@notol/agent
v0.1.3
Published
Notol SDK: send USDC on Arc into an escrow that releases only when the recipient proves the address is theirs, else refunds.
Maintainers
Readme
@notol/agent
TypeScript SDK for Notol on Arc: send USDC into an escrow that releases only when the recipient proves the address is theirs, else refunds the sender. For AI agents and servers that hold their own key: send to an address, confirm a received link, check status, cancel, all over the api, without web pages. Address mode only.
npm install @notol/agent viemTypeScript users also need Node's types (npm i -D @types/node), because the webhook handler is typed with node:http.
Node 20 or later, ESM. Docs: https://www.notol.app/docs#sdk.
import { createAgent } from '@notol/agent';
import { privateKeyToAccount } from 'viem/accounts';
const agent = createAgent({
account: privateKeyToAccount(process.env.AGENT_KEY as `0x${string}`),
chainId: 5042, // Arc mainnet (5042002 = Arc testnet)
apiUrl: 'https://api.notol.app',
webOrigin: 'https://app.notol.app',
});
// Sender. Amounts are USDC base units (6 decimals) as bigint.
const sent = await agent.sendToAddress({ to: '0x…', amount: 1_000_000n, notify: 'share' });
// 'share': deliver sent.confirmLink yourself, by a channel you already trust for this recipient.
// Alternatives, only against an api that delivers that channel (api.notol.app does not: EMAIL_DISABLED / WEBHOOK_CHANNEL_DISABLED):
// notify: { email: '[email protected]' }
// notify: { webhook: 'https://payee.example/notol', key?: '<payee box public key>' }: sealed to the payee's key, the api POSTs the box there (sent.notifyDelivered). See "Receiving by webhook".
// Recipient (its own agent, holding the destination key).
await agent.confirmFromLink(link, { displayName: 'Acme bot' });
await agent.transferStatus(sent.transferId); // TransferView: Pending | Released | Refunded
await agent.readTransfer(id); // the escrow's own record on your RPC: mode, status, sender, recipient, amount (bigint), expiresAt
await agent.cancel(sent.transferId); // sender only, while Pending: Escrow.cancel, back to you
await agent.rejectFromLink(link); // payee: "not mine", the link's contact key refunds the senderReceiving by webhook
The payee runs createConfirmHandler on the URL senders use as notify: { webhook }. Two bodies can arrive:
- Sealed (D65, preferred):
{ type: 'confirm.sealed', transferId, chainId, box }. The sender sealed the link secret to your X25519 public key before the api saw it. The api stores and forwards only the box and cannot open it; a hacked api can delay or drop delivery, not read the secret. The handler opens the box withboxKeys. - Plaintext (
confirm.requested,confirmLink): only against an api that delivers the plaintext webhook channel. Off on api.notol.app.
Nothing in either body is trusted: the handler reads the transfer on the agent's own RPC, and confirmFromLink / rejectFromLink check the link's secret against the on-chain contact key.
import { createServer } from 'node:http';
import { createConfirmHandler } from '@notol/agent';
const handler = createConfirmHandler({
agent: payee, // createAgent with the destination key
chainId: 5042,
boxKeys: [process.env.NOTOL_BOX_KEY_CURRENT!], // private keys, current first; older ones while they are in rotation
// Your own check, e.g. an open invoice from this sender for exactly this amount.
decide: async (t) => ((await openInvoice(t.sender, t.amount)) ? { action: 'confirm', displayName: 'Acme AP' } : { action: 'reject' }),
onResult: (r) => log(r), // confirmed | rejected | ignored | failed; never holds the link
});
createServer((req, res) => void handler(req, res)).listen(8080);- The handler answers within the api's 5 s: 400 for a body that is not a confirm request for this chain and transfer, 200 when there is nothing to do (settled, another mode, unknown id), 503 when the chain is unreadable (the api retries), and 202 once it has queued the work. The confirm or reject then runs and reports through
onResult. - A transfer locked to an address that is not this agent's, but sent to this channel, is rejected by default (
onForeignRecipient: 'reject'), so the sender is refunded. That is the poisoning case: the sender reached the right party but locked to a swapped address.decideis not asked. - With
boxKeysthe same URL also answers GET with{ "type": "notol.contact-key", "v": 1, "keys": ["<base64url public key>", ...] }, current key first. That is where a sender's SDK reads the key when it has none pinned. - Make a key with
newContactBoxKey(), which returns{ privateKey, publicKey, keyId }. The private key is a secret: store it like an API key and show it once, from your own tooling. Give senderspublicKey(they pin it asnotify.key).contactBoxPublicKey(privateKey)derives the public key again. - Rotation: put the new private key first in
boxKeysand keep the old ones until your longest open transfer has expired (72 h by default). Lost key: make a new one. Boxes sealed to the old key fail to open and those transfers refund at expiry. - Anyone can POST to the endpoint. A forged body can at worst confirm money really sent to you, or refund a transfer whose link the caller already holds. Put the handler behind your own rate limiter (
ponytail:none built in).
Policy and send
const agent = createAgent({ …, policy: { maxPerTransfer: 50_000_000n, maxPerDay: 200_000_000n, escrowAbove: 10_000_000n } });
const r = await agent.send({ to: '0x…', amount: 5_000_000n, notify: { webhook: vendor.notolWebhook } });
if (r.kind === 'direct') r.txHash; else r.transferId; // escrow: a SendResult, as sendToAddresssendneeds a policy (POLICY_REQUIRED). With a policy,sendToAddressobeys its limits andverifiedOnlytoo; it always escrows.maxPerTransfer(required) andmaxPerDaycap the amount. The 24 h total is your escrow locks fromGET /v1/transfers?sender=(any status, cancelled ones included) plus this instance's own sends, counted before broadcast. If the list cannot be read, it refuses (POLICY_UNKNOWN), never counting it as 0.ponytail:direct sends are kept in memory only, so a restart forgets them; upgrade path: read your USDCTransferlogs.- The route: input checks, limits, then the api's
checkPayee(blockedrefuses:SELF_SEND,LOOKALIKE,BLOCKED). A direct ERC-20transferhappens only when the api saysdirectANDPayeeRegistry.isVerified(you, to)reads true on your own RPC ANDamount <= escrowAbove.escrowAboveunset means never direct. Anything else escrows, or withverifiedOnlyrefuses an unverified payee (NOT_VERIFIED). The api alone can only make the agent escrow or refuse. The rule is the purerouteDecision, tested exhaustively. - A direct send has no escrow and no refund. It relies on the payee having proved control of that address to you before (a released transfer).
- The notify minimum applies to
sendwith email or webhook even when it ends up direct; pass'share'for smaller amounts. - The policy is a soft guard: it lives in the same process as the key. Hard limits need smart-account session keys (planned).
Webhook notify: take the URL from your own vendor records, never from the invoice or message that carries the address. Whoever controls the webhook gets the link and can confirm, so a poisoned invoice carrying both an address and a webhook defeats the check, exactly as a poisoned email address would. The URL must be https on port 443 (plain http or another port only on localhost), at most 2048 characters, and is signed exactly as given. The same goes for key: pin it from your own vendor records. Without key the SDK GETs it from the webhook URL directly (never through our api), which is only as good as that URL. If the api offers the sealed channel (webhookSealed in GET /v1/info) the send is sealed, and a key at the URL that is not valid stops it. notifyDelivered is true once the payee's endpoint answered 2xx; false means the api retries for about an hour.
One agent instance per account. The agent signs its approve and lock with nonces from the chain, read at send time; it keeps no shared nonce counter. One instance runs its own money calls one at a time, so concurrent calls on it are safe. Two processes, or two instances, with the same key can still pick the same nonce: one tx then replaces or blocks the other. Run one instance per key; use separate keys for parallel senders.
Refusals throw AgentError with a code. These happen before anything is locked or signed:
BAD_INPUT,SELF_SEND,LOOKALIKE,PAYEES_UNKNOWN,BELOW_NOTIFY_MIN;POLICY_REQUIRED,POLICY_LIMIT,POLICY_UNKNOWN,NOT_VERIFIED,BLOCKED;BAD_LINK,NOT_FOUND,WRONG_MODE,NOT_PENDING,NOT_YOUR_ADDRESS,WRONG_LINK(cancel:BAD_INPUTwhen you are not the sender);EMAIL_DISABLED,WEBHOOK_CHANNEL_DISABLED: an escrow send withnotifyemail or webhook, when the api'sGET /v1/infosays it does not deliver that channel (NETWORKif that read fails). On api.notol.app both are off, so escrow sends there usenotify: 'share'or the sealed webhook.CONTACT_KEY_UNAVAILABLE: a webhook send, and the payee's URL gave no usable contact key or could not be read (a network error, timeout, 5xx, 429 or a malformed key document), or the key cannot be sealed to.SEALED_CONTACT_DISABLED: the api has no sealed channel, andkeyis pinned or the payee's URL serves one; the SDK never sends the secret in plaintext then. The plaintext webhook channel is used only when the api offers it and the payee's URL answers 404, 405, 410 or JSON that is not a key document. Neither code locks anything.
Api errors keep the api code, such as NOT_PENDING or RATE_LIMITED. Others:
FEES_TOO_HIGH: network fees are abovemaxFeePerGas(option, defaultDEFAULT_AGENT_MAX_FEE_PER_GAS= 1000 gwei). Nothing is signed.LOCK_UNCONFIRMED: the node errored on the lock and the tx was not seen within about 30 s, or its receipt timed out. It may still land. Do not send again; resume instead, which re-broadcasts the same signed tx and so can never lock twice:try { await agent.sendToAddress(req); } catch (e) { if (e instanceof AgentError && e.code === 'LOCK_UNCONFIRMED') await agent.resumeSend(e); else throw e; }The error holds the link secret in a non-enumerable
pendingfield, so logging orJSON.stringifydoes not print it. Keep the error object in memory only.LOCK_FAILED: the lock reverted or mined without itsLockedevent. Nothing is locked.TRANSFER_UNCONFIRMED: a direct transfer (or a cancel) was sent but not seen mined. It may still land. For a direct send, callagent.resumeDirect(err): it re-sends the same signed bytes (err.pendingDirect, non-enumerable), so it can pay at most once. Never callsendagain for it, which would sign a new nonce and could pay twice. A cancel just re-reads: a second cancel is refused withNOT_PENDING.Money calls (
send,sendToAddress,resumeSend,resumeDirect,cancel) run one at a time per agent instance. WithescrowAboveset,maxPerDayalso counts this account's USDC transfers on chain for the last 24 h, so a restart does not reset it. A direct send never goes to a payee that imitates another of your verified payees: that one is escrowed.TRANSFER_FAILED: a direct transfer reverted or mined without exactly one matching USDCTransfer(you, to, amount), or a cancel mined without the escrow readingRefunded.NETWORK: the api or the chain RPC was unreachable.
confirmFromLink and rejectFromLink check the escrow on chain, not the api's view, and return once the relayed receipt is mined and the escrow reads Released / Refunded. rejectFromLink accepts Address and Verified mode and does not require you to be the recipient: "not mine" comes from the person the link reached. cancel waits for its receipt and the on-chain Refunded; a repeat is refused with NOT_PENDING, so retrying it is safe.
