# View models

`@nearai/financial-agents-react/model` is the logic behind Fin's blocks, without the blocks: the thread fold,
what an approval asks, how an automation reads, exact amounts and token metadata. Use it to draw
Fin's data with your own components, to word your own surfaces as Fin's blocks do, or to read
Fin's data on a server.

```ts
import { threadReducer, transcriptEntries } from "@nearai/financial-agents-react/model";
```

Every function is pure over the data Fin sends: nothing renders, fetches or keeps state. Unlike
the components' client entry, it runs anywhere, a server included.

> [!NOTE]
> Functions that read token metadata or routes read what `FinUIProvider` configured. Without a
> provider, as on a server, set them with `configureFinUI`. Unset, they are near.com's.

## Configuration

| Export | Description |
| --- | --- |
| `configureFinUI({ tokens?, routes? })` | Sets the tokens and routes these functions read outside React. `FinUIProvider` calls it for you. |
| `tokens()`, `routes()` | The resolver and routes set now. |
| `DEFAULT_TOKENS` | near.com's token list as a `TokenResolver`. See [Tokens and chains](/tokens-and-chains). |
| `DEFAULT_ROUTES` | near.com's paths for the agent's pages. |
| `TokenResolver`, `TokenInfo`, `FinRoutes` | Their types. |

## The thread

A conversation is a fold over its events. Fold the SDK's `FinStreamEvent`s as they arrive, then
read the thread with these helpers.

| Export | Description |
| --- | --- |
| `threadReducer(thread, event)` | Folds one event in. Ignores one it has seen, by `seq`, so a replay is harmless. |
| `initialThread` | The empty thread. |
| `ThreadState` | The folded thread: `items` in order; `approvals`, `questions` and `executions` by id; `runStatus`; live `streamingText`; the last `seq`. |
| `ThreadItem` | One of `items`: a `user` or `assistant` message, a `tool` call, a `settlement`, a `question`, an `approval` or a `run` ending, which carries the `runId` it ended: what feedback on the reply is sent for. A `user` message the user sent the working run (`run.steered`) carries `steered: true` and sits where the agent read it; one an automation's run opened carries that `automation` (`{ automationId, name }`). |
| `ToolItem` | A `tool` item: its name, input, phase and outcome, and, in an automation's run, that `automation` with the run's `runId`. A call the agent asked for with others carries their `batch`: its `index`, their `size` and the `group` they share, the first call's `key`. A call whose result came after its run ended carries `leftOpen: true`: the run ended before the call did, so one cut short by the person's Stop can read as stopped rather than failed. A perps order, cancellation, margin change or withdrawal whose result was unconfirmed takes its `perps.reconciled` answer as its outcome, and a Solana buy, sale or withdrawal its `solana.reconciled` answer. A Polymarket funding or order takes the latest `prediction.funding` or `prediction.order` observation instead. All are marked `reconciled: true`; for Polymarket this means an updated observation, **not** verified pUSD settlement or a settled trade. |
| `StreamEvent` | An event the reducer takes: the SDK's, or the JSON your relay sent. |
| `ApprovalView` | An approval, with its contract and status. |
| `ExecutionView`, `ExecutionLeg` | A financial execution as the journal reported it, and one of its swaps. |
| `SolanaSaleProgress` | One coin's latest swap snapshot in a sale of several Solana coins (`solana_sell_many`), with `at`, when it arrived: `ExecutionView.solanaSales` keeps one per coin, by the coin's place in the sale (`sale`), so a reader knows which coins sold and which is on its way while the sale runs. |
| `RunStatus` | `idle`, `running`, `paused`, `completed`, `failed` or `aborted`. |
| `isStreaming(thread)` | Whether reply text is arriving now. |
| `isThinking(thread)` | Whether the agent is working with nothing streamed and no tool running. |
| `runningTool(thread)` | The tool call running now, if any; never a `show_cards` call, which shows cards rather than does work. |
| `streamingKey(thread)` | A stable React key for live text, kept once it is saved. |
| `pendingApprovals(thread)` | The approvals waiting for the user. |
| `pendingTrades(thread)` | The trades waiting on the user's decision, by coin: a `ReadonlyMap` from a Solana mint or an Intents token id to `{ side, approvalId }`, read from each pending approval's request: a `solana_buy` buys its mint, a `solana_sell` and each sale of a `solana_sell_many` sell theirs, and each swap of an `intents_execute` request sells what it pays with and buys what it produces. A send, a withdrawal, an order or a rule trades nothing. When two waiting approvals name one coin, the later in the thread says its side. A card's buttons never contradict one: offer no Buy of a coin whose sale waits and no Sell of one whose buy waits; say where the decision is instead. |
| `pausedApprovalExpired(thread)` | Whether the run waits on an approval that expired. |
| `toolForApproval(thread, approval)` | The tool call an approval belongs to. |
| `approvalForTool(thread, item)` | The approval a tool call waits on or was decided by. |
| `executionForApproval(thread, approval)` | The execution an approved trade produced. For a Solana buy or funding it is the 1Click leg that moves USDC into the Solana account, which says whether the SOL has arrived. |
| `executionForTool(thread, item)` | The execution a trade's call drove, for `ToolCallCard`'s `execution`. |
| `runOfItem(thread, key)` | The run that drew an item, or `null` when the journal cannot identify it. Pass it with a result card's message so the host steers only into that same run while it waits on its question. |
| `runEndedAfter(thread, item)` | Whether the run ended after this call, so it will never finish. |

Independent reads can finish out of `batch.index` order. Feed events to `threadReducer`
in durable `seq` order; it matches results by call identity. Use each item's batch
index for the original display order, and keep completed results when a sibling fails
or the user stops the run.

`composite.progress` is folded, not dropped: `executionForApproval` and `executionForTool`
return one parent at `executions["composite:" + callId]` for `composite_execute`. Its
`compositeProgress` holds the latest revision's numbered pieces, each with its tool, nullable
`operationId`, `todo` / `live` / `done` / `bad` / `skip` state and optional failure reason.
Older or duplicate snapshot revisions cannot overwrite it. A piece with an operation id also
has its own `ExecutionView` under that id, with `compositePiece: { parentKey, index }`;
its Intents swaps and receipts stay on that operation, never on an arbitrary sibling sharing
the approval. The conversation keeps one tool call and one approval, not a new card per piece.
Later perps or prediction observations are kept as the piece operation's `reconciledOutcome`,
not substituted for the parent call's whole result. A late piece observation never completes
its sibling pieces or creates a second approval.

