Docs

SDK

@breaker/sdk is one function. It returns a fetch that pays x402 services from a budget, and a status read.

npm i https://breaker.to/sdk/breaker-sdk-0.4.0.tgz

An ES module for Node 22. It carries its own types.

breaker()

import { breaker } from '@breaker/sdk'

const agent = breaker({ budget, key })
OptionTypeWhat it is
budgetstringThe budget’s address, from the panel.
keystring, Uint8Array or number[]The agent key’s secret. See below for the forms it takes.
rpcUrlstring, optionalA Solana RPC to read the budget and a recent blockhash from. Without it the SDK uses the public RPC of the network the service names.
apiUrlstring, optionalWhere the SDK tells Breaker which service a payment was for. Defaults to https://api.breaker.to.
maxPaymentstring or bigint, optionalThe most one call may pay, in the mint’s base units.
sessionCallsnumber, optionalHow many calls a session deposits for at a time. 5 without it. See Streamed payments.

It returns { fetch, status }. Nothing is read or sent until you call one of them, so creating an agent is free and synchronous.

The key

FormExample
The base58 string the panel showsprocess.env.BREAKER_AGENT_KEY
The contents of the downloaded file, a JSON array of bytesreadFileSync('agent.json', 'utf8')
Bytes you already holdUint8Array

Each may hold the 64-byte secret key or its 32-byte seed. The key signs payments and the reports below, and it is never sent anywhere.

The RPC

One call reads the budget, its token account and the mint together, at confirmed. Without rpcUrl, the SDK reads from the public endpoint of the network the service’s price names: mainnet, devnet or testnet. Pass your own rpcUrl for an agent that pays often, and always on a local validator.

fetch

agent.fetch(input, init) takes what fetch takes and returns what it returns.

const res = await agent.fetch('https://api.example.com/v1/complete', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ prompt }),
})

What one call does

  1. Sends your request as it is. Any response other than 402 is returned untouched.
  2. Reads the price from the 402: the PAYMENT-REQUIRED header, or the JSON body of an older service. It takes the offer with scheme exact on Solana whose asset is the budget’s mint; with none, a batch-settlement offer, then an upto one, as under Streamed payments.
  3. Reads the budget from the chain, or uses the one it kept, and checks the price against it, in the order of the table under Errors. A failed check throws, and nothing is signed.
  4. Builds the payment, signs it with the agent key, and sends your request again with the payment attached.
  5. Returns the service’s response.
  6. In the background, reads the service’s receipt and tells Breaker which origin the payment went to, so your ledger names the service.

On a cold call the request is retried once, with the payment. The SDK never submits a transaction itself: the service’s facilitator settles the payment and pays its network fee, which is why the agent key needs no SOL. The exact transaction is on the x402 page.

A service paid before

After its first 402, the agent remembers the service’s price by method, origin and path, and keeps the budget it read. The next call to that route goes out with the payment already attached: one request, no RPC read. Each payment lowers the kept allowance until the period ends, and a recent blockhash is reused for 10 seconds.

A 402 in answer means the price changed: the agent drops what it remembered and pays the price in that answer. A price the kept budget would refuse is checked against a fresh read, so the errors below are always decided on the chain’s state.

Per paid call0.1.40.2.0
Requests to the service, warm21
RPC reads, warm20
Time, with 45 ms to the RPC and the service644 to 687 ms439 to 442 ms

Measured with dev/bench.mjs: one budget, one service, twelve paid calls a run, each run a new process.

Bodies

The request is built once and cloned for the second attempt, so a string, a buffer or a FormData body is sent again as it was.

Streamed payments

A service that sells by use offers upto or batch-settlement, and agent.fetch pays it through a payment channel the budget opens, with the same call and the same errors. The deposit counts against the period’s limit when the channel opens; what the service is not paid comes back to the budget. The channel itself is on the x402 page.

A metered call, upto

Each call opens a channel for the offer’s ceiling, signed by the agent key, and the service settles what the call used. The ceiling is checked against the budget and against maxPayment as a price would be. The agent counts the whole ceiling off what it kept; what the call did not use is back in the allowance once the channel is distributed, and status() reads it from the chain.

A session, batch-settlement

  1. The first call to a service opens one channel and deposits for sessionCalls calls at the service’s price: at least the service’s minDeposit, at most what remains of the period’s limit.
  2. Each call after it sends a voucher for the new running total, signed by the agent key. No transaction, no RPC read: one request.
  3. A call the deposit no longer covers tops the channel up by the same rule, in the same request.
  4. If the service answers with a count of its own for the channel, the agent takes that count once and pays again.

A session belongs to the agent that opened it, kept in memory: another breaker() or another process opens a channel of its own. The price of one call is checked against maxPayment; a deposit or a top-up is checked against the budget, and a refused one throws the same errors as a refused payment.

On lines

A budget on lines pays only through channels. The agent takes only streamed offers from it, reads the line of the offer’s payTo, and sizes each deposit to fit that line as well as the budget. A service with no line, or one that sells only by exact, throws NoLine; a deposit above what the line may still take this period throws LineTripped.

