SDK
Every export of @ayo/sdk, for agents, services and the browser.
@ayo/sdk has four entry points:
| Import | For |
|---|---|
@ayo/sdk | Agents: agent |
@ayo/sdk/hono | Services on Hono: serve |
@ayo/sdk/express | Services on Express: serve |
@ayo/sdk/browser | Owners' browsers: key derivation, Ring access, decryption |
The agent and service entry points run in Node 22. The browser entry point uses Web Crypto and no Node built-ins. Amounts are always base units of the mint, as decimal strings or bigint, except the price option of serve, which is a decimal amount of the mint.
Environment
The agent and service runtimes read their cluster from the environment.
| Variable | Read by | Value |
|---|---|---|
AYO_AGENT_KEY | your agent code, passed to agent | The agent's base58 seed, from the done screen |
AYO_SERVICE_ID | serve | The service account address, when the service option isn't given |
AYO_SERVICE_KEY | serve | The service's base58 seed from the done screen, when the serviceKey option isn't given |
AYO_PROGRAM_ID | both | Ayo's program ID |
AYO_RING | both | local (the default) or spr |
AYO_RING_PROGRAM_ID | both | The Ring program ID, in local mode |
AYO_RPC_URL | both | Solana RPC URL. In spr mode without it, the devnet URL is built from HELIUS_API_KEY |
AYO_API_URL | both | The Ayo API base URL |
HELIUS_API_KEY | both, spr mode | Helius API key for the devnet RPC |
SPR_INDEXER_URL, SPR_PROVER_URL | both, spr mode | The Privacy Rings indexer and prover endpoints |
agent
import { agent } from '@ayo/sdk'
const payments = agent(process.env.AYO_AGENT_KEY!)
const res = await payments.fetch('https://search.example/v1/search?q=solana')agent(key, options?) takes the base58 agent seed and returns an object with four methods. It throws at once if the key isn't a base58 32-byte seed. It connects lazily, on the first fetch or on ready().
Options
| Option | Type | Default | What it does |
|---|---|---|---|
settleAt | string | none | Settle a tab once its cumulative amount reaches this many base units |
idleMs | number | 30000 | Settle a tab after this many milliseconds without a call |
storeDir | string | .ayo | Folder for the default journal of open tabs, under the working directory |
store | AgentStore | files in storeDir | Your own journal in place of the files |
fetch | typeof fetch | global fetch | The HTTP client used for service calls |
onSettlementError | (error, service) => void | logs | Called when a background settlement fails |
onActivityError | (error) => void | logs | Called when posting an encrypted activity record fails |
runtime | AgentRuntime | built from the environment | Replaces the chain and API access, for tests |
fetch
fetch(input, init?) has the signature of the global fetch and returns its Response.
- A URL with no open tab is called once without payment headers. If the answer isn't
402withAyo-Hello, that response is returned as is, so free endpoints work through the same client. - On a hello, the agent reads the service's account on chain and checks the price, unit, mint, Ring address, settlement window and endpoint against the hello, then sends
open_tab, then repeats the request with a voucher. - With a tab already open for that service, it signs the next voucher and sends the request with it.
- A response with
Ayo-Acceptedequal to the voucher's signature counts the call as paid. Anything else leaves the tab where it was. - Don't set
Ayo-VoucherorAyo-Settleyourself;fetchthrows if you do.
If a request gets no response (a timeout, a dropped connection), its voucher stays pending, because the service may or may not have accepted it. The next request to that service carries the same voucher. If the service never recorded it, that request is served and paid by it. If it had, the service answers 409 with the matching Ayo-Accepted, the agent counts the earlier call as paid, and the request after that signs a new voucher. Before settling, the agent asks the service directly with HEAD and Ayo-Settle: reconcile, so it always pays for exactly the calls the service accepted.
Each accepted call is posted to the API as an encrypted activity record in the background; posting never delays the call.
When a tab settles
The agent settles a tab, in the background or before the next call, when the first of these happens:
- the service answers with
Ayo-Settle: now, settleAtis reached,- the tab has been idle for
idleMs, - the next call would pass the service's maximum unpaid amount per tab,
- a third of the settlement window is left, or 60 seconds if a third is less than that (for windows longer than a minute),
shutdown()is called.
Settling means one confidential transfer for the last voucher's total, then close_tab, then HEAD to the service with Ayo-Settle: confirm, which has the service confirm the tab. The signed transfer is saved to the store before it is broadcast, so a restarted agent resubmits the same bytes instead of paying twice.
settle
settle(serviceId) settles the open tab with one service now and resolves when the service has confirmed it.
shutdown
shutdown() stops the timers, waits for calls in flight, and settles every open tab. Call it before the process exits.
ready
ready() connects, reads the deployment's program ID and genesis hash, loads the store and restarts its timers. fetch calls it for you.
AgentStore
type AgentStore = {
load(): Promise<AgentTab[]>
save(service: string, tab: AgentTab | null): Promise<void>
}By default the journal is one JSON file per open tab under .ayo/agents/<genesis hash>/<program ID>/<agent signing key>/, written atomically and readable only by its owner. Set storeDir to move it, or pass a store to keep it elsewhere: save is called with the service address and the tab's whole state, or null once the tab has ended, and must be durable before it resolves. Give each agent key one writer: two processes sharing a key and a journal can sign conflicting vouchers. The journal holds signed vouchers and transfers, so keep it private.
What fetch throws
| Message | Cause |
|---|---|
AYO_AGENT_KEY must be a base58 32-byte seed. | The key passed to agent isn't a seed |
Invalid settlement interval or threshold. | idleMs isn't a positive integer, or settleAt is below 1 |
The listing changed while opening this tab. Request a fresh price. | The service changed its terms while the tab was being opened; the next call starts with a new hello |
The service hello disagrees with its registered endpoint or price terms. | The hello doesn't match the service's account, or the URL isn't under its endpoint |
One call exceeds the service tab limit. | The service's price is above its own maximum unpaid amount |
The registered listing changed. Request a new service hello. | The service changed its listing between the hello and the tab |
The opened tab does not match this agent and service. | The tab read back after open_tab isn't open, or the agent is paused |
Ayo manages payment headers. | The request already had Ayo-Voucher or Ayo-Settle |
This agent has shut down. | fetch after shutdown() |
The tab journal belongs to another agent or deployment. | The store holds tabs signed by another key or for another cluster |
The service flagged this tab unpaid. | Settlement found the tab already unpaid |
What settle throws
settle and shutdown throw these. In the background they go to onSettlementError, and the tab stays in the store to be settled again.
| Message | Cause |
|---|---|
The transfer expired without paying. Call settle(service) to rebuild it. | The settlement transfer's blockhash expired before it landed. failed in place of expired means it failed on chain. Either way nothing was paid, and settle builds a new one |
The stored tab identity does not match the chain. | The stored tab belongs to another service or key |
The recorded transfer disagrees with the chain. Reconcile this tab before continuing. | The tab is settling with a signature other than the stored transfer's |
Settlement was recorded. Receiver confirmation is pending. | close_tab landed but the service didn't answer the confirmation HEAD with success |
Receiver confirmation has not landed for this settlement. | The service answered, but the tab isn't settled on chain yet |
The service flagged this tab unpaid. | The tab was flagged before it settled |
Program errors raised by open_tab or close_tab are listed in Errors.
serve
import { Hono } from 'hono'
import { serve } from '@ayo/sdk/hono'
const app = new Hono()
app.use('/v1/*', serve({ price: '0.002', unit: 'call' }))
app.get('/v1/search', (c) => c.json({ results: [] }))import express from 'express'
import { serve } from '@ayo/sdk/express'
const app = express()
app.use('/v1', serve({ price: '0.002', unit: 'call' }))
app.get('/v1/search', (req, res) => res.json({ results: [] }))serve(options?) returns middleware for Hono or Express. Requests reach your handler only after their voucher checks out. The middleware also carries four methods: confirm, flag, void and syncActivity.
Options
| Option | Type | Default | What it does |
|---|---|---|---|
service | string | AYO_SERVICE_ID | The service account address |
serviceKey | string | AYO_SERVICE_KEY | The service's base58 seed |
price | string | none | The price as a decimal amount of the mint, such as '0.002'. Checked against the listing's base units; a mismatch throws |
unit | string | none | The unit. Checked against the listing |
settleAt | string | none | Ask for settlement with Ayo-Settle: now once a tab's total reaches this many base units |
storeDir | string | .ayo | Folder for the default voucher journal, under the working directory |
store | VoucherStore | files in storeDir | Your own journal in place of the files |
onActivityError | (error) => void | logs | Called when posting an encrypted activity record fails |
runtime | ServiceRuntime | built from the environment | Replaces the chain and API access, for tests |
What the middleware checks
For each request with a voucher, in order: the header decodes; the signature verifies against the tab agent's signing_key; the tab belongs to this service; the tab is open and the agent active; the settlement window hasn't ended; the sequence is the next one; the total rose by exactly the price; the total is within the maximum unpaid amount. Tab state is cached for one second, so a pause reaches a serving process within that time.
Responses
| Status | Headers | When |
|---|---|---|
402 | Ayo-Hello, Ayo-Settlement-Window | The request has no voucher. With Ayo-Hello-Version: 2 on the request, the hello is version 2 |
| passes to your handler | Ayo-Accepted, and Ayo-Settle: now when it's time to settle | The voucher was accepted |
204 | HEAD with Ayo-Settle: confirm and the last voucher: the settlement checked out and confirm_tab landed | |
204 | Ayo-Accepted | HEAD with Ayo-Settle: reconcile: the service accepted this voucher |
409 | HEAD with Ayo-Settle: reconcile: the service has no record of this voucher | |
400 | Invalid voucher header. | |
403 | Invalid voucher signature., or The tab belongs to a different service. | |
409 | Ayo-Accepted | This voucher was already accepted. The call was paid before; nothing is charged again |
409 | An open tab and active agent are required. The tab isn't open or the agent is paused | |
409 | The settlement window has ended. | |
409 | The voucher sequence or cumulative amount is invalid. | |
409 | Another voucher advanced this tab. | |
409 | This tab predates the voucher journal. A first voucher for a tab that opened before this server started, with nothing in its journal | |
409 | Settlement requires the last accepted voucher. | |
409 | The confidential transfer does not match the accepted voucher. | |
503 | Retry-After: 1 | Waiting for the chain clock. A freshly started server waits one clock tick before its first hello |
What serve throws
These are thrown to your server, not sent to the agent.
| Message | Cause |
|---|---|
Settlement threshold must be positive. | settleAt is below 1, thrown by serve itself |
Price must be a decimal amount. | price isn't a decimal number such as '0.002' |
Price exceeds the precision of the service mint. | price has more decimals than the mint |
The configured service price or unit disagrees with its on-chain listing. | price or unit doesn't match the listing |
This tab has no pending settlement. | confirm on a tab that isn't settling |
No accepted voucher is available for this tab. | confirm with no voucher in the journal and none presented |
Only an open or settling tab can be flagged. | flag on a tab that already ended |
The settlement grace period has not elapsed. | flag before the window plus its grace period has passed |
No accepted voucher is available as evidence. | flag with no voucher in the journal |
This settlement matches the voucher. Confirm it instead. | flag on a settling tab that was paid in full |
Only an open tab can be voided. | void on a tab that isn't open |
The tab is not overdue. | void before the settlement window has passed |
This tab has an accepted voucher. | void on a tab the service has a voucher for; flag it instead |
confirm
confirm(tabId) confirms a settling tab: it reads the settlement transfer by its signature, checks the sender, recipient, mint and amount against the last accepted voucher, and sends confirm_tab. The agent asks for this itself with HEAD and Ayo-Settle: confirm; call it directly to confirm a tab whose agent never did. If the journal has lost the voucher, the confirmation HEAD still works: the service checks the voucher the agent presents (its signature, and a total equal to its sequence times the price, within the maximum) and confirms against that.
flag
flag(tabId) flags an overdue tab. It waits out a grace period after the settlement window, a third of the window or 60 seconds, whichever is less, so an agent settling at the last moment isn't flagged. It refuses a settling tab whose transfer matches the voucher (confirm that one instead). Otherwise it sends the Ed25519 precompile instruction with the last accepted voucher, followed by flag_unpaid. See Flag an unpaid tab.
void
void(tabId) closes an open tab on which the service accepted no voucher, once its settlement window has passed, with void_tab. An agent that opened a tab and never made a paid call leaves one of these behind; voiding it frees the service to change its billing terms.
syncActivity
syncActivity(tabId) posts the service's latest encrypted activity record for a tab if it hasn't reached the API yet.
VoucherStore
interface VoucherStore {
last(tab: string): Promise<ServiceEntry | null>
compareAndSet(tab: string, previousSignature: string | null, next: ServiceEntry): Promise<boolean>
}
type ServiceEntry = { voucher: AyoVoucher; activity: WireActivity }By default the journal is one JSON file per tab under .ayo/services/<genesis hash>/<program ID>/<service address>/. A custom store's compareAndSet must replace the entry only if the stored voucher's signature equals previousSignature, atomically, and return whether it did. Run one verifier per tab. Keep the journal: flag needs the last voucher as evidence.
Browser
import { ownerDerivationMessage, deriveOwner, deriveAgent } from '@ayo/sdk/browser'
const signature = await wallet.signMessage(ownerDerivationMessage(walletAddress))
const owner = await deriveOwner(walletAddress, signature)
const first = await deriveAgent(owner.ownerDerivation.derivationSeed, 0)ownerDerivationMessage
ownerDerivationMessage(walletAddress) returns the bytes Privacy Rings defines for deriving a shielded keypair from a Solana wallet. Have the wallet sign them.
deriveOwner
deriveOwner(walletAddress, signature) returns { keypair, ownerDerivation, ringAddress, payer }: the owner's Ring identity, the derivation seed (the signature) bound to the wallet address, the base58 Ring address, and the wallet address as fee payer.
deriveAgent
deriveAgent(ownerSignature, index) returns { seed, agentKey, signingKey, ringAddress, keypair } for agent index. agentKey is the base58 seed that goes in AYO_AGENT_KEY; signingKey is the agent's Solana address. The seed is HKDF-SHA256 of the 64-byte owner signature, with the salt Ayo/agent/v1 and the index as four little-endian bytes. index is a u32.
deriveService
deriveService(ownerSignature, index) returns { seed, serviceKey, signingKey, ringAddress, keypair } for service index. serviceKey goes in AYO_SERVICE_KEY. It is derived like an agent's key with the salt Ayo/service/v1, so service and agent indexes never collide.
createRing
createRing(mode, options) returns a Ring adapter for 'local' or 'spr'. Pass the identity from deriveOwner (or an agent's), rpcUrl, apiUrl, and for spr the indexer and prover URLs.
| Method | Returns |
|---|---|
register() | A base64 transaction registering the identity, or null if it's already registered |
deposit(mint, amount) | A base64 transaction moving public funds in |
transfer(mint, amount, recipient) | A base64 confidential transfer to a Ring address |
withdraw(mint, amount, destination) | A base64 transaction moving funds out to a public address |
balances() | Unspent base units by mint |
history() | Decrypted transfers: signature, mint, amount, sender, recipient |
transaction(signature) | One shielded transaction, a RingBatch when the indexer reports a batch, or null |
viewingKey(signature) | The per-transaction viewing key for a transaction you sent |
decrypt(transaction, key) | That transaction decrypted with a per-transaction key |
decryptOutput(output) | One Ring output's mint and amount |
The builders return unsigned transactions; the caller signs and submits them, usually as ringTransactionBase64 in an API build request. SOL uses the system program address as its mint.
Decryption helpers
| Export | What it does |
|---|---|
decryptActivity(identity, ciphertext) | Opens one encrypted activity record |
spend24h(records, decrypt, now?) | Totals the agent side of the last 24 hours by mint, counting each record ID once |
decryptLocalOutput(identity, output) | Verifies a local Ring output and returns its mint, amount and nullifier |
localViewingKey(identity, transaction) | The per-transaction key of a local transfer you were party to |
decryptLocalReceipt(transaction, key) | Opens a local receipt with its per-transaction key |
decryptSprReceipt(transaction, key, serviceRingAddress, rpcUrl) | Opens a Privacy Rings receipt and checks its output commitment |
The types RingAdapter, RingBatch, RingHistory, RingIdentity, RingOptions and RingTransaction are exported alongside.