Progress is display evidence, not consent or a result: only the exact composite contract and
its frozen piece inputs define the signature. The final `composite_execute` tool outcome holds
each piece's result and unused venue balances; a completed call does not mean every piece bought.
A venue in `unusedUnavailable` means its final balance could not be read, not that it is zero.
Offer an account review and withdrawal instead of claiming no venue money remains.

## The transcript

| Export | Description |
| --- | --- |
| `transcriptEntries(thread)` | What a transcript draws, in order. Consecutive read calls fold into one `activity` entry with their cards. Intents and Solana money calls retain their own financial entry even without a per-call approval. A turn says each thing once: an interrupted draft is left out once later words of its turn exist, and a long reply is left out when a later one says it again with only reads between them. The thread keeps both. |
| `TranscriptEntry` | `{ kind: "item", item }` or `{ kind: "activity", key, items, blocks }`. |
| `entryKey(entry)` | A stable React key. |
| `threadTurns(thread)` | The thread as turns, for an app that sends `show` or `placement` in `context.renders`. Each `Turn` holds its `answer` (the agent's words split at the cards it placed, then approvals, questions, trades, receipts, saved rules and asks for a deposit where they happened), its `work` (every other call, in order: its steps), the `blocks` its reads draw (a turn that saved an automation leaves out its prediction-market reads' cards: they were how the agent found the market to watch), `placed` (whether the agent chose cards for the turn: its replies name any of its cards, or it called `show_cards`), `legacy` (the turn opened before cards were placed, on 2026-10-25 at 17:00 UTC, by when its opening message or, with none, its first step happened; a turn whose events carry no time is not) and `ended` (its run's ending). A name for a call the answer already draws (an approval's, a question's, a trade's, a saved rule's or a deposit ask's) places nothing more. A `show_cards` call is never one of a turn's steps: the cards its result accepted stand in the answer at the call, after the words written before it, and it can name a read of an earlier turn. Words still streaming are the last turn's last parts, so a card shows as soon as its line is whole. A read draws a card only where the agent placed it: draw `blocks` after the words of a `legacy` turn that placed none, and leave the reads of any other turn in its steps. |
| `Turn`, `TurnPart` | A turn, and one part of its answer: `{ kind: "words", key, text, item? }`, `{ kind: "card", key, name, tool, focus? }`, `{ kind: "cards", key, tools, focus? }`, or `{ kind: "item", key, item }`. A `cards` part is several reads of one kind that one `show_cards` call named together: draw Solana tokens as one list, and any other kind one card after another. `focus` is what the call said matters inside the cards: token ids, mints or symbols. |
| `MAX_PLACED_CARDS` | The most cards a turn places (3), by card lines and `show_cards` calls together; a name past them draws nothing. |

## Replies

| Export | Description |
| --- | --- |
| `splitReplyNextSteps(text)` | A reply's `body`, apart from the `nextSteps` it suggests and the `shareLines` it wrote for an app that shares answers (`context.renders` with `share`). |
| `ReplyParts` | `{ body, nextSteps, shareLines }`. |
| `splitReplyCards(text)` | A reply in order: its words and the cards it places (`[card r7k2q]` lines, or several side by side on one line, each placed in order), as `ReplyPiece[]`. A card line inside a fenced block is text; the start of a card still streaming is left out. |
| `ReplyPiece` | `{ kind: "text", text }` or `{ kind: "card", name }`. |
| `replyCardName(callId)` | The name a read's card goes by, from its call id alone, exactly as the host gives it to the agent. |
| `withoutReplyCards(text)` | A reply's words with every card line left out, for an app that draws no cards. |
| `replyContext(thread.items)` | Each asset replies name, with its icon and trend line, by symbol. When the thread's reads gave one ticker to several coins (Dogecoin and Binance-Peg Dogecoin are both `doge`), it is the one your token list's `marketId` names, if the thread read it; otherwise the latest read's. |
| `ReplyContext`, `ReplyAsset` | What it returns, and one asset of it, with its `tokenId` where the thread or the token list gives one. `ReplyContext.ticker(word)` is the asset a word of the reply's own text names, spelled exactly as the thread or the token list spells it. |
| `rehypeReplyFigures`, `rehypeReplyTables`, `rehypeReplyCitations`, `rehypeReplyTickers` | The rehype passes behind colours, panels, source chips and linked tickers, for your own Markdown renderer. Changes are wrapped in `span[data-change="up\|down\|flat"]`, and each word that could be a ticker, outside code and links, in `span[data-ticker]`. |
| `signedFigures(text)` | Where each signed change sits in text, and which way it moved. |
| `Direction` | `up`, `down` or `flat`. |
| `linkSource(href)` | A link's host, and the data provider behind it if Fin knows it. |
| `providerReportedAs(id)` | The data provider a tool result names, with its logo. |
| `SourceProvider` | `{ id, name, logo? }`. |

## Activity

| Export | Description |
| --- | --- |
| `activityStep(item, ended)` | One tool call in words, with its source and time: `activityStep(item, runEndedAfter(thread, item))`. |
| `activitySummary(steps)` | The line that sums the steps up. |
| `ActivityStep` | One step. |

## Result cards

