SDK recipes
Short answers to what your server does with @nearai/financial-agents-sdk. Each assumes fin, the client from the SDK quickstart, and user = fin.user({ userId, token }) for the signed-in user.
Sign users in
With your own login
After your login succeeds, vouch for the user with your API key, naming the wallet or passkey your login verified. The user signs nothing more.
const { token, session } = await fin.users.createSession(userId, {
controller: { kind: "evm", chainId: 1, address: "0x0000000000000000000000000000000000000001" },
});Keep token beside your own session, on your server. Vouch again when a call rejects with credential_expired.
With the user's wallet
Without a login of your own, the user signs Fin's challenge, from the origin you registered:
const challenge = await fin.users.sessionChallenge(userId, {
controller: { kind: "evm", chainId: 1, address: "0x0000000000000000000000000000000000000001" },
origin: "https://wallet.example.test",
});
// The page has the wallet sign challenge.message exactly as returned, and sends back the signature.
const { token } = await fin.users.createSession(userId, {
challengeId: challenge.challengeId,
signature: { kind: "evm", signature: walletSignature },
});The challenge expires within five minutes. A NEAR wallet signs it with challenge.recipient.
Open the account in the same signature
Ask for createWallet, and a user with no agent wallet signs once: the signature that signs them in also creates the wallet.
const opening = await fin.users.sessionChallenge(userId, {
controller: { kind: "evm", chainId: 1, address: "0x0000000000000000000000000000000000000001" },
origin: "https://wallet.example.test",
createWallet: true,
});
// The page has the wallet sign opening.message exactly as returned.
const signature = { kind: "evm" as const, signature: walletSignature };
const session = await fin.users.createSession(userId, {
challengeId: opening.challengeId,
signature,
});
if (opening.createsWallet)
await fin
.user({ userId, token: session.token })
.wallets.create({ signIn: { challengeId: opening.challengeId, signature } });Send it within the challenge's five minutes. A user who already has a wallet gets the plain sign-in message, with createsWallet: false.
Open the account with a passkey the user just created
Creating a passkey signs nothing, so a passkey sign-up would otherwise take a second confirmation. When your own login just created and verified the passkey, vouch for it with createWallet: the session that registers it creates the wallet with nothing signed.
// The passkey your login just created, as its verified registration gave it.
const passkey = {
kind: "webauthn" as const,
credentialId: "q2W8eHn0SPuWxFJjWm1RfA",
publicKey: "pQECAyYgASFYIK…",
rpId: "wallet.example.test",
origin: "https://wallet.example.test",
};
const session = await fin.users.createSession(userId, { controller: passkey, createWallet: true });
if (session.createsWallet) await fin.user({ userId, token: session.token }).wallets.create({});Create the wallet within 270 seconds of creating the session. A wallet, or a passkey the user signed in with before, gets createsWallet: false, and its creation is signed.
Check a session, and sign out
const me = await fin.users.me({ token });
await fin.users.revokeSession({ userId: me.userId, sessionId: me.sessionId, token });users.me rejects with 401 once a token is invalid. Signing out never stops work the user already started.
You don't need users.me before each request: Fin checks the session on every one. Keep the session's expiresAt from Create a session, and create a new session once it passes. When a request answers 401, ask users.me: a 401 there too means the session ended or was revoked, so create a new one; otherwise the refusal was about that request.
Send a message
import { RENDERED_CARDS } from "@nearai/financial-agents-react/model";
const conversation = await user.conversations.main();
const run = await user.runs.start(
{
conversationId: conversation.id,
text: "What's my agent wallet worth?",
context: { timeZone: "America/New_York", renders: [...RENDERED_CARDS] },
},
{ idempotencyKey: messageKey },
);idempotencyKey: make it when the user sends the message. After a lost response or unavailable admission, retry the same body with that key to follow the original run.context.renders: the facts your app draws as cards, so the reply doesn't repeat them. With@nearai/financial-agents-react, sendRENDERED_CARDS. Addplacementwhen you draw a read's card only where the reply places it ([card r7k2q]lines), orshowwhen you draw it where the agent'sshow_cardscall stands (see The journal).contextapplies to this message only.context.country: send the uppercase two-letter country code from your server's edge geolocation with every message, never from the browser; omit it when unavailable. Tokenized-stock purchases require a country outside the United States and Canada and an operator-enabledtokenized_stocksflag. Once held, these assets can only be sold, never withdrawn or sent; see Tokenized stocks for the country rule when selling.- One run at a time: starting another answers 409
run_active. Wait forrun.ended, or callruns.cancel.
Fin automatically retries trusted transient model failures and reviewed safe reads at most three times, under the admitted deadline and budget. A failed ending can still follow completed actions. To retry only the reply, start a follow-up in the same conversation with profile: { tools: [] } and an explicit request to finish the answer from retained results. Keep that follow-up's own idempotency key after a lost acknowledgement. It cannot execute tools. Use financial recovery review and fresh consent for eligible unfinished transfers, rather than resending the original action request. model_invalid_output identifies exhausted terminal format repair; invalid generated output still settles verified AI usage.
If runs.cancel answers stop_pending or execution_unavailable, keep checking runs.get with the original run id and retry its stop as needed. A successful stop confirms the run has stopped; follow any submitted trade or funded order separately for its financial outcome.
Use conversations.create for a separate thread, conversations.list to show them, and conversations.delete when the user removes one. A deleted conversation stays readable by id but refuses new messages with 410 conversation_deleted, and one with a run working or an approval waiting answers 409 run_active until it is stopped. Deleting the main conversation gives the user a new, empty one: call conversations.main() again rather than keeping its id.
Relay a conversation to your browser
The browser never holds the API key or the session, so your server follows the stream and relays it. This handler serves it as server-sent events from any framework with web Request and Response: Next.js, Hono, Remix, Bun or Deno.
import type { FinStreamEvent } from "@nearai/financial-agents-sdk";
export async function GET(request: Request): Promise<Response> {
const { userId, token } = await sessionFor(request); // your own session lookup
const conversationId = new URL(request.url).searchParams.get("conversationId") ?? "";
// A reconnecting EventSource sends the last id it saw: resume after it.
const cursor = Number(request.headers.get("last-event-id") ?? 0);
const events = fin.user({ userId, token }).events.stream(conversationId, {
cursor,
signal: request.signal,
});
const encoder = new TextEncoder();
const frame = (event: FinStreamEvent) =>
`${event.delivery === "durable" ? `id: ${event.seq}\n` : ""}data: ${JSON.stringify(event)}\n\n`;
const body = new ReadableStream<Uint8Array>({
async start(controller) {
for await (const event of events) controller.enqueue(encoder.encode(frame(event)));
controller.close();
},
});
return new Response(body, {
headers: { "content-type": "text/event-stream", "cache-control": "no-store" },
});
}- Durable events carry their position as
seq. Sending it as the frame'sidlets the browser resume exactly where it left off. - Live text (
agent.text_delta) has noseqand is never replayed. - The relay ends when the browser disconnects:
request.signalends the stream.
The React quickstart folds these events in the browser.
Read a conversation's history
import { paginate } from "@nearai/financial-agents-sdk";
for await (const event of paginate((cursor) =>
user.events.list(conversationId, cursor ? { cursor } : {}),
)) {
console.log(event.seq, event.type);
}paginate works with every list, since each returns { data, nextCursor }.
Decide an approval
When the agent needs the user's OK, the run pauses and an approval.opened event arrives. Show the user exactly what it will do (the approval card in @nearai/financial-agents-react does), then send the decision:
await user.approvals.deny(approvalId, { reason: "Not now" });The run resumes by itself. Don't start another.
Money needs the user's signature
An approval that moves money carries authorization: the exact message the user's registered wallet or passkey signs. Check it on your server first, then approve with the signature and the message's controllerId and expiresAt, unchanged:
import { isAuthorizationFor } from "@nearai/financial-agents-sdk";
const approval = await user.approvals.get(approvalId);
const toSign = approval.authorization;
if (toSign) {
const me = await fin.users.me({ token });
if (!isAuthorizationFor(me, finAudience, toSign)) throw new Error("Not this user's Fin request");
// The page has the wallet sign toSign.message exactly as returned.
await user.approvals.approve(approval.id, {
authorization: {
controllerId: toSign.controllerId,
expiresAt: toSign.expiresAt,
signature: { kind: "evm", signature: walletSignature },
},
});
}The message expires about four and a half minutes after Fin issues it; read the approval again for a fresh one. Approving doesn't mean the action worked: follow the run, and for a trade read wallets.listTrades with the run's id.
Answer the agent's questions
A question.opened event carries a questionnaire. Send the answers the user gave, or skip the card:
const question = await user.questions.get(questionId);
await user.questions.answer(
question.id,
{ kind: "answers", answers: [{ id: firstQuestionId, values: [chosenValue] }] },
{ idempotencyKey: crypto.randomUUID() },
);Leave out a question the user skipped; { kind: "skip" } skips the whole card. An answer is a question's id with the chosen option values, or values: [] with the user's own customText. Answers never approve an action or move money.
A question with amount asks for one amount between amount.min and amount.max; its options are presets. Send a preset as its value, and an amount the user slid or typed as customText:
await user.questions.answer(
questionId,
{ kind: "answers", answers: [{ id: firstQuestionId, values: [], customText: "130" }] },
{ idempotencyKey: crypto.randomUUID() },
);An option with recommended: true is the one the agent suggests; its description says why.
Send feedback on a reply
When the user taps a thumb under a reply, send their feedback for that run once it has ended (completed, failed or aborted; a run still working or waiting answers 409 run_active). A thumbs-down may carry one reason from a fixed list (wrong, unhelpful, slow, unsafe or other); there is no free text:
const feedback = await user.runs.sendFeedback(run.id, { rating: "down", reason: "wrong" });
// { rating: "down", reason: "wrong", createdAt, updatedAt }Sending again replaces the earlier feedback, which is how the user changes it, and a retry is safe. To show a thread's thumbs, read its runs with runs.list({ conversationId }): each run carries feedback, null until there is any, so a reloaded page can show the thumb the user chose. When they tap it again to delete it, call runs.deleteFeedback(run.id).
Let a user talk instead of type
The page records with MediaRecorder while voice.get() says available. A browser that cannot record a type voice.get() lists converts its recording to WAV first: NEAR AI's Whisper takes Ogg with Opus and WAV, so the WebM Chrome, Edge and Safari record, and older Safari's MP4, become WAV. The page posts the recording to your server as the request's body, typed as it is sent. Your server holds it to that format's size and passes it on:
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
export async function POST(request: Request): Promise<Response> {
const me = fin.user(await sessionFor(request)); // your own session lookup
const voice = await me.voice.get();
const contentType = request.headers.get("content-type") ?? "";
const format = voice.formats.find(
(entry) => entry.contentType === contentType.split(";")[0]?.trim().toLowerCase(),
);
if (voice.status !== "available" || !format) return json({ error: "not a recording" }, 400);
// More than a minute of its format: refuse it before reading it.
if (Number(request.headers.get("content-length") ?? 0) > format.maxBytes)
return json({ error: "recording too long" }, 413);
const bytes = new Uint8Array(await request.arrayBuffer());
if (bytes.byteLength > format.maxBytes) return json({ error: "recording too long" }, 413);
const { text } = await me.voice.transcribe({ contentType, bytes });
return json({ text });
}In the page, a recording becomes WAV with Web Audio: the browser decodes its own recording, resampled to 16 kHz as it decodes, and the channels are mixed into one.
export async function toWav(recording: Blob): Promise<Blob> {
const audio = await new OfflineAudioContext(1, 1, 16_000).decodeAudioData(
await recording.arrayBuffer(),
);
const frames = audio.length;
const view = new DataView(new ArrayBuffer(44 + frames * 2));
const text = (at: number, value: string) => {
for (let index = 0; index < value.length; index++)
view.setUint8(at + index, value.charCodeAt(index));
};
text(0, "RIFF");
view.setUint32(4, 36 + frames * 2, true);
text(8, "WAVEfmt ");
view.setUint32(16, 16, true);
view.setUint16(20, 1, true); // PCM
view.setUint16(22, 1, true); // one channel
view.setUint32(24, audio.sampleRate, true);
view.setUint32(28, audio.sampleRate * 2, true);
view.setUint16(32, 2, true);
view.setUint16(34, 16, true);
text(36, "data");
view.setUint32(40, frames * 2, true);
const channels = Array.from({ length: audio.numberOfChannels }, (_, index) =>
audio.getChannelData(index),
);
for (let frame = 0; frame < frames; frame++) {
let sum = 0;
for (const channel of channels) sum += channel[frame] ?? 0;
const sample = Math.max(-1, Math.min(1, sum / channels.length));
view.setInt16(44 + frame * 2, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);
}
return new Blob([view.buffer], { type: "audio/wav" });
}- Nothing reaches the agent: put
textwhere the user writes, at their cursor, for them to read and send withruns.start(orruns.steerwhile the agent works). An emptytextmeans no speech was heard. - Each call is charged:
transcribewaits at least 75 seconds, longer than Fin waits for its speech model, and is never retried. A503 provider_unavailableis worth one retry of the same recording. voice.get()changes only when an operator turns voice on or off for the user: read it once for the page, as it decides whether to show a microphone at all.
Create the agent wallet
A user has no agent wallet until they sign its creation. wallets.get returns the wallet, or the message that creates it:
const status = await user.wallets.get();
if (status.wallet === null && status.creation) {
// The page has the wallet sign status.creation.message exactly as returned.
await user.wallets.create({
authorization: {
controllerId: status.creation.controllerId,
expiresAt: status.creation.expiresAt,
signature: { kind: "evm", signature: walletSignature },
},
});
}
const { assets } = await user.wallets.balances();Check the message with isAuthorizationFor first, as for an approval.
Fund the agent wallet
Read what the wallet accepts with wallets.supportedAssets. While the user picks an amount, wallets.quoteDeposit says what it would credit now and the least it will; it creates nothing:
const { rail, network, assetId, amountRaw, maxValueLossBps } = depositTerms;
const quote = await user.wallets.quoteDeposit({
rail,
network,
assetId,
amountRaw,
maxValueLossBps,
});
// What the agent wallet would be credited now, and the least it will within the loss limit.
console.log(quote.expectedCreditRaw, quote.minimumCreditRaw);Then create the deposit with its exact terms, with the quote's minimumCreditRaw as theirs:
const deposit = await user.wallets.createDeposit({ terms: depositTerms }, { idempotencyKey });
// deposit.instruction says where and what to send, once the address is issued.
const latest = await user.wallets.getDeposit(deposit.id);
console.log(latest.state); // "awaiting_deposit", "processing", then "credited" or "refunded"After a timeout, find the deposit with wallets.listDeposits({ requestKey: idempotencyKey }) instead of creating another. Deposits, withdrawals and trades lists every state.
When a deposit limit applies, wallets.balances says how much more the user can deposit, and a deposit worth more is refused with deposit_limit_exceeded and not recorded:
import { FinApiError } from "@nearai/financial-agents-sdk";
const { depositLimit } = await user.wallets.balances();
if (depositLimit) console.log(`Up to ${depositLimit.availableCents} US cents more`);
try {
await user.wallets.createDeposit({ terms: depositTerms }, { idempotencyKey });
} catch (error) {
if (!(error instanceof FinApiError) || error.reason !== "deposit_limit_exceeded") throw error;
// Nothing was recorded: read the balances again and offer an amount within the room left.
}Withdraw from the agent wallet
Quote first. Show the quote's terms, have the user sign its authorization, then withdraw with the quote's requestKey as the idempotency key:
const quote = await user.wallets.quoteWithdrawal(withdrawalRequest);
// The page shows quote.terms, and the wallet signs quote.authorization.message.
const withdrawal = await user.wallets.withdraw(
{
terms: quote.terms,
authorization: {
controllerId: quote.authorization.controllerId,
expiresAt: quote.authorization.expiresAt,
signature: { kind: "evm", signature: walletSignature },
},
},
{ idempotencyKey: quote.requestKey },
);Keep the original key and body for any retry, and follow the returned withdrawal by id. If preparation was interrupted, Fin can later report a terminal refusal when it confirms nothing was sent. Signature expiry alone does not establish that: a pending or uncertain withdrawal still needs its original outcome before the user considers another payment.
Swap in the agent wallet
A swap the user makes from your own screen, with no agent run, follows the same three steps: quote, sign, send with the quote's requestKey. Show the quote's terms, including the least the swap receives, then follow the swap until its status is final:
const quote = await user.wallets.quoteSwap(swapRequest);
// The page shows quote.terms, and the wallet signs quote.authorization.message.
let swap = await user.wallets.swap(
{
terms: quote.terms,
authorization: {
controllerId: quote.authorization.controllerId,
expiresAt: quote.authorization.expiresAt,
signature: { kind: "evm", signature: walletSignature },
},
},
{ idempotencyKey: quote.requestKey },
);
while (["pending", "processing", "uncertain"].includes(swap.status)) {
await new Promise((resolve) => setTimeout(resolve, 2_000));
swap = await user.wallets.getSwap(swap.id);
}Keep the original key and body for any retry. Follow the same swap until its outcome is known; an expired signature does not turn an uncertain swap into a safe replacement. Interrupted preparation can later close with a terminal refusal only when Fin confirms no swap was sent.
To swap a tokenized stock, send the user's country, resolved by your server, with both calls: { ...swapRequest, context: { country } } for the quote, and context: { country } beside terms for the swap. It applies to that one request; see Tokenized stocks.
Place a limit order in the agent wallet
A limit order the user places from your own screen follows the same three steps: prepare, sign, place with the prepared requestKey. Show the prepared terms, including minimumReceivedRaw, the least the whole order receives, then read the order it answers:
const prepared = await user.wallets.prepareOrder(orderRequest);
// The page shows prepared.terms, and the wallet signs prepared.authorization.message.
const order = await user.wallets.placeOrder(
{
terms: prepared.terms,
authorization: {
controllerId: prepared.authorization.controllerId,
expiresAt: prepared.authorization.expiresAt,
signature: { kind: "evm", signature: walletSignature },
},
},
{ idempotencyKey: prepared.requestKey },
);
if (order.state === "abandoned") console.log(`Not placed: ${order.failureReason}`);Keep the original key and body for any retry. Interrupted preparation may later become abandoned when Fin confirms nothing was placed. An expired signature or an unconfirmed result alone is not permission to place a replacement.
Use wallets.cancelOrder(order.id) to request a stop of that original order. A recorded cancelRequestedAt survives temporary outages, and Fin continues the cancellation request. After a timeout or provider_unavailable, read wallets.getOrder(order.id); repeating the stop for that same order is safe. Confirm its final fill status and payout reconciliation before showing a cancellation or refund as complete: a fill can still win the race.
A tokenized stock order takes the user's country with both calls, as a swap does.
Find a Solana token
A person types a ticker, and a ticker does not name one Solana token: many share it. Search, and when the answer is ambiguous let them choose by mint, which is what a buy or a sale pins. Show each candidate's risk, and treat a token whose tradable is false as one to read, never to buy:
const found = await user.solana.searchTokens({ query: "wif" });
const buyable = found.items.filter((token) => token.tradable);
if (found.ambiguous || buyable.length !== 1) {
// The page lists found.items, each with its mint shortened and its risk, and the person chooses.
for (const token of found.items)
console.log(token.symbol, token.mint, token.risk.level, token.tradable);
} else {
const token = await user.solana.getToken(buyable[0].mint);
console.log(`${token.symbol} ${token.priceUsd ?? "no price"} (${token.risk.level})`);
}risk.level is never a statement that a token is safe. Buying and selling are the agent's, with the user's approval in chat: see Solana tokens and Approve Solana trades and transfers.
Manage automations
The agent creates automations in conversation, with the user's approval. Your app lists them and lets the user pause, resume or delete one:
import { paginate } from "@nearai/financial-agents-sdk";
for await (const automation of paginate((cursor) => user.automations.list(cursor ? { cursor } : {})))
console.log(automation.name, automation.enabled);
await user.automations.pause(automationId);
await user.automations.resume(automationId);
// The owner let the run fin paused over go: it counts toward the run limit.
await user.automations.resume(automationId, { countMissedRun: true });
await user.automations.delete(automationId);automations.listRuns reads what each firing did. See Automations.
Manage grids
The agent creates a grid in conversation, with the user's signed approval. Your app lists the user's grids, shows each one's cells and profit, and lets the user pause, resume or cancel one:
import { FinApiError, paginate } from "@nearai/financial-agents-sdk";
for await (const grid of paginate((cursor) => user.wallets.listGrids(cursor ? { cursor } : {})))
console.log(grid.state, grid.cycles, grid.realizedProfit.decimal);
await user.wallets.pauseGrid(gridId);
try {
await user.wallets.resumeGrid(gridId);
} catch (error) {
if (error instanceof FinApiError && error.reason === "grid_trading_disabled")
console.log("Grid trading is off for this user; the grid stays paused.");
else throw error;
}
await user.wallets.cancelGrid(gridId); // answers "stopping"; the grid then ends "stopped"A grid's orders are ordinary limit orders: wallets.listOrders answers them with grid: { gridId, cell }. See grid trading.
Show suggestions on a page
Read a page's suggestions whenever it comes into view, with what your server knows about the user right now; a read answers at once and never waits on the model:
const context = { timeZone: "Europe/London", country: "GB", perpsAllowed: "false" } as const;
const page = await user.suggestions.list({ surface: "orders", ...context });
if (page.status === "ready")
for (const suggestion of page.suggestions) console.log(suggestion.title, suggestion.reason);
// thinking: read again in a few seconds. failed and not retryable: the user's AI budget or the
// hourly limit stopped Fin, so offer no Try again.
if (page.status === "failed" && !page.retryable) console.log("Fin can't look right now.");
const [first] = page.suggestions;
if (first) {
// The user opened it: check it again for fresh terms (409 suggestion_changed when it changed).
const checked = await user.suggestions.review(first.id, context);
console.log(checked.review.kind);
// Or they picked Not now.
await user.suggestions.dismiss(first.id);
}Each review kind is made through the routes that make it, such as Swap tokens or Place an order. See Suggestions.
Ping users' devices
Read the feed from one place on your server, every few seconds, and keep the cursor it answers:
import type { PartnerNotification } from "@nearai/financial-agents-sdk";
// Your own storage and delivery: where the cursor lives, and how a device is pinged.
declare function savedCursor(): Promise<string | undefined>;
declare function saveCursor(cursor: string): Promise<void>;
declare function pingDevices(notification: PartnerNotification): Promise<void>;
// After an outage, an answered or lapsed approval, or anything a day old, is not worth a ping.
const stale = (notification: PartnerNotification) =>
notification.status === "expired" ||
notification.status === "done" ||
Date.now() - Date.parse(notification.createdAt) > 86_400_000;
let after = await savedCursor();
for (;;) {
const page = await fin.partner.notifications(after === undefined ? {} : { after });
for (const notification of page.data)
if (notification.push && !stale(notification)) await pingDevices(notification);
after = page.nextCursor; // even from an empty page
await saveCursor(after);
if (page.data.length === 0) await new Promise((resolve) => setTimeout(resolve, 3000));
}The user's own inbox reads with their session: user.notifications.list() for a page and its unreadCount, and user.notifications.markRead({ through }) once they have seen it. See Notifications.
Handle errors
Every refusal rejects with a FinApiError: the HTTP status, Fin's reason, whether a repeat can succeed, and the requestId to quote.
import { FinApiError } from "@nearai/financial-agents-sdk";
try {
await user.runs.start({ conversationId, text: "Hello" }, { idempotencyKey: messageKey });
} catch (error) {
if (!(error instanceof FinApiError)) throw error;
if (error.reason === "credential_expired") {
// Vouch for the user again, then repeat with the same idempotency key.
} else if (error.reason === "run_active") {
// Wait for run.ended, or cancel the running run.
} else {
console.error(`Fin refused (${error.status} ${error.reason}), request ${error.requestId}`);
}
}| Behaviour | What the client does |
|---|---|
| Retries | Repeats a safe request (a read, a PUT that replaces what is there, or a write with an idempotency key) after a network failure, 429, 502, 503 or 504, up to maxRetries times, honouring Retry-After, unless Fin marked the refusal retryable: false. Never another write without a key. |
| Timeouts | timeoutMs (30 seconds by default) bounds the wait for each response's headers. Every method takes { signal } to abandon it. |
| Your own retries | requestRetryDelay(failures, retryAfter) returns the same capped backoff. |
| The stream | Reconnects by itself. Rejects with FinApiError when Fin refuses, and FinStreamError for a frame no reconnect can fix. Passes events it cannot read to onUnreadable. |
Errors lists every reason and what to do about it.
Watch usage and limits
const usage = await fin.partner.usage(); // requests and AI spend across your users
const quotas = await fin.partner.quotas(); // the limits your key runs under
const budget = await user.budgets.get(); // how much of this user's AI budget is leftSee Usage and limits.
Test without a server
Pass your own fetch to answer requests in tests:
import { createFinClient } from "@nearai/financial-agents-sdk";
const fake = createFinClient({
baseUrl: "https://api.example.test",
apiKey: "fin_test",
fetch: async () =>
new Response(JSON.stringify({ data: [], nextCursor: null }), {
headers: { "content-type": "application/json" },
}),
});
const page = await fake.user({ userId: "customer-123", token: "t" }).approvals.list();
console.log(page.data.length); // 0Review a safe unfinished branch
After a partial trade closes and every submitted action has a conclusive result, offer a user choice to review an unfinished branch with verified recovery evidence. The server returns the complete new request and a run for fresh approval:
const trade = await user.wallets.getTrade("00000000-0000-4000-8000-000000000001");
const reviewKey = crypto.randomUUID(); // Keep this with the user's review intent for safe retries.
const proposal = await user.wallets.prepareRemainingTrade(trade.id, { idempotencyKey: reviewKey });
const reviewRun = await user.runs.get(proposal.run.id);
// Follow this run in the original conversation and render its pending approval normally.
console.log(reviewRun.pendingApprovals);Repeat the same key and body after a lost response; they return the original proposal and run. A different body under the key is refused. Choose a new key for a new review after a group closes conclusively, including a partially completed group or a verified failed prior attempt. Show and sign every new approval. Without a key, matching active or claimed selections retain the older replay behavior.
When the user explicitly chooses a different all-in limit for a selected price-blocked action:
const originalTradeId = "00000000-0000-4000-8000-000000000001";
const revised = await user.wallets.prepareRemainingTrade(originalTradeId, { idempotencyKey: crypto.randomUUID() }, {
originalIndices: [1],
maxValueLossBps: "650", // 6.5%, explicitly chosen by the user; never an automatic default.
});
console.log(revised.request); // Display every returned action and limit before its new signature.The maximum is 1000 basis points. The new proposal cannot lower an independently requested payout minimum. Exact-output swap reviews keep their output target and can require more input at current prices. Ordered and graph selections include unfinished prerequisites and descendants; inspect originalIndices and show the full returned request. Settled or uncertain actions are never sent again. Always address the original root trade and its original action positions; recovery children cannot become new sources. Never repeat the original tool request.
A later receipt can resolve a result that originally remained uncertain. Read current eligibility without creating another proposal:
const originalTradeId = "00000000-0000-4000-8000-000000000001";
const status = await user.wallets.getRemainingTradeActions(originalTradeId);
console.log(status.candidates); // Verified local positions and unclaimed/refunded/not_executed kind.A failed claimed attempt requires conclusive proof; an uncertain one is never replaced merely because it timed out. Every new attempt keeps prior receipts and requires a new owner signature.