From f3449e91b986c8298009455f1089581b83b05cdb Mon Sep 17 00:00:00 2001 From: Ben Stokes Date: Tue, 24 Nov 2026 16:29:07 +0000 Subject: [PATCH] fix: check the platform wallet can pay before building a payout batch Building a batch now refuses, with a clear error and the payouts left pending, when the platform wallet: - is itself a payout destination - holds less USDC than the batch total (402 insufficient_funds) - has too little SOL for the fee plus rent for new token accounts The sender's wallet and USDC account are read in the same getMultipleAccountsInfo call as the recipients, so this adds no RPC requests. Previously these batches were signed, rejected by Solana's preflight, and recorded as failed payouts. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/modules/chains/Solana.spec.ts | 134 ++++++++++++++++++- apps/api/src/modules/chains/Solana.ts | 54 +++++++- apps/docs/src/app/pages/docs/data/payouts.ts | 2 +- 3 files changed, 185 insertions(+), 5 deletions(-) diff --git a/apps/api/src/modules/chains/Solana.spec.ts b/apps/api/src/modules/chains/Solana.spec.ts index b773708..ba201c5 100644 --- a/apps/api/src/modules/chains/Solana.spec.ts +++ b/apps/api/src/modules/chains/Solana.spec.ts @@ -1,10 +1,17 @@ import { + AccountInfo, Keypair, PublicKey, SystemProgram, Transaction, } from '@solana/web3.js'; -import { ValidateSponsoredCheckoutTransaction } from './Solana'; +import { + ACCOUNT_SIZE, + AccountLayout, + AccountState, + TOKEN_PROGRAM_ID, +} from '@solana/spl-token'; +import { Solana, ValidateSponsoredCheckoutTransaction } from './Solana'; jest.mock('@solana/kit', () => ({})); jest.mock('@solana/kit-plugin-rpc', () => ({})); @@ -126,3 +133,128 @@ describe('Solana sponsored checkout transactions', () => { ).toThrow('Sponsored checkout transaction signatures are invalid'); }); }); + +describe('Solana batch payout wallet checks', () => { + const sender = Keypair.generate().publicKey; + const recipient = Keypair.generate().publicKey.toBase58(); + const LAMPORTS = 10_000_000; + + function WalletInfo(lamports: number): AccountInfo { + return { + data: Buffer.alloc(0), + executable: false, + lamports, + owner: SystemProgram.programId, + }; + } + + function UsdcInfo(solana: Solana, cents: number): AccountInfo { + const data = Buffer.alloc(ACCOUNT_SIZE); + AccountLayout.encode( + { + mint: new PublicKey(solana.GetUSDCMintAddress()), + owner: sender, + amount: BigInt(cents) * BigInt(10000), + delegateOption: 0, + delegate: PublicKey.default, + state: AccountState.Initialized, + isNativeOption: 0, + isNative: BigInt(0), + delegatedAmount: BigInt(0), + closeAuthorityOption: 0, + closeAuthority: PublicKey.default, + }, + data + ); + return { + data, + executable: false, + lamports: 2_039_280, + owner: TOKEN_PROGRAM_ID, + }; + } + + /** A Solana whose RPC returns the given sender wallet, sender USDC account and recipient account. */ + function StubSolana( + walletLamports: number | null, + usdcCents: number | null, + recipientExists = true + ) { + const solana = new Solana(); + const getMultipleAccountsInfo = jest + .fn() + .mockResolvedValue([ + walletLamports === null ? null : WalletInfo(walletLamports), + usdcCents === null ? null : UsdcInfo(solana, usdcCents), + recipientExists ? UsdcInfo(solana, 0) : null, + ]); + Object.assign(solana.connection, { + getMultipleAccountsInfo, + getLatestBlockhash: jest.fn().mockResolvedValue({ + blockhash: Keypair.generate().publicKey.toBase58(), + lastValidBlockHeight: 100, + }), + getFeeForMessage: jest.fn().mockResolvedValue({ value: 5000 }), + }); + return { solana, getMultipleAccountsInfo }; + } + + const Build = (solana: Solana, destinationAddress = recipient) => + solana.BuildBatchPayoutTransaction(sender.toBase58(), [ + { destinationAddress, amountInCents: 5800 }, + ]); + + it('builds with a single account read when the wallet can pay', async () => { + const { solana, getMultipleAccountsInfo } = StubSolana(LAMPORTS, 5821); + + const result = await Build(solana); + + expect(result.recipients_count).toBe(1); + expect(getMultipleAccountsInfo).toHaveBeenCalledTimes(1); + }); + + it('rejects a destination that is the platform wallet itself', async () => { + const { solana, getMultipleAccountsInfo } = StubSolana(LAMPORTS, 5821); + + await expect(Build(solana, sender.toBase58())).rejects.toMatchObject({ + statusCode: 400, + message: expect.stringContaining('is the platform wallet'), + }); + expect(getMultipleAccountsInfo).not.toHaveBeenCalled(); + }); + + it('rejects when the platform wallet holds too little USDC', async () => { + const { solana } = StubSolana(LAMPORTS, 1000); + + await expect(Build(solana)).rejects.toMatchObject({ + statusCode: 402, + type: 'insufficient_funds', + message: expect.stringContaining( + 'holds 10.00 USDC, but this payout needs 58.00 USDC' + ), + }); + }); + + it('rejects when the platform wallet has no USDC account', async () => { + const { solana } = StubSolana(LAMPORTS, null); + + await expect(Build(solana)).rejects.toMatchObject({ statusCode: 402 }); + }); + + it('rejects when the platform wallet has no SOL for fees', async () => { + const { solana } = StubSolana(null, 5821); + + await expect(Build(solana)).rejects.toMatchObject({ + statusCode: 400, + message: expect.stringContaining('needs at least 0.000005 SOL'), + }); + }); + + it('counts the rent for recipient token accounts it must create', async () => { + const { solana } = StubSolana(1_000_000, 5821, false); + + await expect(Build(solana)).rejects.toMatchObject({ + message: expect.stringContaining('needs at least 0.00204428 SOL'), + }); + }); +}); diff --git a/apps/api/src/modules/chains/Solana.ts b/apps/api/src/modules/chains/Solana.ts index baa81de..8ee9efd 100644 --- a/apps/api/src/modules/chains/Solana.ts +++ b/apps/api/src/modules/chains/Solana.ts @@ -22,6 +22,7 @@ import { createTransferInstruction, createTransferCheckedInstruction, createAssociatedTokenAccountIdempotentInstruction, + unpackAccount, TOKEN_PROGRAM_ID, } from '@solana/spl-token'; import { createHash } from 'crypto'; @@ -55,6 +56,7 @@ import { GetCheckoutFeePayerSecretKey, RequireSubscriptionOperatorSecretKey, } from '../AppConfig'; +import { AppError } from '../../utils/AppError'; /** * Derive a deterministic on-chain planId (u64) from an off-chain price id string. @@ -173,6 +175,13 @@ const INITIAL_RETRY_DELAY_MS = 2000; // Conservative limit to ensure transactions don't exceed size limit. export const MAX_BATCH_RECIPIENTS = 10; +/** Rent-exempt deposit for a new token account (165 bytes), paid by the sender. */ +const TOKEN_ACCOUNT_RENT_LAMPORTS = 2_039_280; + +/** USDC atomic units (6 decimals) as a 2-decimal string. */ +const FormatUsdc = (atomic: bigint): string => + (Number(atomic) / 1_000_000).toFixed(2); + /** Sleep helper */ const Sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -319,12 +328,38 @@ export class Solana { }) ); - // Batch fetch all token account info in a single RPC call + if (recipients.some((r) => r.destinationAddress === senderPublicKey)) { + throw new AppError( + `The payout destination is the platform wallet ${senderPublicKey} itself. Choose a different destination wallet.`, + 400, + 'invalid_request_error' + ); + } + + // One RPC call for the sender's wallet and USDC account plus every recipient token account const tokenAccountKeys = recipientData.map((r) => r.tokenAccount); - const accountInfos = await this.WithRetry(() => - this.connection.getMultipleAccountsInfo(tokenAccountKeys) + const [senderInfo, senderTokenInfo, ...accountInfos] = await this.WithRetry( + () => + this.connection.getMultipleAccountsInfo([ + sender, + senderTokenAccount, + ...tokenAccountKeys, + ]) ); + const senderUsdc = senderTokenInfo + ? unpackAccount(senderTokenAccount, senderTokenInfo).amount + : BigInt(0); + if (senderUsdc < BigInt(totalAmount) * BigInt(10000)) { + throw new AppError( + `Platform wallet ${senderPublicKey} holds ${FormatUsdc( + senderUsdc + )} USDC, but this payout needs ${(totalAmount / 100).toFixed(2)} USDC.`, + 402, + 'insufficient_funds' + ); + } + // Create Transaction const transaction = new Transaction(); @@ -383,6 +418,19 @@ export class Solana { } SOL)` ); + const accountsToCreate = accountInfos.filter((info) => !info).length; + const requiredLamports = + (fee.value || 0) + accountsToCreate * TOKEN_ACCOUNT_RENT_LAMPORTS; + if ((senderInfo?.lamports ?? 0) < requiredLamports) { + throw new AppError( + `Platform wallet ${senderPublicKey} needs at least ${ + requiredLamports / 1_000_000_000 + } SOL to pay network fees. Send SOL to it and try again.`, + 400, + 'invalid_request_error' + ); + } + // Serialize the unsigned transaction const serializedTransaction = transaction .serialize({ requireAllSignatures: false }) diff --git a/apps/docs/src/app/pages/docs/data/payouts.ts b/apps/docs/src/app/pages/docs/data/payouts.ts index bdc47d3..5b4f355 100644 --- a/apps/docs/src/app/pages/docs/data/payouts.ts +++ b/apps/docs/src/app/pages/docs/data/payouts.ts @@ -973,7 +973,7 @@ export const PAYOUTS_BUILD_PAGE: DocPage = { { type: 'heading', level: 2, text: 'Returns' }, { type: 'paragraph', - text: 'Returns a payout_batch_build object containing the unsigned transaction (base64-encoded), the blockhash, estimated fees, and the payout objects included in the batch.', + text: 'Returns a payout_batch_build object containing the unsigned transaction (base64-encoded), the blockhash, estimated fees, and the payout objects included in the batch. In live mode, this call raises an error and leaves the payouts pending if the platform wallet lacks the USDC for the batch or the SOL for network fees, or if a destination is the platform wallet itself.', html: true, }, ],