| Export | Description |
| --- | --- |
| `toolBlock(item)` | What a completed call's result draws: an `automation`, the `wallet`, `orders`, `contacts`, a `price` (a `market_history` read of one asset) or a `comparison` (of several), `vaults` (an `earn_vaults` read), `predictions` (a `prediction_markets` search), a `predictionMarket` (a `prediction_market` read), a `predictionPreview` (a `prediction_preview` walk), a `tokenCandidates` (a `solana_token_search`), `memecoins` (a `memecoins_top` list), a `solanaToken` (a `solana_token` read), `solanaHoldings` (a `solana_account` read), a `firing` (an automation's run placing its sealed perps order: `PerpsFiringCard`, with the `automationId` to read), a `deposit` (a `deposit_request` result: what a request lacks, for the deposit your own app draws, standing in the turn's `answer` where the call happened, never among its `blocks`; `FinEntry` draws nothing for it), or `null`. A contacts lookup that matched nobody draws nothing; one that found the user has none saved draws the empty card. A history read with no asset observed, a prediction search that found no event, a token search that found no token and a memecoin list with no row draw nothing, and so does a Solana read whose result does not parse as the `/v1` shape it must have. |
| Grid tool blocks | `toolBlock(item)` also returns `grids` for the grid `grid_create`, `grid_pause`, `grid_resume` or `grid_cancel` returned, or the page an `intents_grids` read returned. A grid read that found none draws nothing. |
| `ToolBlock` | Its result, with the typed data each card takes. |
| `AutomationReceipt`, `WalletReading`, `LimitOrderView`, `ContactsLookup`, `GridOutput` | What `AutomationCard`, `WalletCard`, `OrdersCard`, `ContactsCard` and `GridCard` take. A `WalletReading` row carries an optional `priceStatus` (`HoldingPriceStatus`); one this version does not know reads as absent. |
| `EarnVaults`, `EarnVault` | What `VaultsCard` takes from an `earn_vaults` read (`kind: "vaults"`): each tradable vault's name, provider, chain, share token, payment asset, minimum, fees and share price as the read gave them, its provider's current `rate` (`{ percent, type, source, observedAt }`, or `null` when none could be read, or the read predates rates), and how many vaults are unlisted. |
| `runProgress(thread, key)`, `RunProgressView`, `RunProgressStep` | The steps of the run an item belongs to, as they happened, for `RunProgress`: `null` unless the run opened an approval and took two steps or more. Its `request` is the run's first message as the user reads it back, a chat card's `mint <address>` shortened. |
| `firstApprovalOfRun(thread, key)` | Whether an approval is the first its run opened, where `FinEntry` draws the progress. |
| `runReceipt(thread, key)`, `RunReceiptView`, `RunReceiptLine`, `ReceiptAmount` | What the run an item belongs to moved, from its settlement receipts, for `RunReceipt`: `null` until it ended with two swaps or more settled. |
| `PriceHistory`, `MarketComparison`, `PricePoint` | What `PriceCard` and `ComparisonCard` take: each asset's figures as the tool's own decimal strings, its ticker from the reviewed market catalog, and the line to draw (`points`: the daily `series` when the read asked for it, dated; else the trend, undated). A `PricePoint` is `{ at, priceUsdDecimal }`; a loader's points carry `at` as an ISO date-time. |
| `PredictionSearch`, `PredictionEvent`, `PredictionMarketLine` | What `PredictionsCard` takes from a `prediction_markets` search (`kind: "predictions"`): its `status` (`open`, or `settled` when the call asked for closed events), when it was read, the query, and each event with its title, venue `url`, end date, volume, liquidity, how many markets were left out and the markets shown. A market carries its `marketSlug`, question, short label, two outcomes with their prices, its spread and `weakQuote`, and for a settled market `resolvedOutcome` and `closedAt`. Every figure is the tool's decimal string. |
| `PredictionMarketDetail` | What `PredictionMarketCard` takes from a `prediction_market` read (`kind: "predictionMarket"`): the question, venue `url`, end date, `open` (trading), `closed` (the venue closed it; a market that is neither is inactive) and `acceptingOrders`, two outcomes with their prices (`null` when unpriced), volume, liquidity, the venue's cleaned `rules`, the resolution source's host, `resolvedOutcome` and `closedAt` for a closed market, and `readAt`. |
| `PredictionPreview` | What `PredictionPreviewCard` takes from a `prediction_preview` walk (`kind: "predictionPreview"`): the market, question and outcome, `depth` (`budget_spent`, `book_too_thin`, `below_minimum` or `no_asks`), the stake, shares, cost, unspent amount, average, best and worst price, levels used, the venue's minimum, when the book last changed (`bookUpdatedAt`) and `readAt`. Fees are not included and it is never a quote. |
| `PredictionBlock` | The three prediction-market variants of `ToolBlock`. |
| `SolanaTokenSearch`, `SolanaTokenList`, `SolanaTokenDetail`, `SolanaAccountRead`, `SolanaBlock` | What the Solana cards take, exactly the `/v1` shapes the tools return: a search with its candidates (`kind: "tokenCandidates"`), a ranked list in one lane and window (`"memecoins"`), one token with its stats and `risk` (`"solanaToken"`, with the `view` its read asked for: `price` by default, `safety` or `trading`, so a card can open on what the person asked about), and the agent's Solana account (`"solanaHoldings"`), which is either the account with its holdings or the typed answer that it has `no_account` or that it is `unavailable`. `SolanaBlock` is the four variants of `ToolBlock`. Every figure is the tool's own decimal string, and a token is named by its mint. |
| `SOLANA_RISK_COPY`, `riskFlagViews(risk)`, `worstRiskFlag(risk)` | Every risk flag Fin raises in plain words, a `label` and the `line` that says what it means for whoever holds the token (`The creator can freeze your tokens, so you might not be able to sell them`). `SOLANA_RISK_COPY` has an entry for each flag Fin can raise, so a flag with no words fails typecheck. `riskFlagViews` lists the raised flags with their words, the ones that refuse a buy first and the soft ones by how much they matter, and `worstRiskFlag` is the first. `RiskFlagView` is one of them and `RiskFlagCopy` its words. |
| `riskLevelView(level)`, `RiskLevelView` | A token's overall verdict as a `label` and a `tone` (`neutral`, `caution` or `danger`): `No flags raised`, `Medium risk`, `High risk`, `Can't be bought` or `Unknown risk`. There is no tone for safe: the checks look at a token's setup and its market data, which cannot promise it is. |
| `riskWarnings(risk)`, `RiskWarning` | The warnings a token wears as chips, worst first: `Unknown risk` when Fin could not read its setup, then each flag raised, the ones that refuse a buy first, each a `label` and a `tone` (`danger` refuses a buy, `caution` is a warning to read). None for a token with no flag raised, which the Solana cards and the fin app draw with no chip at all. |
| `searchContenders(search)` | A search's candidates as `TokenCandidatesCard` offers them: `contenders`, the ones that share the name or symbol asked about (or, when the search is ambiguous, the top match's symbol), those Fin would buy before those it wouldn't (`tradable`), verified first and then by liquidity, deepest first; `others`, the rest in the search's own order, which wait behind Show more; and `shared`, a symbol two contenders or more carry, which the card asks about (`Which WIF?`), or `null`. A search none of whose candidates bears the words asked offers its best match first. |
| `solanaRisks(thread.items)` | What a chat's Solana reads found of each token's risk, by mint, the latest read of a token winning: the `tokenRisks` an approval card takes so a Solana ticket wears its token's worst warning. It parses every Solana read in the thread, so keep its answer for as long as `thread.items` is the same list; `FinEntry` does. |
| `withShortMintMentions(text)` | A message as the user reads it back: each `mint <address>` a chat card wrote (`Use BONK, mint DezX…B263`) shortened as every mint is shown, for your own bubble, queue and title. Any other address stays whole, and the message sent keeps the mint whole for Fin. |
| `tokenAge(createdAt, observedAt)`, `organicShare(stats)`, `collidingMints(tokens)` | A token's age at the moment of the read, never by the reader's clock, as `12m`, `5h`, `3d`, `4mo` or `2y`, and `null` when the venue gave no creation time; the share of a window's volume the venue judges organic, as a whole percent worked from the exact figures (`63%`), and `null` when it cannot say; and the mints in a list whose symbol another token shares, which a card shows shortened so look-alikes can be told apart. |
| `automationIdsOf(thread.items)` | Every automation the thread created, edited or archived, to read each as it is now. |
| `gridIdsOf(thread.items)` | Every grid the thread created, changed or read, to read each as it is now for `FinEntry`'s `grids.current`. |
| `RENDERED_CARDS` | The cards Fin's blocks draw, for `context.renders`: `receipts`, `automations`, `balances`, `orders`, `contacts` and `grids`. |

`AutomationReceipt` accepts retained creation receipts and revision-bound edit
receipts (`edited` or retry `existing`). `toolBlock` renders completed edits from
their persisted `tool.result`, keyed by call identity; durable replay restores the
same receipt, not a client-reconstructed edit. Refresh your shared owner read on
each committed edit revision. `AutomationCard` ignores an older cached definition
while that read catches up, so chat and the automation page converge on the same revision.

An `automations_archive` result folds through the ordinary `tool.result` replay
path and draws an `automation` block. Its `AutomationReceipt.status` is
`archived`, with `contractRevocation` preserved as `none`, `confirmed` or
`pending`. Reconnect/reload must replay stored events, not reconstruct an
archive from assistant prose. Pending remote acknowledgement remains pending
in the receipt; never infer it from a completed run.


When starting a run, also send `context.country` from your server's edge geolocation with every
message; see [Tokenized stocks](/concepts#tokenized-stocks) for country and purchase restrictions.

## Approvals

| Export | Description |
| --- | --- |
| `NearIntentsContract` | A money approval's contract (`type` `near_intents_transfer`), or an automation's grant. `ContractTerms` reads it. |
| `approvalContent(approval, { holdings?, now? })` | What the card shows: `headline`, `terms`, `approveLabel`, whether it is `readable`, the optional `risk` notice, and the exact frozen `edit` when this is an automation edit. Render `risk` before approval without hiding it: Polymarket funding explains that its bound covers only the first leg and final pUSD is estimated. A Solana buy, sale, funding or withdrawal reads from its exact grant: its `terms` are its figures (`You pay`, `You get`, `Max loss`, `Valid until`), then what its card keeps behind Details, the token address and its `copy` action among them, and the ticket draws all but `Valid until`, whose time its band's countdown already shows; `holdings` that price a Solana token by `solana:<mint>` add an estimate to `You get`. A missing, mismatched or multi-execution grant is not `readable`. A standing Solana grant on an `automation_create` approval reads the same way, its `headline` the rule's sentence with every price-threshold digit and its `approveLabel` `Approve automation`, when the host's contract and the stored definition agree on every term. |
| `TermRow` | One row of `terms`: `label`, `value`, `mono?`, `tone?` (`caution` for the term to read first, such as a loss bound above 3%) and `copy?` (`{ text, label }`, a button beside a shortened value that copies the whole). |
| `ApprovalContent` | What it returns. |
| `deriveApprovalState({ approval, … })` | Where an approval stands, never past what the journal proves: pending, denied, expired, executing, settled, failed and the rest. A limit order ends `placed`, `not_placed`, `cancel_requested`, `not_canceled` or `unconfirmed`, never `executed`. A perps margin change ends `executed` labelled `Applied`, `not_executed` labelled `Not applied`, or `unconfirmed`. Polymarket delivery to the bridge stays awaiting, not settled; an unverified pUSD credit never advances it to funded. A Solana call's `label` is the step it is on (`Funding your Solana account`, `Swapping on Solana`, `Sending back to your wallet`) or how it ended (`Done`, `Partly done: SOL is in your Solana account`, `Partly done: SOL is with 1Click` for a sale or a withdrawal whose transfer to 1Click landed and whose outcome left no SOL in the account, `Partly done` with a line to check the Solana account when the outcome says neither, `Didn't run (expired)`), from the same journal and outcome the card reads. |
| `deriveExecutionState(input)`, `ExecutionState`, `ExecutionStateInput` | The financial state of a tool call without a per-call approval. Pass its `tool`, `outcome`, running/ended facts and available execution evidence. Solana calls use their own outcome status, so a completed tool result remains awaiting, partial or refused until its financial evidence says otherwise. |
| `deriveSolanaReceipt(approval, outcome)` | A Solana call's receipt from its own outcome; only the approval's `tool` and optional `contract` are needed, so a standing occurrence can pass `{ tool }`. It returns the receipt, or `null` without a Solana detail: `title`, `status`, `rows` (paid, received, average price, network fees, SOL left in the account, every figure exact), the transactions it signed and the follow-ups a partial ending offers. What `SolanaReceipt` takes. |
| `SolanaReceiptView`, `SolanaReceiptTransaction` | What it returns, and one transaction of it: its `purpose` (`swap` or `sweep`), state and whole `signature`. |
| `ApprovalState`, `ApprovalViewState` | What it returns, and the state's name. |
| `SwapRow` | One frozen action's display state. A terminal blocked row can carry `failure` with its bounded cause category and, for a verified price limit, quote terms in the frozen asset's exact units. |
| `executionRecoveryChoices(outcome, candidates?)` | Verified fresh-review choices from the result wrapper or a later owner-scoped status read. Claimed actions require an explicit verified `refunded` or `not_executed` candidate. A newly proven unclaimed action without a historical refusal has category `unclaimed`; it carries no invented failure cause. This is display evidence, never spending authority. |
| `executionRecoveryClaimsAreTerminal(outcome, execution)` | Whether all original claims and signed journal siblings have terminal receipts. A later receipt outranks an older uncertain result; an unclaimed candidate never erases an unresolved signature. |

| `contractHeadline(contract, definition?)` | The sentence naming a proposal, as the card, chip and activity row word it. |
| `approvalConsent(input)`, `ApprovalConsent`, `ApprovalConsentInput` | Reads an approval once: its state, definition, contract display and the one view it has (`card`, `order`, `perps`, `prediction`, `predictionOrder`, or `solana`), its exact terms and headline. A request no view reads is `unreadable` and cannot be approved. |
| `decisionEvidence(thread, approvalId, { format?, now? })` | What a pending decision is based on, for its card: `based`, the completed reads of the decision's own turn that share its subject, the latest read per subject (for a Solana buy or sale the Solana account and the coins traded, the coins of a multi-coin sale on one row; for a NEAR Intents swap, send or withdrawal the agent wallet, the contact it pays and the history of the assets it trades), each an `EvidenceRead` with the `tools` behind it to open in place, a `title`, a `detail` and its `icons`; and `after`, what the person holds once it runs, from the latest read of those holdings less what the decision spends and plus what it buys at the price its reads carried, or `null` without such a read. `null` for an approval the thread does not hold or one no longer pending. Every figure is exact decimal arithmetic; `format` takes your own number formatters so the words read as your app does. |
| `DecisionEvidence`, `EvidenceRead`, `EvidenceIcon`, `AfterLine`, `EvidenceFormat`, `DecisionEvidenceOptions` | What it returns (`{ based, after }`), one row and its mark (a coin, a chain, the wallet, a person), the line (`{ lead, text }`: "After this buy" "you’ll hold about 121.35 POPCAT and have 5,309.80 USDC left."), the formatters it takes and its options. |
| Grid approvals | `approvalContent` reads a grid from its signed contract; one this version cannot read is not `readable`. `deriveApprovalState` ends a grid tool `executed` with the grid's own status line (`gridStatusLine`), rather than saying a trade executed. `contractHeadline` reads `Trade ZEC in a grid, 1,100 – 1,300 USDC`. |
| `standingDefinition(approval)` | The automation an `automation_create` approval would save. |
| `deriveOrderView(approval)` | A limit-order approval's headline and terms, or `null`. An order that pays with a stablecoin (the token list's `type:stablecoin` tag) reads as a buy priced per the asset bought. |
| `OrderView` | What it returns. |
| `orderTermsView(terms)` | A placed order's terms in the card's words, for an orders screen: `side` (`buy` or `sell`), the `asset` its price is per unit of, the `price` bound in `priceAsset`, `receivesAtLeast`, `headline` and `terms`. Pass `WalletOrder.terms`. |
| `OrderTermsView`, `OrderTermsSource` | What it returns, and what it reads. |
| `orderStatus(order)` | Where an order stands, as `label` and `tone`: `Open`, `Partly filled`, `Cancelling`, `Filled · paying out`, `Filled`, `Cancelled`, `Expired` and the rest. Pass `WalletOrder.observation` or a `LimitOrderView`. A fill never reads done while its payout can change. |
| `OrderStatus` | What it returns. |
| `resolveAsset(term)` | A contract's asset with its symbol and icon, by exact id, never by symbol. |
| `ResolvedAsset` | What it returns. |
| `actionInputPhrase(action, asset)`, `actionOutputPhrase(action, asset)` | One action's input and output in words. |
| `formatEstimateUsd(value)` | An estimate from an exact `Decimal`: `$12.35` below a thousand, `$0.004` below a cent, `$1,235` from a thousand. |
| `Decimal` | An exact decimal, such as `assetUsdValue` returns. Never a JavaScript number. |
| `PricedHolding` | A holding with the price it was read at. |
| `VaultRate` | A curated vault's current rate, `{ assetId, rate }`, as the Earn vaults route lists it: what `ApprovalCard`'s `vaultRates` takes. |