100 calls of the same 0.02 inferenceexact, a payment a callOne session
Transactions on chain1003: the open, the service’s claim and its payout
Time per call455 ms17 ms
Time per call, with 45 ms to the RPC and the service457 ms70 ms

Measured with dev/bench.mjs on @breaker/sdk 0.3.0: one budget, one service selling the same inference both ways, the session run with sessionCalls: 100. The run with added delay settled in 5 transactions.

status

await agent.status() reads the budget from the chain. Use it to let an agent plan its own work inside what remains.

const s = await agent.status()
if (s.state !== 'live') return
if (BigInt(s.remaining) < price) await waitUntil(s.periodEnd)
FieldTypeWhat it is
statestringOne of live, tripped, off, expired.
limitstringThe limit per period, in base units.
remainingstringWhat the key can still pay before the next grant: the allowance on the token account.
balancestringWhat the budget account holds.
spentThisPeriodstringWhat this period has spent so far.
lifetimeSpentstringEverything the budget has ever paid.
periodSecondsnumberThe length of a period.
periodStart, periodEndstringThe current period, as ISO times.
expirystring or nullThe expiry as an ISO time.
onbooleanWhether the budget is switched on.
labelstringThe budget’s label.
budget, agentKeystringThe budget’s address and the key now approved on it.
mint, tokenProgram, tokenAccountstringThe mint, its token program, and the account that holds the money.
linedbooleanWhether the budget is on lines. On lines, remaining is the limit less this period’s spend since the last reset, since the key holds no delegation.

Amounts are strings of base units, so they survive JSON and never lose precision: USDC has 6 decimals, so 1500000 is 1.50. Wrap them in BigInt() to compare. The state is worked out in a fixed order: expired, then off, then tripped when nothing remains, else live.

maxPayment

maxPayment is the SDK’s own cap on a single call, checked before anything else. It guards against one service quoting a price far above what you expect, inside a limit that would otherwise allow it. A price above it throws PaymentTooLarge and nothing is paid.

// never pay more than 0.50 USDC for one call
const agent = breaker({ budget, key, maxPayment: 500_000n }) // USDC has 6 decimals

Errors

Each is a class exported from @breaker/sdk, thrown by agent.fetch before a payment is signed. When one is thrown, no money has moved. They are checked in this order.

ErrorThrown whenCarries
PaymentTooLargeThe price is above the maxPayment you passed.price, maxPayment
BudgetExpiredThe budget is past its expiry.budget, expiredAt
BudgetOffThe budget is switched off, or this key is no longer its agent key.budget
BudgetTrippedThe price is above what remains of this period’s limit.budget, resetsAt, remaining, price
InsufficientBalanceThe budget account holds less than the price.budget, balance, price
NoLineThe budget is on lines, and this service has no line or sells only by exact.budget, service
LineTrippedThe service’s line has taken what its cap allows this period.budget, service, resetsAt, remaining, price
import { BudgetTripped, BudgetOff, BudgetExpired, InsufficientBalance, PaymentTooLarge, NoLine, LineTripped } from '@breaker/sdk'

try {
  return await agent.fetch(url)
} catch (e) {
  if (e instanceof BudgetTripped) return retryAt(e.resetsAt)       // wait for the roll
  if (e instanceof InsufficientBalance) return askOwnerToFund(e)   // the limit allows it, the account does not
  if (e instanceof LineTripped) return retryAt(e.resetsAt)         // this service's line is spent for the period
  if (e instanceof NoLine) return skip(url)                        // the budget does not pay this service
  if (e instanceof PaymentTooLarge) return skip(url)               // this service costs more than one call may
  if (e instanceof BudgetOff || e instanceof BudgetExpired) return stop()
  throw e
}

A service whose price cannot be paid from this budget at all, because it offers no exact, upto or batch-settlement price on Solana or none in the budget’s mint, throws a plain Error that says so.

Patterns

Working code for the usual jobs is on the Recipes page: one agent for every request, a budget per agent, a check before a job, a cap on one payment, a trip handled, a wait for the roll.

What the SDK sends to Breaker

Two small reports, each signed by the agent key so Breaker can tell they are yours. Both go to apiUrl, in the background, and never hold up or fail a call.

ReportSent whenHolds
OriginA payment settled.The budget, the payment’s signature and the origin of the URL you called. It is what puts a service’s name beside a payment in your ledger.
RefusedA price was above what remains.The budget, the price and the origin. It is what lets the panel show the trip the moment it happens.

Pass apiUrl: '' to send neither. Payments work the same; the ledger then shows them by their destination account.

Exports

import {
  breaker,                    // the function
  BudgetTripped, BudgetOff, BudgetExpired, InsufficientBalance, PaymentTooLarge, NoLine, LineTripped,
  PROGRAM_ID,                 // the Breaker program's address
  DEFAULT_API_URL,            // 'https://api.breaker.to'
  MAINNET_NETWORK,            // the x402 network id of Solana mainnet
} from '@breaker/sdk'
import type { Breaker, BreakerOptions, BudgetStatus, AgentKey } from '@breaker/sdk'