Pay over x402
Pay for a generation or rent a GPU in USDC from a wallet with no account, over HTTP, the CLI, the SDK or MCP.
x402 prices a request in its 402 answer and takes payment in the retry. You need USDC in a Solana wallet, enough for the price; no SOL, no account and no agent key.
#Endpoints and prices
| Endpoint | Body |
|---|---|
POST /x402/generate/image | An image request |
POST /x402/generate/video | A video request |
POST /x402/generate/voice | A voice request |
POST /x402/generate/asset3d | A 3D asset request |
The bodies are the generation requests of the API, and the price is the generation's price in USDC atoms, 1,000 to a credit.
| Kind | Credits | Per | In dollars |
|---|---|---|---|
| Image | 40 | image | $0.040 |
| Video | 100 | output second | $0.100 |
| Voice | 15 | 1,000 characters | $0.015 |
| 3D asset | 200 | 3D asset | $0.200 |
#Pay for a generation
HTTP
Install
The script uses
@solana/web3.jsand@solana/spl-token.Terminal npm install @solana/web3.js @solana/spl-tokenSave the script
It pays for one 3D asset: it asks, builds the payment from the 402, and retries with it.
pay-x402.ts import { readFileSync } from 'node:fs' import { ComputeBudgetProgram, Connection, Keypair, PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js' import { createTransferCheckedInstruction, getAssociatedTokenAddressSync, getMint } from '@solana/spl-token' const api = process.env.SHADER_API! const connection = new Connection(process.env.RPC_URL!, 'confirmed') const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(process.env.WALLET!, 'utf8')))) const decode = (header: string) => JSON.parse(Buffer.from(header, 'base64').toString('utf8')) const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64') const url = `${api}/x402/generate/asset3d` const body = JSON.stringify({ kind: 'asset3d', prompt: 'A small wooden chair', options: { format: 'glb' } }) const headers = { 'content-type': 'application/json' } // 1. Ask without paying: the answer is 402 with the price in PAYMENT-REQUIRED. const challenge = await fetch(url, { method: 'POST', headers, body }) const required = decode(challenge.headers.get('payment-required')!) const accepted = required.accepts[0] console.log(challenge.status, accepted) // 2. Pay: one USDC transferChecked to the treasury, with Shader's sponsor as fee payer. const mint = new PublicKey(accepted.asset) const tokenProgram = (await connection.getAccountInfo(mint))!.owner const { decimals } = await getMint(connection, mint, 'confirmed', tokenProgram) const from = getAssociatedTokenAddressSync(mint, wallet.publicKey, false, tokenProgram) const to = getAssociatedTokenAddressSync(mint, new PublicKey(accepted.payTo), true, tokenProgram) const { blockhash } = await connection.getLatestBlockhash('confirmed') const payment = new VersionedTransaction(new TransactionMessage({ payerKey: new PublicKey(accepted.extra.feePayer), recentBlockhash: blockhash, instructions: [ ComputeBudgetProgram.setComputeUnitLimit({ units: 50_000 }), ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 0 }), createTransferCheckedInstruction(from, mint, to, wallet.publicKey, BigInt(accepted.amount), decimals, [], tokenProgram), ], }).compileToV0Message()) payment.sign([wallet]) // 3. Retry with PAYMENT-SIGNATURE: the server co-signs, settles, generates and answers 200. const signature = encode({ x402Version: 2, resource: required.resource, accepted, payload: { transaction: Buffer.from(payment.serialize()).toString('base64') } }) const paid = await fetch(url, { method: 'POST', headers: { ...headers, 'payment-signature': signature }, body }) const { job } = await paid.json() console.log(paid.status, decode(paid.headers.get('payment-response')!)) console.log({ id: job.id, state: job.state, result: job.result })Run it
Terminal SHADER_API=<api url> RPC_URL=<rpc url> WALLET=wallet.json node pay-x402.tsRead the output
A run against a local Shader printed the 402 requirement, then the 200 with its settlement and the job:
Output 402 { scheme: 'exact', network: 'solana:A3PLXRKeM6ZGoGvf13FALFSfMoMRaQmUXYnRV7qwMaAi', amount: '200000', asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', payTo: 'GgAYZpkuW4qgyFByDDoN7NHjzkRe4xbce49MiXhZX2XQ', maxTimeoutSeconds: 60, extra: { feePayer: '9E5pMr8vpge92LqC5nx56gEnRd9ZtdUgNTjme1ktgURv', paymentFlow: 'upfront', transactionVersions: [ 0 ], computeUnitPriceMicroLamports: '0' } } 200 { success: true, transaction: '44tMUnyLrT7Bt195PeHSMjYAA1y2wU2GaEvcPx13GKiStyuFeTwcLFibUx3G8CaKVPxW9iG6L3NtPTDtTdHk6Gww', network: 'solana:A3PLXRKeM6ZGoGvf13FALFSfMoMRaQmUXYnRV7qwMaAi', payer: '6Rxpu2Je2eQJhQxt7Y7FsdeYyDzCAtMJ5do72uXxvxdQ' } { id: 'ee26d629-697d-40ad-b91c-ec634d7b7a63', state: 'done', result: { url: 'http://127.0.0.1:4710/files/ee26d629-697d-40ad-b91c-ec634d7b7a63-0.glb', mimeType: 'model/gltf-binary', sizeBytes: '884' } }
SDK
import { readFileSync } from 'node:fs'
import { Keypair } from '@solana/web3.js'
import { Shader } from '@shader/sdk'
const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(process.env.WALLET!, 'utf8'))))
const shader = new Shader({ baseUrl: process.env.SHADER_API_URL, rpcUrl: process.env.RPC_URL })
const { job } = await shader.x402.generate('asset3d', { prompt: 'a small wooden chair' }, {
signer: payer,
maxAmountBaseUnits: '200000',
})
console.log(job.state, job.paymentMode, job.result?.url)done x402 http://127.0.0.1:4710/files/b23e84b2-def9-4905-8b54-1176e58064c5-0.glbThe SDK checks the mint against the API's configuration and the network against your RPC, signs once, and refuses a price above maxAmountBaseUnits.
#What happened
The 402
The first request answered 402 with
PAYMENT-REQUIRED: schemeexact, the network, the amount in atoms, the USDC mint,payTo, and the sponsor asextra.feePayer.The payment
The client built a v0 transaction with the sponsor as fee payer, a compute-unit price of 0 and one
transferCheckedto the treasury, and signed it as the token owner.The retry
The retry carried it in
PAYMENT-SIGNATURE. The server checked the transfer, co-signed as fee payer and landed it.The file
The server generated the file and answered 200 with the job and
PAYMENT-RESPONSE.
amount above is 200 credits in atoms. The network id is the local ledger's; on mainnet it is solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp. The payment transaction is 429 bytes signed and uses 405 compute units.
#The receipt
PAYMENT-RESPONSE holds the settlement signature, the network and the payer. The payment is listed as an x402 receipt under the payer's wallet, linked to the job.
#Afterwards
The file is at the job's result.url. A payment is used once; send a new one for the next request.
#If it fails
| What you see | Why | Next |
|---|---|---|
PAYMENT_INVALID on a repeated request | That payment was already used | Pay again with a new transaction |
PAYMENT_INVALID | The header is not base64 JSON, or the transfer does not match the requirement | Build the transfer from the 402 you just got |
PAYMENT_SETTLEMENT_FAILED | The payment verified but did not land | Read the payer's balance before paying again |
A failed job with refundRequired: true | Generation failed after the payment landed | The payment is held for a refund by the operator |
#Rent a GPU over x402
GPU rentals use the upto scheme: the agent escrows a ceiling in a payment channel and will be charged only the seconds the machine ran (x402). The 402 quotes one machine at its live price, and that rate is locked for the rental. The paid retry opens the channel and launches the machine. At stop, Shader charges the seconds run at that rate, never more than the ceiling, and the channel returns the rest to your wallet.
Ask for a quote
Send the GPU's catalog id in the path, and optionally
maxSeconds, the longest the rental may run (3,600 by default and at most), andsshPublicKey.Terminal curl -i -X POST $SHADER_API/x402/rent/h100-sxm-80gb \ -H 'content-type: application/json' \ -d '{"maxSeconds":300}'The answer is
402 Payment Required, with the quote in thePAYMENT-REQUIREDheader and the same JSON in the body.Decode the header
Terminal curl -s -X POST $SHADER_API/x402/rent/h100-sxm-80gb -H 'content-type: application/json' -d '{"maxSeconds":300}' -D - -o /dev/null \ | grep -i '^payment-required' | sed 's/^[^:]*: //' | tr -d '\r' | base64 -dAgainst a local Shader it decoded to:
PAYMENT-REQUIRED { "x402Version": 2, "error": "PAYMENT-SIGNATURE header is required", "resource": { "url": "http://127.0.0.1:4710/x402/rent/h100-sxm-80gb", "description": "Shader H100 SXM 80GB rental at 0.755 credits/s, up to 300 s", "mimeType": "application/json", "serviceName": "Shader" }, "accepts": [ { "scheme": "upto", "network": "solana:36aDQWtw54ZQn8W1iiWo6cYYKfZSZeW4tc5MDpNQpHeS", "amount": "226500", "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "payTo": "GgAYZpkuW4qgyFByDDoN7NHjzkRe4xbce49MiXhZX2XQ", "maxTimeoutSeconds": 600, "extra": { "feePayer": "9E5pMr8vpge92LqC5nx56gEnRd9ZtdUgNTjme1ktgURv", "receiverAuthorizer": "EV6tE5VHwaNoYapTunB4hXAm4f63NRZqGXEubJ4AnXrs", "withdrawDelay": 600, "tokenProgram": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "memo": "369780e6-e242-4727-8460-26f2a46882fc" } } ], "extensions": { "rentalQuote": { "expiresAt": "2026-11-28T19:58:30.676Z" } } }The quote is for one machine at 0.755 credits a second, so 300 seconds is a ceiling of 226,500 atoms. The quote expires at
extensions.rentalQuote.expiresAt, two minutes after it was made.Sign the open
Build a transaction for the payment-channels program,
CHNLxYvVA28MJP9PrFuDXccuoGXAx7jBacfLEkahyGsX, whoseopenescrows exactlyamountof the USDC mint from your wallet, pays 100% topayTo, uses the 402'swithdrawDelay, and carries exactly one Memo instruction equal toextra.memo. Setextra.feePayeras fee payer and sign it with your wallet only; the memo makes your signature commit to this quote.Retry with the payment
Send the same request with
PAYMENT-SIGNATURE: base64 JSON holdingx402Version2, the requirement youaccepted, and thepayloadbelow.Read the answer
A 200 carries the running instance with its SSH and Jupyter details, the locked rate and a stop token, and
PAYMENT-RESPONSEnames theopentransaction. Keep the stop token. The fields are below.Stop it
When the work is done, stop the rental with the stop token as a bearer token. The payer's own wallet session works too, and so does Stop on the instance page when the payer is signed in.
Terminal curl -X POST $SHADER_API/instances/<instance>/stop \\ -H "authorization: Bearer $STOP_TOKEN"The answer is the instance,
stopped, with itspaymentholdingchargedBaseUnits,refundedBaseUnits, the seal and distribute signatures andclosedAt.PAYMENT-RESPONSEnow carries the chargedamountand the distribute signature astransaction.
#With the CLI, the SDK or MCP
The same rental, with the quote, the open and the stop done for you. None of them needs an account or an agent token, and none sends your key anywhere.
CLI
--wallet is a keypair file; the CLI signs the open with it locally. It prints the quote first, and refuses before signing if the ceiling is above --max-usd. It keeps the stop token in your config folder, readable only by you, for extend and stop.
$ shader rent h100-sxm-80gb --x402 --max-seconds 120 --wallet wallet.json --max-usd 0.25 --ssh-key id_ed25519.pub
Locked rate 0.564 credits/s ($2.0304/h)
Ceiling 67.68 credits ($0.06768) for 120 s.
INSTANCE GPU STATE
6569c57e-ed79-4b8c-a49f-24700a108663 H100 SXM 80GB running
ssh shader@127.0.0.1 -p 4840
Jupyter http://127.0.0.1:4860/lab?token=<token>
$ ssh -p 4840 shader@127.0.0.1 'nproc; python3 --version'
14
Python 3.12.16
$ shader stop 6569c57e-ed79-4b8c-a49f-24700a108663
Rental 6569c57e-ed79-4b8c-a49f-24700a108663 stopped
CHANNEL CHARGED CREDITS REFUNDED CREDITS RECEIPT SIGNATURE
1 4.512 63.168 553ZRUFsnNSWgKkXTquxrxFMTCFHMCXNoYDT1Wn1YV8NnaiNe6FMZUkfwo3x5fvUDkvzmcNHK4PZm2Wbcb82bNdnRun against a local Shader. The rental ran 8 seconds at the locked rate: 4.512 credits charged and the rest of the 67.68-credit ceiling refunded. shader extend <instance> --seconds <n> adds a channel before the ceiling is reached.
SDK
signer is a public key and a function that signs a transaction, so the SDK never holds your key.
import { readFileSync } from 'node:fs'
import { Keypair, type VersionedTransaction } from '@solana/web3.js'
import { Shader } from '@shader/sdk'
const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(process.env.WALLET!, 'utf8'))))
const signer = {
publicKey: wallet.publicKey,
async signTransaction(transaction: VersionedTransaction) {
transaction.sign([wallet])
return transaction
},
}
const shader = new Shader({ baseUrl: process.env.SHADER_API_URL, rpcUrl: process.env.RPC_URL })
const rented = await shader.rentX402({
gpu: 'h100-sxm-80gb',
maxSeconds: 120,
maxUsd: '0.25',
signer,
onQuote: (quote) => console.log('quote', quote.creditsPerSecond, 'credits/s, ceiling', quote.ceilingCredits, 'credits'),
})
console.log('running', rented.instance.id, rented.instance.ssh?.command)
await new Promise((resolve) => setTimeout(resolve, 10_000)) // your work runs here
const stopped = await shader.stopX402({ instanceId: rented.instance.id, stopToken: rented.stopToken })
const payment = stopped.instance.payment
if (payment && 'chargedBaseUnits' in payment) console.log('stopped: charged', payment.chargedBaseUnits, 'refunded', payment.refundedBaseUnits, 'receipt', payment.distributeSignature)quote 0.564 credits/s, ceiling 67.68 credits
running de336dc3-3790-4d8e-a832-2576b458cade ssh shader@127.0.0.1 -p 4840
stopped: charged 5640 refunded 62040 receipt 2iCjjo3gTxnW1bfHDVM9u9gaDqm7ACwwbdDE75MqRFrF7boh3ubEckK41921YKe14yQQeS6Y5gzEzbjmJNBp3dtoTen seconds at 564 base units a second is 5,640 charged; the other 62,040 of the 67,680 ceiling came back. extendX402 adds a channel the same way.
MCP
With no token, an x402-capable client calls rent_gpu, gets the quote as an isError result, and calls again with the payment in _meta["x402/payment"]. Use the MCP server has the steps and the tools.
#Each field of the 402
| Field | In the answer above | What it is |
|---|---|---|
scheme | upto | The payer escrows a ceiling and is charged the seconds used |
network | the local ledger's id | The same CAIP-2 id as the generation 402; on mainnet solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp |
amount | 226500 | The ceiling in USDC atoms: the quoted rate in base units per second times maxSeconds |
asset | the USDC mint | EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v |
payTo | the treasury's owner | The same as the generation 402 |
maxTimeoutSeconds | 600 | maxSeconds plus 300 seconds; the rental has to settle inside it |
extra.feePayer | the sponsor | The same fee payer as the generation 402: Shader pays the fees |
extra.receiverAuthorizer | a key | The key that will sign the settlement voucher for the seconds used |
extra.withdrawDelay | 600 | Seconds before the payer can take back an unsettled ceiling; equal to maxTimeoutSeconds |
extra.tokenProgram | the classic SPL Token program | The token program of the USDC mint |
extra.memo | a quote id | The quote this payment is for; the open must carry exactly one Memo with it |
resource.description | the GPU and its rate | "Shader H100 SXM 80GB rental at 0.755 credits/s, up to 300 s" |
extensions.rentalQuote.expiresAt | a UTC time | When the quote stops being accepted |
The rate is the machine's live price, quoted before launch. The addresses above are a local validator's; on mainnet the fee payer and the receiver authorizer are the operator's keys.
#The payload
| Field | What it is |
|---|---|
from | Your wallet |
maxAmount | The ceiling you authorize, equal to amount |
deposit | The atoms the open escrows, also equal to amount |
channelId | The channel account the open creates |
authorizedSigner | The key allowed to sign your side of the channel |
nonce | A number you choose, so each channel is new |
validAfter, expiresAt | Unix times between which the authorization is valid |
openSlot | The slot the open was built at |
openTransaction | The signed open, base64 |
The full schema is under X402UptoPayload.
#The answer
| Field | What it is |
|---|---|
instance | The rental, running, with ssh (host, port, user, command) and jupyter (URL and token), and payment with the channel, the ceiling and the open signature |
lockedRateBaseUnitsPerSecond | The rate locked for this rental, base units per second |
stopToken | shdrstop_…, shown once: the bearer token that stops this rental |
PAYMENT-RESPONSE | success, payer, network, transaction (the open signature) and amount "0": nothing is charged until the stop |
On the localnet, an H100 SXM rental for 60 seconds was quoted at 475 base units a second, a ceiling of 28,500 atoms. Its open transaction was 779 bytes and used 50,704 compute units.
#The stop and the refund
| In the stop's answer | What it is |
|---|---|
instance.state | stopped |
instance.payment.chargedBaseUnits | The charge: seconds run times the locked rate, never more than the ceiling |
instance.payment.refundedBaseUnits | The deposit less the charge, back in your wallet |
instance.payment.sealSignature, distributeSignature | The transactions that sealed the channel and paid it out |
instance.payment.closedAt | When the channel closed |
PAYMENT-RESPONSE | amount is the charge and transaction the distribute signature |
A rental that reaches its ceiling, its maxSeconds, stops and closes by itself, with the whole ceiling charged and nothing refunded. A second stop answers with the same result and closes nothing twice.
On the localnet, an H100 SXM rental quoted at 564 base units a second ran 120 seconds: 67,680 atoms were charged and 33,840 refunded from a deposit of 101,520. The seal and the distribute went in one transaction of 832 bytes, about 14,400 compute units.
#Extend a rental
A job that needs more time than its ceiling keeps running on a further channel, at the same locked rate.
Ask for more time
Call the extend endpoint with the rental's stop token and the seconds you want to add:
Terminal curl -i -X POST $SHADER_API/x402/rent/<instance>/extend \\ -H "authorization: Bearer $STOP_TOKEN" \\ -H 'content-type: application/json' \\ -d '{"maxSeconds":3600}'The answer is a 402 shaped like the launch one, with no new quote:
amountis the rental's locked rate timesmaxSeconds,extra.memois a new extension id, andmaxTimeoutSecondscovers the seconds left on the open channels, the new seconds and a 300-second close margin.Pay it
Sign an
openfor that ceiling from the same wallet that paid the rental, with the new memo, and retry withPAYMENT-SIGNATUREas at launch. The 200 carries the instance, itspayment.channelsnow listing both, andPAYMENT-RESPONSEfor the newopen.Keep working
Nothing restarts. When the first channel's ceiling is used up, that channel closes for its full ceiling with no refund, and the seconds carry on against the next one.
At stop, the channel in use closes for the seconds it carried, and an extension never used closes with a full refund. Each close has its own x402 receipt, marked channel N of M, and auto-stop moves to the end of the last open ceiling.
On the localnet, an H100 SXM rental quoted at 564 base units a second had a 60-second ceiling and a 60-second extension, and was stopped at 100 seconds. Channel 1 carried 60 seconds: 33,840 atoms charged, nothing refunded. Channel 2 carried 40: 22,560 charged and 11,280 refunded. The extension's open was 779 bytes and each close 832 bytes.
#What happened
Quote
Shader picked one machine for the GPU at its live price and held the quote for two minutes.
Verify
It checked the
openagainst the quote: only the instructions the scheme allows, the payment-channels program, the USDC mint and token program, thewithdrawDelay, a 100% distribution topayTo, a deposit equal to the ceiling, and one Memo naming a live, unused quote.Open
Only then did the fee payer sign and submit it. The channel escrowed the ceiling.
Launch
Once the
openconfirmed, the quoted machine launched at the locked rate. If the launch fails, the channel is sealed with no charge and the whole deposit goes back to the payer.Stop
At the stop, Shader stopped the machine at the provider first, so nothing ran after the charge was fixed.
Voucher
The charge, seconds times the locked rate capped at the ceiling, was signed by the receiver authorizer as a voucher over the channel, the amount and its expiry.
Seal and distribute
Shader, as payee and fee payer, sent
settle_and_sealwith the voucher and thendistribute:payToreceived the charge and your wallet the rest of the deposit.
Shader starts the close two minutes before the voucher's window ends. A channel that reaches its expiry with no voucher refunds the whole deposit.
#The receipt
Each channel's close is a receipt of kind x402 under the payer's wallet, addressed by its distribute transaction and marked channel N of M. It holds the seconds run, the locked rate, the atoms charged and refunded, and the channel id. Receipts lists its fields.
#If it fails
A refused payment answers 402 again with a fresh quote, and error.reason says why. Nothing is opened.
error.reason | Why | Next |
|---|---|---|
quote_expired | The quote's two minutes ran out | Sign an open for the fresh quote |
invalid_upto_svm_channel_already_open | That payment was already used | Open a new channel for the fresh quote |
invalid_upto_svm_payload_deposit_not_ceiling | The deposit is not the quoted ceiling | Escrow exactly amount |
invalid_upto_svm_payment_requirements | payTo or another field does not match the quote | Build from the 402 you just got |
invalid_upto_svm_payload_open_transaction | The open breaks the policy, for example a missing or wrong memo | One Memo equal to extra.memo, and only the allowed instructions |
GPU_UNAVAILABLE | No machine of that model can be quoted now | Try another model or later |
NOT_FOUND | The GPU id is not in the catalog | Use an id from GET /catalog/gpus |
| 401 on the stop or the extend | The stop token is wrong or missing | Use the token from the paid answer, or sign in as the payer to stop |
INSTANCE_NOT_EXTENDABLE | The rental is not running | Rent again |
EXTENSION_PENDING | An extension is already paid and not in use yet | Use it before asking for another |
PAYMENT_INVALID, invalid_upto_svm_payload_payer_mismatch | The extension was paid from another wallet | Pay from the wallet that paid the rental |