`approvalConsent` intentionally marks `composite` contracts and `composite_execute` requests
unreadable, even if every piece is valid. The shared `ApprovalCard` does not draw basket terms
and remains Cancel-only. An enabled product implementing its own basket card must validate the
whole composite and frozen input, match every piece, and reuse each piece's existing consent
view. One unknown, missing, malformed or mismatched piece means refusal-only. Never turn a
shared composite into an approvable consent model without a complete packaged renderer. A
cash-out's second piece, `perps_freed_withdrawal` or `prediction_freed_withdrawal`, has no
shared consent view at all (`approvalConsent` reads it as unreadable): it is a withdrawal of what
the exit before it freed, at most `upToRaw`, so a product's own card draws it from those exact
terms and names `upToRaw` only as the most that can come back.

A completed `intents_execute` outcome can carry optional `financialFailures` beside its unchanged
`result`: `nodeFailures` identifies exact unclaimed actions, and historical `preflightFailure`
describes a shared request check. A price-limit diagnostic states the authenticated quoted
minimum or maximum against its approved bound, including fees, spread and slippage headroom;
it is not realized slippage. Skipped dependencies have no invented quote failure.

The metadata wrapper preserves the legacy strict financial result shape. Older React consumers
continue showing that result; older tool-outcome decoders may discard the unknown optional wrapper.
The updated React model validates and combines the metadata only for presentation. Fin derives it
from retained dispatch steps without changing stored operation outcomes, preserving old API and
rollback readers too.

