@usdf/sdk
v0.1.6
Published
Client for the USDF metered inference gateway: every listed model and tool at or below list price, with zero retention by default. Run a prompt paid from a prepaid key or per request with x402 in USDF or USDG, OpenAI-compatible chat completions with recei
Maintainers
Readme
@usdf/sdk
Client for the USDF metered inference gateway, an AI SDK provider (@usdf/sdk/ai), and the usdf command. No runtime dependencies; fetch only. Node 20+, Deno, Bun and browsers. viem is an optional peer, for paying from a wallet.
1 USDF = $1 of compute, redeemable 1:1 for USDG at any time. Every request is held for its worst case before it runs, billed from the provider's reported usage at the published price sheet, and answered with a receipt.
npm install @usdf/sdkRun a prompt
import { USDF, type Receipt, type X402Receipt } from "@usdf/sdk";
// Pay per request from a wallet, no account: a viem WalletClient (or a local account).
const usdf = new USDF({ wallet });
const result = await usdf.run("deepseek-v3.2", "Hello", { max_tokens: 16384 });
// result.receipt is Receipt | X402Receipt; paying from a wallet always gets the x402 shape.
const paidReceipt = result.receipt as X402Receipt;
console.log(result.text, paidReceipt.paid.usdf, paidReceipt.payment.asset);
// Or charge a prepaid balance with an API key.
const prepaid = new USDF({ apiKey: process.env.USDF_API_KEY });
const r = await prepaid.run("deepseek-v3.2", "Hello", { max_tokens: 256 });
const receipt = r.receipt as Receipt;
console.log(r.text, receipt.cost.usdf, "USDF", receipt.request_id);run(model, prompt | messages, { max_tokens, system, temperature, provider, onText }) returns { text, receipt, id, completion, payment }; receipt is the gateway's receipt as it returns it, typed Receipt | X402Receipt (narrow or cast on which path paid, as above). onText streams the answer piece by piece and the receipt arrives at the end.
With no options, new USDF() reads USDF_API_KEY, USDF_BASE_URL (the gateway origin, default https://api.usdf.fi), USDF_SESSION_TOKEN, USDF_RPC_URL, USDF_MAX_AMOUNT and USDF_PAY_TO. A wallet given explicitly is the payer; the environment's key is not picked up then.
Paying from a wallet (x402)
The gateway answers an unpaid request with 402 and two accepted payments for the same amount: USDF through Permit2 and USDG through an EIP-3009 authorization. Neither costs the payer gas. The client reads the wallet's USDF allowance to Permit2 first, on Robinhood Chain only (from rpcUrl / USDF_RPC_URL, which must answer for chain 4663; else the WalletClient's own transport when it is on 4663; else the chain's public RPC, https://rpc.mainnet.chain.robinhood.com): when it covers the amount it pays in USDF, otherwise in USDG, which needs no approval. { asset: "USDF" | "USDG" } fixes the choice; { approve: true } sends the one approval a USDF payer ever needs (approve(Permit2, max) on USDF) instead of falling back to USDG. The receipt carries paid (what was charged: what the request used, at most the quote), usage_cost and payment { tx, payer, asset, method }; result.payment is the decoded PAYMENT-RESPONSE.
The gateway has a minimum charge: the gas of returning a payment at the chain's gas price now, with a margin (a few thousandths of a USDF; the 402's quote names it, minimum_charge). A request whose quote would be below it is quoted the minimum instead (floored: true) and charged it whole. A short prompt at the model's default output budget usually is, so pass a max_tokens large enough that the quote is well above it, as above: the request is then charged only what it uses, and the rest is refunded (a remainder smaller than the gas of returning it is kept). A gateway that runs without the minimum charge refuses such a request before anything is signed (400 quote_below_refund_gas; the message names the amount).
The 402 comes from whatever server answers at the base URL, so the client signs nothing on its word alone. It pays only: on Robinhood Chain (eip155:4663); USDF (0x4A35a5eC2A50A4d2957B2F2366E017f526cAB318) through Permit2 or USDG (0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168) through EIP-3009 under USDG's own domain (Global Dollar, version 1); to the payee the gateway names: its own 402 when the base URL is the gateway (https://api.usdf.fi), else the address the gateway's GET https://api.usdf.fi/v1/config publishes (x402.pay_to), and when that does not answer nothing is signed; payTo (or USDF_PAY_TO, comma-separated) pins another payee, such as a self-hosted gateway's, and then only that one; with a validity window of at most an hour; and at most maxAmount base units per payment (USDF_MAX_AMOUNT; default 1000000, 1 USDF). Anything else throws USDFError with type payment_refused and a code (untrusted_network, untrusted_asset, untrusted_domain, untrusted_payee, amount_over_limit, untrusted_amount, untrusted_timeout, wrong_chain) before any approval, read or signature. The exact scheme charges the quote, the request's worst case at its max_tokens, so a lower max_tokens is the way to a smaller payment. The approval is sent only for USDF, to Permit2, from a wallet on chain 4663.
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { robinhood } from "viem/chains";
import { USDF } from "@usdf/sdk";
const wallet = createWalletClient({ account: privateKeyToAccount(process.env.PAYER_KEY as `0x${string}`), chain: robinhood, transport: http("https://rpc.mainnet.chain.robinhood.com") });
const usdf = new USDF({ wallet, approve: true });The lower-level pieces are exported for other signers: X402, signExactPayment (which applies the same checks), checkAccept, paymentLimits, chooseAccept, walletSigner, readPermit2Allowance, approvePermit2, permit2ApprovalCall, decodePaymentRequired, encodePaymentSignature, and the constants CHAIN_ID, USDF_ADDRESS, USDG_ADDRESS, GATEWAY_PAYEE, PUBLIC_RPC_URL, DEFAULT_MAX_AMOUNT.
Accept USDF on your x402 API (your own forwarder)
acceptUsdf and acceptUsdfFetch (payments settled into Foundry's own wallet and paid out later) are retired: they answer every request 503 accept_usdf_retired and charge nothing. Use acceptUsdfX402.
With your own forwarder, each payment goes from the payer straight to your forwarder contract, never through a wallet of Foundry's. acceptUsdfX402 answers an unpaid request 402 with the USDF option (PAYMENT-REQUIRED, with your forwarder as payTo), built on your server with no call out. A request with a payment is verified and then settled by Foundry's facilitator with your facilitator key (pfk_..., from USDF_FACILITATOR_KEY); your handler runs only after the payment settled, and the response carries PAYMENT-RESPONSE. Your forwarder's address and the key come from registering the forwarder on usdf.fi.
Express (or Connect, or plain Node http):
import express from "express";
import { acceptUsdfX402 } from "@usdf/sdk/accept";
const app = express();
app.get("/v1/thing", acceptUsdfX402({ forwarder: "0xYourForwarder", price: "0.001" }), (req, res) => res.json({ ok: true }));
app.listen(8080);A Next.js route handler (the same works in Hono, Bun, Deno and Workers):
import { acceptUsdfX402Fetch } from "@usdf/sdk/accept";
const paid = acceptUsdfX402Fetch({ forwarder: "0xYourForwarder", price: "0.001" });
export async function GET(request: Request) {
const r = await paid(request);
if (r.response) return r.response;
return Response.json({ ok: true, tx: r.payment.transaction }, { headers: r.headers });
}Options: forwarder (required), price (USDF as a string, from "0.001" to "10000" with at most 6 decimals, or a function of the request), apiKey (default USDF_FACILITATOR_KEY), description, mimeType, resourceUrl, baseUrl (default USDF_BASE_URL, else https://api.usdf.fi), maxTimeoutSeconds (default 300, at most 3600), timeoutMs (each facilitator call's, default 15000) and fetch. A bad option throws when the middleware is built. The settled payment is req.usdf (r.payment above): { transaction, payer, network, amount }, with amount in base units ("1000" is 0.001 USDF). A payment the facilitator refuses is answered 402 with the reason in the error of a fresh PAYMENT-REQUIRED, and so is one made out to anything but this request's option (checked on your server first); a refused facilitator key is answered 500, and a facilitator that is busy, down or slower than 15 seconds 503 (with its retry-after). Your handler never runs for any of them.
Chat completions
const client = new USDF({ apiKey: process.env.USDF_API_KEY });
const completion = await client.chat.completions.create({ model: "deepseek-v3.2", messages: [{ role: "user", content: "Hello" }], max_tokens: 256 });
console.log(completion.choices[0].message.content, completion.receipt.cost.usdf);
const stream = await client.chat.completions.create({ model: "deepseek-v3.2", messages, max_tokens: 256, stream: true });
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta.content ?? "");
const receipt = await stream.receipt; // from the stream's last line; null if you stopped earlyThe body is the OpenAI chat format. max_tokens bounds the hold; without it the model's default output budget is held. stream.requestId is the request id from the first byte; stream.interrupted is set when the provider's stream ended before it closed the answer (what arrived is billed; the receipt says partial). A stream that ends with nothing produced throws USDFError upstream_unavailable: nothing was charged.
Privacy and routing per request: provider: { zdr: true }, { data_collection: "deny" }, { private: true } (attested hardware the gateway verified, at the model's price), or a :private, :cheapest, :fastest suffix on the model id. A request served on attested hardware carries receipt.private and receipt.data_policy.attestation_measurement (the build it ran), and client.receipts.attestation(id) returns the provider's record of it.
The receipt of every chat and completions request carries signature, the gateway's Ed25519 signature over what was served: await client.privacy.verifyReceipt(receipt) checks it against the keys at GET /v1/privacy/keys. For a model whose attested route takes it, client.privacy.chat(params) (or client.privacy.stream) encrypts the message content on your machine to a key of the enclave's attested keyset and opens the answer here, so the gateway routes and bills the request without reading it (sealChatRequest builds the envelope alone). It takes the key from the gateway's own verification (client.privacy.e2ee(model)); to rely on the gateway for nothing, verify the enclave's attestation yourself first and pass the checked target to sealChatRequest.
Batch jobs
Models whose price carries batch_input run as jobs at the upstream's batch rate:
// batchModel: any model whose price on GET /v1/pricing carries batch_input.
const job = await client.batches.create({ model: batchModel, messages, max_tokens: 256 });
const done = await client.batches.wait(job.id); // the completion, receipt.batch === truebatches.get(id) and batches.result(id) read a job directly; { webhookUrl } on create has the gateway POST the outcome.
Before and after a call
quote({ model, prompt | messages, max_tokens }): the hold the gateway would place and the x402 amount for the same request. No key.balance(): what the key can spend, the account's balance and holds, the key's budget.receipts.get(id): a receipt with its settlement batch once settled and its leaf in the public usage log (log).receipts.list({ limit, model, status, before }): the latest receipts, newest first; a key lists its own, a session the account's.models.list(),pricing(),tools.list(),tools.call(id, input),embeddings.create({ model, input }).estimatePromptTokens,maxCostUnits,costUnits: the gateway's hold arithmetic, for figures before a round trip. The gateway's quote and receipt are the figures that bind.
The account (session)
Everything a key can do (requests, quotes, the balance, receipts, tools) needs only the key: create one on the dashboard at usdf.fi. The account's own calls take a session: sign in at usdf.fi and pass its session token, new USDF({ sessionToken }) or USDF_SESSION_TOKEN (it lasts about an hour). Email and password sign-in is retired: auth.signIn and auth.refresh throw sign_in_retired. auth.info() reads GET /v1/auth (the sign-in in force and every account path); auth.signOut() ends the session at the gateway.
keys.create({ label, budgetUnits, rateLimitRpm })(the key text is returned once;rateLimitRpmis the key's own limit, from 1 to 5,999 requests a minute, and left out the key has none),keys.list({ revoked }),keys.revoke(id),keys.rotate(id)(a new key with the old one's controls; the old one is revoked),keys.limits(id),keys.update(id, { spend_limit_hour_units, spend_limit_day_units, spend_limit_month_units, allowed_models, no_logs, private_tier, webhook_url }),keys.pause(id),keys.resume(id). All on the gateway's own account endpoints (/v1/account/keys,/v1/keys/{id}).account.get(),account.overview(),account.activity({ model, status, from, to, limit }),account.activityCsv(...),account.settings(),account.updateSettings({ zdr, max_price, low_balance_units, ... }),account.analytics({ days }),account.withdraw({ units, chainId, idempotencyKey })(to the linked wallet; every call sends anIdempotency-Key, yours or one made for the call, so pass your own to retry a failed call safely).- Links:
links.create({ units, memo, expiresInDays })returns the claim token once;links.list(),links.get(token)(public),links.claim(token),links.cancel(id). - Agents:
agents.create({ slug, name, allowed_models, max_request_units, ... }),agents.list(),agents.get(slug),agents.update(slug, policy),agents.fund(slug, { units, direction, idempotencyKey }),agents.pay(slug, { to, units, memo, idempotencyKey })(with the agent's key or the owner's session),agents.payments(slug),agents.rotateKey(slug). - Pay with anything:
zap.quote({ token, amount, recipient, slippageBps })prices ETH or a token with a liquidity pool against USDG into USDF and returns the transactions to send. No key. pool.read(): the USDF/USDG pool's price, tick, whether it sits in the seeded band, its liquidity and reserves. No key.
Money is carried as strings of base units (1 unit = $0.000001 = 0.000001 USDF); every amount is { units, usd, usdf }. Unit arguments take a bigint, a number or a decimal string.
AI SDK
import { usdf, createUSDF } from "@usdf/sdk/ai";
import { generateText } from "ai";
const { text, providerMetadata } = await generateText({ model: usdf("deepseek-v3.2"), prompt: "Hello" });
console.log(text, providerMetadata?.usdf.receipt);
const paid = createUSDF({ wallet }); // pays each call over x402usdf reads USDF_API_KEY and USDF_BASE_URL when the first request is made; createUSDF({ apiKey | wallet, baseUrl, asset, approve, rpcUrl, maxAmount, payTo }) sets them (unset, the wallet path reads USDF_RPC_URL, USDF_MAX_AMOUNT and USDF_PAY_TO as new USDF does). The models implement the AI SDK's provider specification v3 (AI SDK 6 and 7): generateText, streamText, generateObject (JSON schema), tools, and usdf.embedding(id) for embed. The gateway's receipt is in providerMetadata.usdf.receipt on every result and on the stream's finish.
Errors
Every refusal is a USDFError with the gateway's status, type, code, message, requestId and retryAfter: invalid_api_key 401, insufficient_balance 402, spend_limit_exceeded 402, key_paused 403, model_not_allowed 403, rate_limited 429, model_not_found 404 (the message names the closest ids), permit2_allowance_required 402 (x402), susdf_retired 410 (sUSDF is retired: a stake quote and the staking line; see Staked USDF). The rest of the gateway's error object is in body. Nothing is charged for a refusal.
The command
npx @usdf/sdk balance, npx @usdf/sdk keys, npx @usdf/sdk run deepseek-v3.2 "Hello" --cost, npx @usdf/sdk receipts, npx @usdf/sdk receipt <id>, npx @usdf/sdk pricing, npx @usdf/sdk quote deepseek-v3.2 "Hello", npx @usdf/sdk login --key sk_.... npx @usdf/sdk help lists everything.
Installed globally (npm install -g @usdf/sdk), the command is usdf: usdf balance, usdf run deepseek-v3.2 "Hello" --cost.
Changes
0.1.6. keys.create sends no rate limit unless rateLimitRpm is given, so a key has none unless you set one; 0.1.5 set 60 requests a minute on every key it made. rateLimitRpm takes 1 to 5,999 (KEY_RPM), the range GET /v1/limits states for keys; anything else is refused before a request. balance() and keys.list() give rate_limit_rpm as the key's own limit, or null for a key with none, where 0.1.5 passed through the gateway's 6000; its type is now number | null. keyRateLimit() reads a stored value the same way. The usdf command does the same: keys create sets none unless --rpm is given, and balance and keys print none for a key with no rate limit. account.withdraw sends an Idempotency-Key header on every call: idempotencyKey when given (8 to 128 letters, digits, _, ., : or -, as IDEMPOTENCY_KEY matches; anything else is refused before a request), else one made for the call, so a retry with your own key can be answered with the withdrawal it first made rather than a second one. WithdrawalRequested may carry status, idempotency_key and replay.
0.1.5. A wallet payment is signed only for a payee the gateway itself names: its own 402 when the base URL is https://api.usdf.fi, else its GET https://api.usdf.fi/v1/config. When neither can be had, nothing is signed (untrusted_payee); 0.1.4 signed for a fixed payee then, a hot wallet the gateway has since retired. Before Add funds from another chain signs anything, the quote is checked too: what is received is the amount less the fee, and the fee is at most 5% of the amount.
0.1.3. pricing() sends the API key (or the session token) when the client has one. GET /v1/pricing answers only to a key or a signed-in session, and 0.1.2 called it without either, so it failed with 404. The usdf command's pricing and run --cost do the same. With neither set, they behave as 0.1.2.
0.1.2. A wallet payment goes to the payee the gateway names, not to a hot wallet fixed in the package: the gateway rotated its custody hot wallet on 2026-10-26, and 0.1.1, which pays only the retired one (0x52Fe...9F05), refuses the new one's 402 with untrusted_payee before signing anything. The 402's payee is taken as it stands from https://api.usdf.fi; through any other base URL it must be the one https://api.usdf.fi/v1/config publishes, or the new hot wallet (GATEWAY_PAYEE). payTo and USDF_PAY_TO still pin a payee. The account calls move off the retired email and password sign-in: keys are created, listed, revoked and rotated on the gateway's own account endpoints with a session from the site, account.withdraw sends USDF to the linked wallet, and auth.signIn and auth.refresh throw sign_in_retired. The usdf command's login takes an API key (--key) or a session token (--token), and keys rotate is new.
0.1.1. The default base URL is https://api.usdf.fi, the gateway's own domain; 0.1.0 used the hosting provider's hostname for the same gateway, which still answers. baseUrl or USDF_BASE_URL still points the client elsewhere. The usdf command reads a config file saved by 0.1.0 as saved for https://api.usdf.fi, so its saved key and session move with it. No other change.
Add funds from another chain
USDC or PYUSD on Ethereum, USDC on Arbitrum, or Global Dollar (USDG), issued by Paxos, on either, added to the balance as
USDF. Your wallet signs and sends the order itself; its address must be the account's linked wallet, where the USDG
arrives on Robinhood Chain before it is added. The minimum is the route's (usdf.transit.routes("deposit")).
import { createWalletClient, http } from "viem";
import { arbitrum } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";
import { USDF } from "@usdf/sdk";
const wallet = createWalletClient({ account: privateKeyToAccount(process.env.AGENT_KEY as `0x${string}`), chain: arbitrum, transport: http() });
const usdf = new USDF({ apiKey: process.env.USDF_API_KEY });
const order = await usdf.transit.depositFrom({ wallet, sourceChainId: 42161, asset: "USDC", amountUnits: 250_000_000n });
const done = await usdf.transit.wait(order.id); // fulfilled, its deposit creditedBefore the wallet signs or sends anything, depositFrom and topUpIfLow check what the server answered against values pinned in this SDK: the route's tokens, USDG's own authorization for the amount received, an approval of that token to the order contract for exactly the amount, and the order's target, value and calldata. Anything else is refused with an untrusted_* code and nothing is signed or sent. To add funds through a gateway other than api.usdf.fi, name its payee with payTo (or USDF_PAY_TO).
usdf.transit.topUpIfLow({ wallet, sourceChainId: 42161, asset: "USDC", rule }) adds the rule's amount when the balance is
below its threshold, within its cap for the period. With an API key alone, pass rule; without it the account's own
top-up rule is read, which takes the signed-in session (sessionToken) as well. Cash out to USDC or USDG on Arbitrum or Ethereum with the signed-in
session: usdf.transit.cashout.preview(...), then usdf.transit.cashout.create(...).
How payouts are converted is the account's payout preference, read and set with its own key or its session:
usdf.transit.payoutPreference.get(), usdf.transit.payoutPreference.set({ wantAsset, destinationChainId, destinationAddress })
(USDC or USDG on 42161 or 1; no address is the linked wallet's own there) and usdf.transit.payoutPreference.clear(). With
one, each paid payout the API shows carries convert, the conversion pre-filled. An address other than the linked wallet
is set from the signed-in session only, after a recent sign-in, and the account is emailed.
Staked USDF (sUSDF)
sUSDF is retired: it takes no stakes, and nothing is paid into it. USDF earns nothing, plain or held in any other token or vault. usdf.susdf.get() answers { configured: false, retired: true, successor: "/v1/fees", note } (SusdfRetired), with no funding, rate or earnings.
Shares already held can be unstaked at any time: usdf.susdf.position(address) reads a wallet's shares and what they are worth, usdf.susdf.history(address) its events, usdf.susdf.days(30) the share price by UTC day, and usdf.susdf.quote({ action: "unstake", address, amount: "10" }) (or all: true) answers the transactions the wallet signs and sends itself, in order, paid at once (no request, cooldown or claim). The gateway signs and sends nothing. An unstake is never refused by region.
Every method is kept: a stake quote, usdf.susdf.eligibility(), usdf.susdf.acknowledgement(address), usdf.susdf.acknowledge(...) and usdf.susdf.confirmLine(...) answer 410 susdf_retired.
import { privateKeyToAccount } from "viem/accounts";
import { USDF } from "@usdf/sdk";
const account = privateKeyToAccount(process.env.WALLET_KEY as `0x${string}`);
const usdf = new USDF();
const quote = await usdf.susdf.quote({ action: "unstake", address: account.address, all: true });
// quote.calls: the transactions the wallet sends itself, in order