Shader
Pay over x402

DocsGuides22 of 35 · 12 min read

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

EndpointBody
POST /x402/generate/imageAn image request
POST /x402/generate/videoA video request
POST /x402/generate/voiceA voice request
POST /x402/generate/asset3dA 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.

KindCreditsPerIn dollars
Image40image$0.040
Video100output second$0.100
Voice151,000 characters$0.015
3D asset2003D asset$0.200

#Pay for a generation

HTTP

  1. Install

    The script uses @solana/web3.js and @solana/spl-token.

    Terminal
    npm install @solana/web3.js @solana/spl-token
  2. Save 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 })
  3. Run it

    Terminal
    SHADER_API=<api url> RPC_URL=<rpc url> WALLET=wallet.json node pay-x402.ts
  4. Read 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

pay-with-sdk.ts
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)
Output
done x402 http://127.0.0.1:4710/files/b23e84b2-def9-4905-8b54-1176e58064c5-0.glb

The 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

  1. The 402

    The first request answered 402 with PAYMENT-REQUIRED: scheme exact, the network, the amount in atoms, the USDC mint, payTo, and the sponsor as extra.feePayer.

  2. The payment

    The client built a v0 transaction with the sponsor as fee payer, a compute-unit price of 0 and one transferChecked to the treasury, and signed it as the token owner.

  3. The retry

    The retry carried it in PAYMENT-SIGNATURE. The server checked the transfer, co-signed as fee payer and landed it.

  4. 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 seeWhyNext
PAYMENT_INVALID on a repeated requestThat payment was already usedPay again with a new transaction
PAYMENT_INVALIDThe header is not base64 JSON, or the transfer does not match the requirementBuild the transfer from the 402 you just got
PAYMENT_SETTLEMENT_FAILEDThe payment verified but did not landRead the payer's balance before paying again
A failed job with refundRequired: trueGeneration failed after the payment landedThe 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.

  1. 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), and sshPublicKey.

    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 the PAYMENT-REQUIRED header and the same JSON in the body.

  2. 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 -d

    Against 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.

  3. Sign the open

    Build a transaction for the payment-channels program, CHNLxYvVA28MJP9PrFuDXccuoGXAx7jBacfLEkahyGsX, whose open escrows exactly amount of the USDC mint from your wallet, pays 100% to payTo, uses the 402's withdrawDelay, and carries exactly one Memo instruction equal to extra.memo. Set extra.feePayer as fee payer and sign it with your wallet only; the memo makes your signature commit to this quote.

  4. Retry with the payment

    Send the same request with PAYMENT-SIGNATURE: base64 JSON holding x402Version 2, the requirement you accepted, and the payload below.

  5. Read the answer

    A 200 carries the running instance with its SSH and Jupyter details, the locked rate and a stop token, and PAYMENT-RESPONSE names the open transaction. Keep the stop token. The fields are below.

  6. 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 its payment holding chargedBaseUnits, refundedBaseUnits, the seal and distribute signatures and closedAt. PAYMENT-RESPONSE now carries the charged amount and the distribute signature as transaction.

#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.

Terminal
$ 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            553ZRUFsnNSWgKkXTquxrxFMTCFHMCXNoYDT1Wn1YV8NnaiNe6FMZUkfwo3x5fvUDkvzmcNHK4PZm2Wbcb82bNdn

Run 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.

rent-x402.ts
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)
Output
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 2iCjjo3gTxnW1bfHDVM9u9gaDqm7ACwwbdDE75MqRFrF7boh3ubEckK41921YKe14yQQeS6Y5gzEzbjmJNBp3dto

Ten 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

FieldIn the answer aboveWhat it is
schemeuptoThe payer escrows a ceiling and is charged the seconds used
networkthe local ledger's idThe same CAIP-2 id as the generation 402; on mainnet solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp
amount226500The ceiling in USDC atoms: the quoted rate in base units per second times maxSeconds
assetthe USDC mintEPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
payTothe treasury's ownerThe same as the generation 402
maxTimeoutSeconds600maxSeconds plus 300 seconds; the rental has to settle inside it
extra.feePayerthe sponsorThe same fee payer as the generation 402: Shader pays the fees
extra.receiverAuthorizera keyThe key that will sign the settlement voucher for the seconds used
extra.withdrawDelay600Seconds before the payer can take back an unsettled ceiling; equal to maxTimeoutSeconds
extra.tokenProgramthe classic SPL Token programThe token program of the USDC mint
extra.memoa quote idThe quote this payment is for; the open must carry exactly one Memo with it
resource.descriptionthe GPU and its rate"Shader H100 SXM 80GB rental at 0.755 credits/s, up to 300 s"
extensions.rentalQuote.expiresAta UTC timeWhen 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