A recovery child's wrapper also carries `recovery`: the original operation id, the mapping from
this card's action indices to original indices, and the child's currently approved loss bound.
Route its next fresh review to that original operation. Root operations omit this field; `null`
means no safe mapping was proved, so expose no recovery control. This routing context grants no
spending authority. The backend excludes settled or uncertain family attempts and independently
proves any terminal failed attempt eligible before admitting a replacement.

A later original receipt can resolve a result that was uncertain when the run ended. Read the
owner-scoped `remaining-actions` endpoint before offering another attempt, bind its `operationId`
to the requested operation, and pass ready `candidates` through `remainingRecoveryEvidence` on
`FinEntry`/`ApprovalCard`/`ToolCallCard`. Status failures expose a status-only retry. Never prepare
an attempt automatically. The Fin app aborts superseded reads, rejects another account's or
operation's response, and reads once per changed receipt or explicit retry without polling.
Fresh unclaimed evidence may clear stale checking/quoting progress to `Not started`; actual claims,
signatures and terminal receipts retain precedence. No old blocked row means no inferred cause.

If drawing your own approval card, an `ApprovalContent.edit` must be rendered as
the exact target `automationId`/`snapshot`, current definition, requested `changes`,
complete `result` and prior used/reserved/resulting remaining allowance **before**
offering approval. Its empty ordinary `terms` array is not permission to show only
the headline. Offer only cancellation when `readable` is false, and retain the
existing owner-signature flow whenever either definition has a financial contract.
Prefer `ApprovalCard` when you do not implement that full exact presentation.

