|
| 1 | +import { |
| 2 | + type Address, |
| 3 | + appendTransactionMessageInstructions, |
| 4 | + createDefaultRpcTransport, |
| 5 | + createSolanaRpcFromTransport, |
| 6 | + createTransactionMessage, |
| 7 | + getBase64EncodedWireTransaction, |
| 8 | + isSolanaError, |
| 9 | + mainnet, |
| 10 | + partiallySignTransactionMessageWithSigners, |
| 11 | + pipe, |
| 12 | + prependTransactionMessageInstruction, |
| 13 | + SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, |
| 14 | + setTransactionMessageFeePayer, |
| 15 | + setTransactionMessageLifetimeUsingBlockhash, |
| 16 | + type TransactionSigner, |
| 17 | +} from "@solana/kit"; |
| 18 | +import { |
| 19 | + getSetComputeUnitLimitInstruction, |
| 20 | + setTransactionMessageComputeUnitPrice, |
| 21 | +} from "@solana-program/compute-budget"; |
| 22 | +import { TOKEN_PROGRAM_ADDRESS } from "@solana-program/token"; |
| 23 | +import { |
| 24 | + fetchMint, |
| 25 | + findAssociatedTokenPda, |
| 26 | + getTransferCheckedInstruction, |
| 27 | + TOKEN_2022_PROGRAM_ADDRESS, |
| 28 | +} from "@solana-program/token-2022"; |
| 29 | +import type { PaymentRequirements, SchemeNetworkClient } from "@x402/core/types"; |
| 30 | + |
| 31 | +const MEMO_PROGRAM_ADDRESS: Address = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr" as Address; |
| 32 | +const COMPUTE_UNIT_LIMIT = 20_000; |
| 33 | +const COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1; |
| 34 | + |
| 35 | +const USDC_MINT: Address = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" as Address; |
| 36 | +const USDC_DECIMALS = 6; |
| 37 | + |
| 38 | +// Public no-auth Solana mainnet RPCs used as failover chain. |
| 39 | +// On 429 from one endpoint the transport immediately tries the next. |
| 40 | +// |
| 41 | +// api.mainnet.solana.com (Solana Labs load-balanced cluster): |
| 42 | +// 100 req/10s per IP, 40 req/10s per method, 100 MB/30s bandwidth cap. |
| 43 | +// (api.mainnet-beta.solana.com is an alias for the same cluster - |
| 44 | +// requests to either count against the same rate limit.) |
| 45 | +// |
| 46 | +// public.rpc.solanavibestation.com (community, self-hosted in Atlanta): |
| 47 | +// 5 RPS general limit. 100% uptime last 90 days per status page. |
| 48 | +const MAINNET_RPC_URLS = [ |
| 49 | + "https://api.mainnet.solana.com", |
| 50 | + "https://public.rpc.solanavibestation.com", |
| 51 | +]; |
| 52 | + |
| 53 | +type Transport = ReturnType<typeof createDefaultRpcTransport>; |
| 54 | + |
| 55 | +/** |
| 56 | + * Create a failover transport that tries each RPC in order. |
| 57 | + * On 429 from one endpoint, immediately tries the next instead of waiting. |
| 58 | + * Each transport gets its own coalescing via createDefaultRpcTransport. |
| 59 | + */ |
| 60 | +function createFailoverTransport(urls: string[]) { |
| 61 | + const transports = urls.map((url) => createDefaultRpcTransport({ url })); |
| 62 | + const failover: Transport = (async (config) => { |
| 63 | + let lastError: unknown; |
| 64 | + for (const transport of transports) { |
| 65 | + try { |
| 66 | + return await transport(config); |
| 67 | + } catch (e) { |
| 68 | + lastError = e; |
| 69 | + if ( |
| 70 | + isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && |
| 71 | + e.context.statusCode === 429 |
| 72 | + ) { |
| 73 | + continue; |
| 74 | + } |
| 75 | + throw e; |
| 76 | + } |
| 77 | + } |
| 78 | + throw lastError; |
| 79 | + }) as Transport; |
| 80 | + return failover; |
| 81 | +} |
| 82 | + |
| 83 | +function createRpcClient(customRpcUrl?: string) { |
| 84 | + const urls = customRpcUrl ? [customRpcUrl, ...MAINNET_RPC_URLS] : MAINNET_RPC_URLS; |
| 85 | + return createSolanaRpcFromTransport(createFailoverTransport(urls.map((u) => mainnet(u)))); |
| 86 | +} |
| 87 | + |
| 88 | +/** |
| 89 | + * Optimized ExactSvmScheme that replaces upstream @x402/svm to prevent |
| 90 | + * RPC rate-limit failures on parallel payments. |
| 91 | + * |
| 92 | + * Two optimizations over upstream: |
| 93 | + * 1. Shared RPC client - @solana/kit's built-in request coalescing |
| 94 | + * merges identical getLatestBlockhash calls in the same tick into 1. |
| 95 | + * 2. Hardcoded USDC - skips fetchMint RPC call for USDC (immutable data). |
| 96 | + */ |
| 97 | +export class OptimizedSvmScheme implements SchemeNetworkClient { |
| 98 | + readonly scheme = "exact"; |
| 99 | + private readonly rpc: ReturnType<typeof createRpcClient>; |
| 100 | + |
| 101 | + constructor( |
| 102 | + private readonly signer: TransactionSigner, |
| 103 | + config?: { rpcUrl?: string }, |
| 104 | + ) { |
| 105 | + this.rpc = createRpcClient(config?.rpcUrl); |
| 106 | + } |
| 107 | + |
| 108 | + async createPaymentPayload(x402Version: number, paymentRequirements: PaymentRequirements) { |
| 109 | + const rpc = this.rpc; |
| 110 | + |
| 111 | + const asset = paymentRequirements.asset as Address; |
| 112 | + |
| 113 | + let tokenProgramAddress: Address; |
| 114 | + let decimals: number; |
| 115 | + if (asset === USDC_MINT) { |
| 116 | + tokenProgramAddress = TOKEN_PROGRAM_ADDRESS; |
| 117 | + decimals = USDC_DECIMALS; |
| 118 | + } else { |
| 119 | + const tokenMint = await fetchMint(rpc, asset); |
| 120 | + tokenProgramAddress = tokenMint.programAddress; |
| 121 | + if ( |
| 122 | + tokenProgramAddress !== TOKEN_PROGRAM_ADDRESS && |
| 123 | + tokenProgramAddress !== TOKEN_2022_PROGRAM_ADDRESS |
| 124 | + ) { |
| 125 | + throw new Error("Asset was not created by a known token program"); |
| 126 | + } |
| 127 | + decimals = tokenMint.data.decimals; |
| 128 | + } |
| 129 | + |
| 130 | + const [sourceATA] = await findAssociatedTokenPda({ |
| 131 | + mint: asset, |
| 132 | + owner: this.signer.address, |
| 133 | + tokenProgram: tokenProgramAddress, |
| 134 | + }); |
| 135 | + |
| 136 | + const [destinationATA] = await findAssociatedTokenPda({ |
| 137 | + mint: asset, |
| 138 | + owner: paymentRequirements.payTo as Address, |
| 139 | + tokenProgram: tokenProgramAddress, |
| 140 | + }); |
| 141 | + |
| 142 | + const transferIx = getTransferCheckedInstruction( |
| 143 | + { |
| 144 | + source: sourceATA, |
| 145 | + mint: asset, |
| 146 | + destination: destinationATA, |
| 147 | + authority: this.signer, |
| 148 | + amount: BigInt(paymentRequirements.amount), |
| 149 | + decimals, |
| 150 | + }, |
| 151 | + { programAddress: tokenProgramAddress }, |
| 152 | + ); |
| 153 | + |
| 154 | + const feePayer = paymentRequirements.extra?.feePayer as Address; |
| 155 | + if (!feePayer) { |
| 156 | + throw new Error("feePayer is required in paymentRequirements.extra for SVM transactions"); |
| 157 | + } |
| 158 | + |
| 159 | + const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); |
| 160 | + |
| 161 | + const nonce = crypto.getRandomValues(new Uint8Array(16)); |
| 162 | + const memoIx = { |
| 163 | + programAddress: MEMO_PROGRAM_ADDRESS, |
| 164 | + accounts: [] as const, |
| 165 | + data: new TextEncoder().encode( |
| 166 | + Array.from(nonce) |
| 167 | + .map((b) => b.toString(16).padStart(2, "0")) |
| 168 | + .join(""), |
| 169 | + ), |
| 170 | + }; |
| 171 | + |
| 172 | + const tx = pipe( |
| 173 | + createTransactionMessage({ version: 0 }), |
| 174 | + (tx) => setTransactionMessageComputeUnitPrice(COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx), |
| 175 | + (tx) => setTransactionMessageFeePayer(feePayer, tx), |
| 176 | + (tx) => |
| 177 | + prependTransactionMessageInstruction( |
| 178 | + getSetComputeUnitLimitInstruction({ units: COMPUTE_UNIT_LIMIT }), |
| 179 | + tx, |
| 180 | + ), |
| 181 | + (tx) => appendTransactionMessageInstructions([transferIx, memoIx], tx), |
| 182 | + (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), |
| 183 | + ); |
| 184 | + |
| 185 | + const signedTransaction = await partiallySignTransactionMessageWithSigners(tx); |
| 186 | + |
| 187 | + return { |
| 188 | + x402Version, |
| 189 | + payload: { transaction: getBase64EncodedWireTransaction(signedTransaction) }, |
| 190 | + }; |
| 191 | + } |
| 192 | +} |
0 commit comments