Docs3SDK reference

Section 3

SDK reference

One object does the work: the agent wallet. This page lists everything it exposes.

3.1Entry points

ImportContains
@doei/sdkThe wallet, policy engine, fee arithmetic, 402 wire format, paywall, receipts and types. No network code.
@doei/sdk/ringsThe Privacy Rings rail and the view-only reader. Imports @heliuslabs/spr.
@doei/sdk/mcpThe MCP tool table, its handlers and a server factory.
@doei/sdk/simMemoryLedger, MemoryRail and routeFetch, for tests and dry runs.

The root entry point has no network dependency, so the policy engine and the 402 parser can run anywhere, including a browser. Keep @doei/sdk/rings on a server: it holds the key.

3.2createAgentWallet

createAgentWallet(options: AgentWalletOptions): AgentWallet

Synchronous. It compiles the policy and throws INVALID_POLICY if the file is wrong, so a bad policy fails at startup and not at the first payment.

OptionTypeMeaning
railPrivateRailWhere the private balance lives. Required.
assetAssetThe one asset this wallet spends, USDC or USDC_DEVNET. Required.
policyPolicyThe owner's limits. Required. See Policies.
feeFeeSchedule{ bps, collector }. Default: no fee.
receiptsReceiptStoreWhere receipts are kept. Default: in memory.
statePolicyStateRestores the spend ledger and kill switch from an earlier snapshot().
clock() => numberUnix milliseconds. Default Date.now. Tests pass a fixed clock.
fetchtypeof fetchUsed by wallet.fetch. Default: the global fetch.

3.3AgentWallet

MemberReturnsMeaning
addressAddressThe wallet's public Solana address.
assetAssetThe asset it spends.
policyPolicyThe policy in force, as it was passed in.
killedbooleanTrue after kill() until revive().
balance()Promise<bigint>The private balance in base units, read through the rail.
budget(){ cap, spent, remaining }The rolling 24-hour budget in base units, holds included.
quote({ to, amount })PayQuoteAmount, fee, total and the policy's decision. Sends nothing.
pay({ to, amount, memo? })Promise<Receipt>One confidential payment.
fetch(url, init?)Promise<Response>An HTTP request that settles a 402 challenge.
receipts()Promise<readonly Receipt[]>Every payment this wallet made, oldest first.
deposit(amount)Promise<Settlement>Public balance to private balance. The amount is public.
withdraw(amount, to)Promise<Settlement>Private balance to a public address. The amount is public.
setPolicy(policy)voidReplace the policy. Earlier spending still counts.
kill() / revive()voidRefuse every payment, or accept them again.
snapshot()PolicyStateThe spend ledger and kill switch as plain JSON.

3.4wallet.pay

wallet.pay(input: { to: Address; amount: bigint | string; memo?: string }): Promise<Receipt>

The steps run in this order, and the first failure stops the payment:

  1. The address and the amount are validated. INVALID_ADDRESS, INVALID_AMOUNT.
  2. The protocol fee is added. Every limit below applies to the total.
  3. The policy is asked. On a yes it places a hold on the budget. On a no: POLICY_DENIED, with the rule in error.detail.code.
  4. The private balance is read. INSUFFICIENT_BALANCE.
  5. The payee must be registered with Privacy Rings. PAYEE_NOT_REGISTERED.
  6. One transfer is sent with two outputs: the payee, and the fee collector when a fee applies.
  7. The hold becomes a debit, and the receipt is stored and returned.

If anything after step 3 fails, the hold is released and the budget is as it was. Steps 1 to 3 happen in the wallet process, before anything is signed.

3.5wallet.fetch

wallet.fetch(url: string | URL, init?: PaidFetchInit): Promise<Response>

PaidFetchInit is RequestInit plus three fields.

FieldTypeMeaning
maxAmountbigint | stringRefuse a 402 price above this, before the policy is asked.
memostringStored in the receipt.
trace(event: FetchEvent) => voidCalled at each step, for logs and UIs.

A response that is not 402 is returned as it is, and nothing is paid. On a 402, the wallet picks the first entry of accepts that matches its network and asset, pays it with wallet.pay, signs the proof and sends the request once more. It retries once. A second 402 raises PAYMENT_NOT_ACCEPTED with the receipt in error.detail, because the money has moved.