FieldWhat it is
fromYour wallet
maxAmountThe ceiling you authorize, equal to amount
depositThe atoms the open escrows, also equal to amount
channelIdThe channel account the open creates
authorizedSignerThe key allowed to sign your side of the channel
nonceA number you choose, so each channel is new
validAfter, expiresAtUnix times between which the authorization is valid
openSlotThe slot the open was built at
openTransactionThe signed open, base64

The full schema is under X402UptoPayload.

#The answer

FieldWhat it is
instanceThe rental, running, with ssh (host, port, user, command) and jupyter (URL and token), and payment with the channel, the ceiling and the open signature
lockedRateBaseUnitsPerSecondThe rate locked for this rental, base units per second
stopTokenshdrstop_…, shown once: the bearer token that stops this rental
PAYMENT-RESPONSEsuccess, 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 answerWhat it is
instance.statestopped
instance.payment.chargedBaseUnitsThe charge: seconds run times the locked rate, never more than the ceiling
instance.payment.refundedBaseUnitsThe deposit less the charge, back in your wallet
instance.payment.sealSignature, distributeSignatureThe transactions that sealed the channel and paid it out
instance.payment.closedAtWhen the channel closed
PAYMENT-RESPONSEamount 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.

  1. 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: amount is the rental's locked rate times maxSeconds, extra.memo is a new extension id, and maxTimeoutSeconds covers the seconds left on the open channels, the new seconds and a 300-second close margin.

  2. Pay it

    Sign an open for that ceiling from the same wallet that paid the rental, with the new memo, and retry with PAYMENT-SIGNATURE as at launch. The 200 carries the instance, its payment.channels now listing both, and PAYMENT-RESPONSE for the new open.

  3. 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

  1. Quote

    Shader picked one machine for the GPU at its live price and held the quote for two minutes.

  2. Verify

    It checked the open against the quote: only the instructions the scheme allows, the payment-channels program, the USDC mint and token program, the withdrawDelay, a 100% distribution to payTo, a deposit equal to the ceiling, and one Memo naming a live, unused quote.

  3. Open

    Only then did the fee payer sign and submit it. The channel escrowed the ceiling.

  4. Launch

    Once the open confirmed, 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.

  5. Stop

    At the stop, Shader stopped the machine at the provider first, so nothing ran after the charge was fixed.

  6. 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.

  7. Seal and distribute

    Shader, as payee and fee payer, sent settle_and_seal with the voucher and then distribute: payTo received 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.reasonWhyNext
quote_expiredThe quote's two minutes ran outSign an open for the fresh quote
invalid_upto_svm_channel_already_openThat payment was already usedOpen a new channel for the fresh quote
invalid_upto_svm_payload_deposit_not_ceilingThe deposit is not the quoted ceilingEscrow exactly amount
invalid_upto_svm_payment_requirementspayTo or another field does not match the quoteBuild from the 402 you just got
invalid_upto_svm_payload_open_transactionThe open breaks the policy, for example a missing or wrong memoOne Memo equal to extra.memo, and only the allowed instructions
GPU_UNAVAILABLENo machine of that model can be quoted nowTry another model or later
NOT_FOUNDThe GPU id is not in the catalogUse an id from GET /catalog/gpus
401 on the stop or the extendThe stop token is wrong or missingUse the token from the paid answer, or sign in as the payer to stop
INSTANCE_NOT_EXTENDABLEThe rental is not runningRent again
EXTENSION_PENDINGAn extension is already paid and not in use yetUse it before asking for another
PAYMENT_INVALID, invalid_upto_svm_payload_payer_mismatchThe extension was paid from another walletPay from the wallet that paid the rental