## Grids

A grid is one signed contract for a range of resting limit orders that re-arm as they fill. These
read it exactly: prices stay decimal strings, amounts atomic units, and every figure is bigint or
`Decimal` arithmetic rounded once where it is shown.

| Export | Description |
| --- | --- |
| `gridApprovalView(approval, { holdings?, now? })` | A pending `grid_create` approval as its card draws it, from the signed grid contract: `headline`, `subline` (`9 levels · 30 days`), `approveLabel`, the `base` and `quote` assets, the `band`, the `stats` (`Each cycle`, what one cycle earns at least; `Buys rest`, the quote its buys use at the start; `Each order`, each order's size), the `notes` on the card's face (what happens outside the range, and that the idle cells never place an order), `cautions` (a pinned precision the token list disagrees with), every term in `terms`, and the `footnote` (`3 orders`). `null` for any other contract and for a grid contract this version cannot read. `holdings` only places an estimated now dot. |
| `GridApprovalView` | What it returns. |
| `gridView(grid, { price?, now? })` | A grid read (`GridOutput`) as `GridCard` draws it: `title`, `eyebrow` (`Grid · day 6 of 30`), the compact `headline`, its `status` badge and `statusLine`, the `stats` (earned, buys and sells resting, the base it holds), the `band`, the cells with completed cycles in `fills`, the compact `summary`, the `stalled` count, and whether it `canPause`, `canResume` or `canCancel`, or is `final`. |
| `GridView`, `GridStatus`, `GridFill`, `GridStat` | What it returns, its badge, one cell's completed cycles, and one figure (`label`, `value`, `detail`, `tone`). |
| `GridBandView`, `GridBandCell`, `GridBandSide` | What `GridBand` takes: the `levels`, the `cells` (`{ side, resting?, cycles? }`, `side` `buy`, `sell` or `idle`), the `price` now and the `unit`. |
| `gridHeadline(terms)` | The sentence naming a grid from its terms. |
| `gridStatusLine(grid)` | Where a grid stands, in one sentence: `Running: its orders rest at 1Click and re-arm as they fill.` |
| `GridOutput` | A grid as Get a grid and the grid tools return it: the SDK's `Grid`. |

What a cycle earns at least is the sale's minimum receive (the quantity at the cell's high level,
rounded down to the quote's smallest unit) less the buy's cost (the quantity at the low level,
rounded up): the figure the two orders guarantee, before fees.


## Automations

| Export | Description |
| --- | --- |
| `automationStatus(automation)` | Its status badge: label and tone, `Needs you` while `waitingForOwner` is set, `Setup needed` while an owner webhook has no key, and `Watching news` or `News checks paused` for a news exit (`rule.news`), which never needs a webhook. |
| `monitoringLabel(automation, nowMs)` | The sentence beside the badge. |
| `automationCheckSummary(automation)` | How often it checks. |
| `automationConditionSummary(automation, catalog?, price?)` | What it waits for, with assets named. A condition that reads only Solana tokens' prices names each token by its symbol (or its shortened mint, never the whole one, whatever catalog is at hand) and states each price level in `price`'s words, `formatTokenPriceUsd` by default (`$0.0₅495`, not the 23 digits it was saved to). |
| `withReadablePrices(rule, price)`, `PriceWords` | The rule as its sentence words it: each level a Solana token's price is compared with, in `price`'s words. Only the sentence reads the copy; the rule stays as saved everywhere else. |
| `readableRuleSummary(rule, { utc? })` | Its schedule and limit in words. |
| `firingSummary(rule)`, `deliverySummary(rule)` | What one firing does, and how it delivers. |
| `conditionSummary(condition)` | A condition as an expression. |
| `contractStatus(contract, nowMs)` | Its grant's state: `Active`, `Revoked`, `Expired`, `All executions used` or `Spend cap used`. |
| `ContractStatusLabel` | Those labels. |
| `spendCapProgress(contract)` | A capped grant's budget, such as `Budget 5 USDC (1 spent, 4 left)`; `null` without a cap. |
| `perpsAutomationActionSentence(contract)` | What one firing of a `perps_automation` grant does: `Open a $200.00 BTC long at 3× cross`, `Reduce your BTC long by 50%`, `Close your ETH short` or `Add 25 USDC margin from your agent wallet`. |
| `perpsAutomationExitsPhrase(contract)` | An `open` grant's native exits from the mark it opens at, such as `take-profit +10%, stop-loss −5%`; `null` without any. |
| `perpsAutomationActionLine(contract)` | The same with its one bound, and an open's exits: `… · market within 1% of mark` or `… · max loss 3%`. |
| `perpsAutomationLimits(contract)` | How often until when: `up to 3 times · until Sep 12`, or `once · until Sep 12`. |
| `automationCanToggle(automation)` | Whether it can pause or resume. A revoked grant cannot resume. |
| `Occurrence` | One firing. |
| `runPlace(run, automation)` | A run's place among its automation's: `4 of 30`, or `4` past or without a limit; null for an exit. |
| `automationRunCount(automation, listed?)` | How many times it has run. |
| `occurrencePresentation(occurrence)` | A firing's status, in words and tone, for every `state`, a recorded ending first. |
| `occurrenceSelectionLabel(selection)` | What a firing selected. |
| `occurrenceThreadLabel(occurrence)` | A firing's conversation label. |
| `automationTime(value, rule?)` | A time in the automation's calendar time zone. |
| `durationLabel(seconds)` | A duration in words, such as `1 hour 30 minutes`. |

## Amounts and values

Exact decimal arithmetic on Fin's strings, rounded once where shown, never through a JavaScript
number.

| Export | Description |
| --- | --- |
| `formatUsdCents(cents)` | `"$10.15"` from integer cents. |
| `formatUsdCompact(usdDecimal)` | `"$1.2B"`, `"$34.5M"`, `"$870K"` from a decimal string: cut to one decimal place, never rounded up, so a figure never overstates; under a thousand, `"$420"` or `"$0.004"`. |
| `formatTokenPriceUsd(priceUsdDecimal)` | A token's price from a decimal string: to the cent from a dollar up (`"$104.20"`), and below a dollar four significant digits (`"$0.0123"`), so a memecoin's price is not blurred to the cent. |
| `formatAssetAmount(asset)` | An exact amount at the asset's scale, such as `1.999999`. |
| `formatAssetSummary(asset)` | A row's amount: four decimals, cut not rounded, `< 0.0001` below. |
| `formatAssetFigure(amountRaw, decimals)` | A card's amount: four significant digits, cut not rounded (`0.0000234`); grouped whole units from a thousand. |
| `assetUsdValue(asset)` | A priced amount's exact dollar value; `null` without a price or scale. |
| `displayAssetUsdCents(asset)` | That value in whole cents. |
| `displayPortfolioUsdCents(assets)` | A wallet's total in cents, rounded once; `null` if any holding is unpriced. |
| `displayPricedUsdCents(assets)` | `{ cents, unpriced }`: the total of the priced holdings in cents, rounded once, and how many have no price. Never blank. |
| `priceStatusLabel(status)` | What a card says of a price that isn't a fresh close: `"Carried"`, `"Last trade"` or `"No price"`; `null` for `priced` or no status. |
| `HOLDING_PRICE_STATUSES`, `HoldingPriceStatus` | How a balance read found a price: `priced`, `carried`, `last_trade`, `unpriced`. |
| `holdingDisplay(asset)` | A holding with the token list's name, icon and network. |
| `holdingId(asset)`, `holdingTokenId(asset)` | A holding's id, and its token when the list knows it. |
| `PortfolioHolding`, `AssetAmount`, `PricedAmount` | A holding; an amount at its scale; and one with its price. |

## Tokens and chains

These read the configured `TokenResolver`; [Tokens and chains](/tokens-and-chains) explains
them.

| Export | Description |
| --- | --- |
| `getTokenMetadata(tokenId)` | A token's metadata by exact id; `undefined` if the list lacks it. |
| `withTokenMetadata(asset)` | An asset with the list's symbol and name; nonempty catalog artwork takes precedence, otherwise its supplied `iconUrl` is retained. Amounts are unchanged. |
| `finAssetId(tokenId)` | Fin's opaque id for a token, derived as Fin does. |
| `catalogTokenId(assetId)` | The token behind one of Fin's opaque ids. |
| `assetChain(tokenId)` | The chain a token comes from; a `solana:<mint>` id is on `solana`. |
| `solanaTokenId(mint)`, `solanaMintOf(tokenId)`, `SOLANA_TOKEN_PREFIX` | A Solana token's id, `solana:<mint>`, the mint behind such an id, and its prefix. The resolver keys Solana tokens this way. |
| `shortMint(mint)` | A mint shortened the way a grant's headline shortens it: its first four and last four characters, `DezX…B263`. |
| `solanaTokenIcon(mint)` | A Solana token's icon as your resolver names it by `solana:<mint>`, or `null`, which draws the mint's monogram. A read's `iconUrl` is a path of Fin's API that a browser reaches only through your server, so your resolver names your server's address for it. |
| `SOLANA_SOL_ID` | `solana:sol`, the SOL the agent's own Solana account holds, as `SolanaHoldingsCard` names it to `routes.asset`: no mint, so `solanaMintOf` answers `undefined` for it. |
| `assetNetwork(tokenId)` | That chain's display name. |
| `tokenNetworkName(chain)` | A chain's display name. |
| `networkIcon(chain)` | A chain's badge for light and dark, or `null`. |

## Fixtures

`@nearai/financial-agents-react/fixtures` holds realistic Fin data, to draw every state of Fin's blocks in your
stories and tests without a live conversation. Every token it names is on near.com's list.

```tsx title="approval.stories.tsx"
import { ApprovalCard } from "@nearai/financial-agents-react";
import { oneShotApproval, oneShotContracts, PINNED_NOW } from "@nearai/financial-agents-react/fixtures";

export const PendingSwap = () => (
  <ApprovalCard
    approval={oneShotApproval(oneShotContracts.singleSwap)}
    busy={false}
    onDecide={() => {}}
    now={PINNED_NOW}
  />
);
```

| Group | Fixtures |
| --- | --- |
| Conversations | `fixtureEvents`, a named list of events per moment (`plainReply`, `thinking`, `streaming`, `toolRunning`, `approvalPending`, `ruleCreated`, `balancesThenSwap`, `ordersListed`, `gridStarted`, `gridsListed`, `runFailed` and more), named by `FixtureName`; `foldFixture(name)`, the thread they fold to; `foldConversation()`, several turns |
| Trades to settlement | `executionFixtures`, a trade's endings (`settled`, `awaiting`, `partial`, `unconfirmed`, `failed`, `refused`), named by `ExecutionEnding`; `foldExecution(name)` at a step (`ExecutionStep`) or ending; `foldLateSettlement()`, `foldBuriedExecution()`, `lateSettlement`, `executionTimeline()`; `restrictedApprovalEvents(approve)`; `executionCardProps(thread)` |
| Solana trades | `solanaCalls` (the calls the model proposes: `buyBonk`, `buyBonkTight`, `buyWithSol`, `buyNewCoin`, `buyLookalike`, `sellHalf`, `sellAllKeepSol`, `sellExact`, `fund`, `withdrawExact`, `withdrawAll`), `solanaApproval(call)` (a pending approval whose grant is the host's own derivation of the call), `solanaStandingApproval(definition)` with `solanaStandingDefinitions` (`dailyBonk`, `everySixHours`, `dipBuy`, `takeProfit`, `stopLoss`, `weeklySale`, `weeklyWithSol`, `datedBuy`, `newCoinDip`, `lookalikeDip`, `everyPriceUpdate`) and `solanaPriceRule(token, comparator, usd)` (an `automation_create` approval for a standing buy or sale), `solanaFixtureTokens(base)` (a resolver that knows three real mints by `solana:<mint>`, on top of `base`), `solanaPricedHoldings(wallet)` (a wallet's priced holdings with the prices a chat's Solana reads carry, which price a Solana ticket's estimates) and the mints `SOLANA_BONK`, `SOLANA_WIF`, `SOLANA_WIF_LOOKALIKE` and `SOLANA_NEW_COIN`; `foldSolanaBuy(step)`, `foldSolanaBuyEnding(outcome)`, `foldSolanaSell(outcome?)` and `foldSolanaReconciled()`, the thread after a purchase or sale reaches a step or ends as an outcome says, with `solanaBuyResults`, `solanaSellResults` and `solanaKeepSolResult` as the outcomes and `solanaTradeProps(thread)` for the card |
| Approvals and contracts | `oneShotApproval(contract)` with `oneShotContracts` (`singleSwap`, `exactOutput`, `sellHalf`, `sendToThree`, `twoBuys` and more); `standingApproval(definition)` with `standingDefinitions` (each a `StandingDefinition`, `tloMonthlyHarvest` a vault deposit with a scheduled harvest), `perpsStandingDefinitions` (each a `PerpsStandingDefinition`: `reduceNearLiquidation`, `closeOnFunding`, `addMarginOnRatio`) and `pushExitDefinition`; `editApproval` (the frozen current/patch/result and carried allowance for a signed edit); `btcThresholdRule(usd)`, `tokenPriceThresholdRule(token, usd)`; `limitOrderPlaceApproval()`, `limitOrderCancelApproval()`, `limitOrderPlaceInput`, `limitOrderNearInput`, `limitOrderCancelInput`; `pricedHoldings`; `vaultRates` |
| Solana reads | `SOLANA_TOKEN_SEARCH` (a search for `wif` that matched three tokens, two of them named WIF), `SOLANA_TOKEN_SEARCH_EXACT`, `SOLANA_TOKEN_LIST` and `SOLANA_TOKEN_LIST_NEW`, `SOLANA_TOKEN_DETAIL` and its variants (`_ON_CURVE`, `_NO_FLAGS`, `_BLOCKED`, `_UNKNOWN`), `SOLANA_ACCOUNT` and its variants (`_LOOKALIKES`, `_EMPTY`, `_UNREADABLE`), `SOLANA_NO_ACCOUNT` and `SOLANA_ACCOUNT_RECORD_UNAVAILABLE`: the four reads' results as the tools return them, each checked against the contract at load; `foldSolanaResearch()` folds a search, a list, a token read and the account into one conversation |
| Prediction markets | `PREDICTION_SEARCH`, `PREDICTION_SETTLED_SEARCH`, `PREDICTION_MARKET`, `PREDICTION_SETTLED_MARKET`, `PREDICTION_PREVIEW`, `PREDICTION_PREVIEW_THIN`: the three reads' results as the tools return them; `predictionResearch` in `fixtureEvents` folds a search, a market read and a preview into one conversation |
| Tokens | `USDC_ETH`, `USDC_NEAR`, `USDC_BASE`, `ETH`, `BTC`, `ZEC`, `NEAR`, `SOL`, `TLO` (Taler USDC's vault share), and `UNLISTED` (one the list lacks) |
| Automations | `automationFixture()`, `finiteAutomationFixture()`, `contractAutomationFixture()`, `contractAutomationWith()`, `perpsAutomationFixture()`, `measurementAutomationFixture`, `webhookAutomationFixture`, `automationRunFixture()`, `simpleRule()`, `measurementAlertRule()`, `sourceCatalogFixture`, `sourcePlanFixture()` |
| Grids | `gridFixture()` (a running grid: two buys and a sell resting, five idle cells, five cycles), `newGridFixture()` (just approved, its buys pending), `pausedGridFixture()`, `stoppedGridFixture()` |
| Grid approvals | `gridCreateApproval()`, `gridCreateInput` (a ZEC grid: three buys below 1,158.09 USDC, five idle cells above), `gridHoldings` |
| Pinned values | `PINNED_NOW` (the fixtures' clock), `EXPIRES_IN_MS`, `APPROVAL_ID`, `PANEL_WIDTH` (the cards' width in stories) |

Solana execution views include optional `solanaProgress`: the latest `solana.progress`
snapshot for the operation; a single-coin sale's carries `paid`, what its swap sold, once the
swap landed, so a card need not estimate it from a balance read afterwards. `threadReducer`
ignores an older or repeated revision and links its original `callId` to the tool row,
including standing occurrences. A sale of several coins (`solana_sell_many`) also keeps
`solanaSales`, each coin's latest swap snapshot by its `sale` (a `SolanaSaleProgress`).
Funding receipts remain separate from native attempts; neither a funding receipt nor a confirmed native phase completes
a buy or sale. Approval and tool blocks keep showing stages for an `in_progress` financial
result after the model run ends, then use the operation's final outcome or reconciliation.

A `solana_sell_many` approval is consent the packaged card never reads: the tool is offered only
to a run whose app said it draws the sale (`context.renders`), so `approvalConsent` marks it
`unreadable` (Cancel alone) and the app that asked for it draws its own card. `deriveApprovalState`
still reads where it stands: `Selling coin 2 of 4` from its progress, then from its outcome `Done`,
`Partly done: 3 of 4 coins sold` when the transfer back settled with a coin unsold, and the single
sale's partly-done labels when the transfer back did not finish.