stepCarriesWhen
requestmethod, urlBefore the first request.
challengerequirementA 402 arrived and one entry was accepted.
authorizedquoteThe policy allowed the total.
paidreceiptThe transfer settled.
retryheaderThe request is sent again with Doei-Payment.
responsestatus, receiptHeaderThe final response arrived.

3.6Receipts

A receipt is plain JSON. It is the only place the amount of a payment exists outside the two wallets, so store it somewhere you control. Pass a ReceiptStore with append and list to keep receipts on disk or in a database.

FieldTypeMeaning
idstringUnique within this wallet.
atstringISO 8601 instant the payment was sent.
payeeAddressWho was paid.
payeeLabelstring?The label from the allow-list, if the payee has one.
asset, mintstring, AddressSymbol and mint of the asset.
amountstringBase units paid to the payee.
feestringBase units paid to the fee collector.
totalstringamount + fee. This is what the budget was charged.
signature, slotstring, stringThe transaction, as the rail reported it.
memostring?Free text from the caller.
resourcestring?The URL that answered 402, for payments made by fetch.

3.7Owner actions

These calls belong to the owner. The MCP server does not expose any of them to the model.

examples/owner.ts, controls
wallet.budget(); // { cap, spent, remaining } for the last 24 hours
wallet.setPolicy(tighter); // earlier debits still count against the new budget
wallet.kill(); // every later payment is refused with KILLED
wallet.revive();
// A withdrawal is a public transaction and shows its amount.
await wallet.withdraw("12.50", "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin");
examples/owner.ts, persist
// The spend ledger lives in the wallet process.
// Save it, or a restart resets the budget.
const state = wallet.snapshot();
// later: createAgentWallet({ ...options, state })

Outside your own code, the same controls are files. The MCP server and the doei command read the limits file again whenever it changes, and refuse every payment while a file named stop sits next to it. doei stop and doei resume make and remove it, and the wallet page does both from a browser, next to the wallet's history.

3.8Errors

Every failure the SDK raises on purpose is a DoeiError with a code and a detail object. Use isDoeiError(error) to narrow it.

CodeRaised when
INVALID_AMOUNTAn amount is not a positive decimal, or has more decimals than the asset.
INVALID_ADDRESSA value is not a base58 Solana address.
INVALID_POLICYThe policy file fails validation. The message names the path.
POLICY_DENIEDThe policy refused the payment. detail.code is the rule.
INSUFFICIENT_BALANCEThe private balance is smaller than the total.
PAYEE_NOT_REGISTEREDThe payee has no shielded address on Privacy Rings.
INVALID_CHALLENGEA 402 response has no body the wallet can parse.
UNSUPPORTED_CHALLENGENo entry of accepts matches this wallet's network and asset.
CHALLENGE_EXPIREDThe challenge had expired when it arrived.
PRICE_ABOVE_LIMITThe price is above maxAmount.
INVALID_PROOFA Doei-Payment header cannot be parsed. Raised by parseProof.
PAYMENT_NOT_ACCEPTEDThe server answered 402 again after payment. detail.receipt is set.
BODY_NOT_REPLAYABLEThe request body is not a string.
RAIL_ERRORThe rail failed: RPC, indexer, prover or a rejected transaction.

3.9Amounts

Internally every amount is a bigint of base units. Where a function accepts bigint | string, the string is a decimal in display units. Floating point numbers are never accepted.

FunctionResult
parseAmount("0.0042", 6)4200n
formatAmount(4200n, 6)"0.0042"
formatAmount(25000000n, 6, { minFraction: 2 })"25.00"
protocolFee(4250n, { bps: 100, collector })43n, rounded up

3.10Rails

A rail is the wallet's only path to a chain. PrivateRail has eight members: network, address, balance, transfer, deposit, withdraw, isRegistered and signMessage. Two implementations ship.

RailFromState
createRingsRail(options)@doei/sdk/ringsThin adapter over @heliuslabs/spr. Verified with a real payment on mainnet.
new MemoryRail(ledger, seed)@doei/sdk/simIn memory. Used by the test suite and by every figure on this site.

To use a different signer or a different shielded pool, implement PrivateRail. Nothing else in the SDK knows which rail it is talking to.