# Deposits, withdrawals and trades

Each user's agent has its own wallet. The user funds it with a deposit, the agent trades from
it with the user's approval, the user can swap in it from your own screen, and the user takes
money out with a withdrawal. Fin routes and
settles transfers through NEAR Intents (1Click); your app needs no Intents account of its own.
If your app already reads its users' accounts from 1Click, it can read the agent wallet the same
way: see [read the wallet from 1Click yourself](#read-the-wallet-from-1click-yourself).

## Discover the wallet, networks and assets

After [user provisioning and login](/quickstart), read:

```http
GET /v1/users/{userId}/wallet
GET /v1/users/{userId}/wallet/supported-assets
GET /v1/users/{userId}/wallet/balances
```

`wallet` is `null` until the user [creates it](#create-the-agent-wallet) with a signature.

An existing wallet can need a one-time ownership confirmation. When the wallet read returns
`confirmation`, show the complete existing `wallet.intentsAccountId` and explain that the
signature confirms that account without moving funds or granting trade permission. Have the
registered wallet or passkey sign `confirmation.message` unchanged, then send its authorization
to `POST /v1/users/{userId}/wallet/confirm`. Use the returned wallet only after verifying its
ownership receipt against your independently pinned worker key and the connected owner.
Before requesting a signature, parse the message and require purpose `wallet.confirm`,
`walletId` and `requestKey` equal to the reviewed wallet id, and the exact request
`{ walletId, intentsAccountId }` matching the displayed account, with no extra fields. Never
substitute a spending request under a confirmation label.
Cancellation leaves the wallet unchanged; read the wallet again for a fresh message before retrying.

Ownership statements distinguish version 1 (owner-signed creation) from version 2 with
`basis: owner_confirmation` (an existing imported account confirmed by its owner). Their signed
domains are respectively `fin.wallet-ownership.v1\n` and
`fin.wallet-ownership.v2\n`, followed by the exact canonical `statement` bytes.
Both bind wallet, account, agent, owner and deployment audience. Version 2 does not prove that
the key was generated inside an attested worker. A missing or invalid receipt never establishes
ownership; do not trust a key supplied by the response in place of your own pin.

Supported assets returns the current provider catalog. Use returned network and asset
identifiers; do not build your own chain enum or infer an asset from its symbol. A catalog
entry is not a promise that every amount or route has a quote. Execution validates a current
signed quote.

Supported assets and new deposit admission return `503` when the provider catalog is
unavailable or malformed. A withdrawal or swap quote also returns `503` if its catalog lookup
or provider quote request fails: 1Click did not answer, or asked us to slow down (then with
`Retry-After`). These responses carry `reason: "provider_unavailable"` and `retryable: true`.
Do not interpret those failures as an empty catalog, a zero fee, or permission to submit. When
1Click answers the quote by refusing it, usually an amount below what it routes or a pair it does
not offer, the quote returns `400` with `reason: "quote_refused"`: asking again unchanged gets the
same answer, so change the amount or the assets. Recover an interrupted deposit using the
retained request key and exact terms first; an already-admitted deposit does not require a fresh
catalog to return its original instructions.

| Destination or source | `rail` | `network` |
| --- | --- | --- |
| Native blockchain | `chain` | Exact catalog network id |
| Public Intents ledger | `intents` | `near-intents` |
| Confidential Intents ledger | `intents` | `near-intents-confidential` |

These two ledgers are distinct from the NEAR blockchain. The normal portfolio uses opaque
Fin `assetId` values and native asset metadata, so you never parse protocol token ids. The
wallet's `intentsAccountId` is its NEAR Intents account, for apps that read it from 1Click
themselves. An explicit Intents deposit supplies the protocol information necessary for that
advanced signing path.

All amounts are decimal integer strings in atomic units. For six decimals, `"1000000"` is
one token. Keep calculations in integer arithmetic; never round through a JavaScript number.

## Create the agent wallet

A new user has no wallet. The user creates it once, with one signature, usually the first
time they fund the agent. Read the wallet:

```http
GET /v1/users/{userId}/wallet
```

Until it exists, `wallet` is `null` and `creation` holds the message to sign:

```json
{
  "wallet": null,
  "creation": {
    "message": "Fin authorization v1\n…",
    "controllerId": "8f0c…",
    "expiresAt": "2026-09-24T15:04:05.000Z"
  }
}
```

Have the user sign `creation.message` with the wallet they signed in with (see
[supported wallets](/authentication) for how each one signs), then send the signature:

```http
POST /v1/users/{userId}/wallet
Content-Type: application/json

{ "authorization": { "controllerId": "8f0c…", "expiresAt": "2026-09-24T15:04:05.000Z",
                     "signature": { "kind": "evm", "signature": "0x…" } } }
```

Send `controllerId` and `expiresAt` back exactly as you received them. The message is valid for
about five minutes; after that, read the wallet again for a fresh one. Without a signature the
call is refused with `403 signature_required`. Once the wallet exists, calling this again
returns it unchanged.

### In the same signature as sign-in

If you use wallet sign-in, the user can create the wallet with the signature that signs them
in, and sign nothing more. Send `createWallet: true` to
[Start wallet sign-in](/authentication). For a user with no wallet, the answer has
`createsWallet: true` and its message both signs them in and creates their agent. Create the
session with that signature, then, within the challenge's five minutes, send the same challenge
id and signature here:

```http
POST /v1/users/{userId}/wallet
Content-Type: application/json

{ "signIn": { "challengeId": "3f2b…", "signature": { "kind": "evm", "signature": "0x…" } } }
```

Send either `signIn` or `authorization`, not both. A sign-in that wasn't an account-opening one
is refused with `401`. Past the five minutes, use `creation` above instead.

### With a passkey the user just created

Creating a passkey signs nothing, so a user who signs up with one would otherwise confirm twice:
once to create it, once to sign. If your own login just created and verified the passkey, send
`createWallet: true` when you [create the session](/authentication) with it. When the answer has
`createsWallet: true`, send an empty body here from that session within 270 seconds:

```http
POST /v1/users/{userId}/wallet
Content-Type: application/json

{}
```

Only the session that registered the passkey can do this, and only while the user has no
wallet; any other session, or this one after the 270 seconds, gets `403 signature_required` and
uses `creation` above. Where the user's wallet is set up through the Agent API, the passkey still
signs that API's own setup steps.

### Set up an Agent API wallet

The user's wallet can instead be an agent they own in the NEAR Intents Agent API: its key stays in
the Agent API, and its NEAR Intents account is a `0x` address. This is opt-in: ask Fin to enable
Agent API wallets for your partner, or first for a few of your users, once your integration reads
the wallet account routes below. Until then nothing in this section applies to your users and no
response ever carries a `0x` account; a user it is not enabled for never gets one. Once enabled,
`agent_api_wallets` is on in the user's List a user's features.

An Agent API wallet's balance is held by its `0x` account, so the older `intentsAccountId` field
has no truthful value for it, and the routes that name a wallet by it (Get the agent wallet, Create
the agent wallet, Confirm wallet ownership, Get a 1Click session, Get balances) refuse one with
`409 wallet_account_unsupported`. Read every wallet instead with Get wallet account
(`GET /v1/users/{userId}/wallet/account`), Get wallet account balances
(`GET /v1/users/{userId}/wallet/account/balances`) and Open a wallet account session
(`POST /v1/users/{userId}/wallet/account/sessions`). They answer the same bodies, with the account
named by `intentsAccount`:

```json
{ "intentsAccount": { "id": "0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", "kind": "evm" } }
```

`kind` is `near` for a Fin-held wallet (the same id as its `intentsAccountId`) and `evm` for an
Agent API wallet. The older responses carry `intentsAccount` too, always `near`.

To set one up, send the same `authorization` or `signIn` to Start wallet setup instead of Create
the agent wallet:

```http
POST /v1/users/{userId}/wallet/setup
```

The answer is `completed` with the wallet when it was created at once (the user's wallet is not
one the Agent API can own, or your partner is not enabled), or the first step the user signs in
their own wallet:

```json
{
  "status": "signature_required",
  "step": {
    "setupId": "intent_…",
    "step": "agent_create",
    "expiresAt": "2026-09-24T15:09:05.000Z",
    "summary": "Create an agent wallet you own…",
    "intent": { "standard": "eip712", "payload": { … } },
    "policy": {
      "maxSlippageBps": 300,
      "destinations": [
        { "network": "near-intents-confidential", "address": "0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed" },
        { "network": "eth", "address": "0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed" },
        { "network": "hypercore", "address": "0x857cd3362740c16ce4c55af0b81a23aa9e5723db", "venue": "perps" }
      ]
    }
  },
  "wallet": null
}
```

Show `summary`, and tell the user what the wallet they create allows. `policy` says it in Fin's
terms, so you can put it in your own words rather than parse `summary`: Fin's agent may sign swaps
that pay back to the wallet losing at most `maxSlippageBps` of their value in total (fees, price
and slippage together, by 1Click's own USD values; 300 is 3%), and payouts only to
`destinations` (their own NEAR Intents account, on
`near-intents-confidential`, the wallet they signed in with, and the agent's own venue accounts,
each marked with its `venue`); nothing else. Fin lists the agent's own account on each venue the
user can use when they create it (`perps` its Hyperliquid account, `prediction` the Polymarket
bridge's deposit address for its Polymarket account, `solana` its Solana account), so funding
those needs no second signature; a destination with `venue` funds the user's own account there,
so describe it that way, not as a payout. A venue Fin could not name in time is left out and is
allowed later by its venue (below). A `grant_issue` step carries `accessExpiresAt` instead: when
the access the user gives Fin's agent ends, unless
they renew it sooner. Either field is absent when Fin cannot state it for the step; show
`summary` alone then.

Before the user signs `agent_create`, the Agent API requires you to show its Owner Terms,
OutLayer's terms and its risk notice, word for word:

> This is an experimental, mainnet-only beta service. You may lose all assets you put in this
> wallet, or lose access to them. Keep amounts small.

and to keep evidence that the user accepted them (which user, each document's address and version,
what notice they saw, when), in your own backend. `summary` ends with the notice; it does not
replace showing the terms. Show the notice again before the user funds the wallet (any deposit to
an `intentsAccount.kind` `evm` wallet). Fin does not record this acceptance for you, and the Agent
API team supplies the two documents' addresses and versions. `grant_issue` and later steps need no
new acceptance while the same versions are in force.

Then have
their wallet sign `intent.payload` unchanged, as `intent.standard` says: `nep366` a NEAR delegate
action (`signDelegateActions`), `nep413` a NEAR message (`signMessage`, the nonce decoded from
base64), `eip712` EVM typed data (`signTypedData`), `webauthn` a passkey assertion with the payload
as its request options. Send the intent with the wallet's output added:

```http
POST /v1/users/{userId}/wallet/setup/continue
Content-Type: application/json

{ "setupId": "intent_…",
  "signature": { "standard": "eip712", "payload": { … }, "signature": "0x…" } }
```

The answer is the next step, signed and sent the same way: `grant_issue` (the user lets Fin's
agent use the wallet for a year), then `completed` with the wallet, named by `intentsAccount`.
`provider_unavailable` means a step is still landing: send the same request again. A step past its
`expiresAt` answers a fresh step to sign. Before the year is up, Get wallet account carries
`renewal`: have the user sign it, send it to Renew wallet access
(`POST /v1/users/{userId}/wallet/access/renew`), and complete the `grant_issue` step it answers the
same way.

### Allow a withdrawal destination

An Agent API wallet pays out (withdrawals, sends and the funding of a perps, prediction-market or
Solana account) only to addresses its user allowed; setup allows their own NEAR Intents account,
the wallet they signed in with and the agent's own account on each venue they could use then. A
payout to any other address is refused with
`403 destination_not_allowed` before anything is signed. To allow one, send its network (a network
`id` from List supported assets) and address:

```http
POST /v1/users/{userId}/wallet/destinations
Content-Type: application/json

{ "network": "eth", "address": "0x5AAEB6053F3E94C9b9A09f33669435E7Ef1BeAed" }
```

The answer is the `policy_update` step the user signs, exactly like a setup step: show its
`summary` (its `policy` lists every address the wallet may pay once the user signs, the new one
included), have their wallet sign it, and send it to Continue wallet setup, which answers
`completed` once the address is allowed. An address already allowed answers `completed` at once.
The address is allowed in the NEAR Intents Agent API's spelling of it (an EVM address lowercase,
for one), so allowing either spelling allows both. An address that is not one on its network, or
an account on the public `near-intents` ledger (an Agent API wallet pays NEAR Intents accounts on
`near-intents-confidential` only), is refused with `400` and nothing is asked. The Agent API lets
a wallet change what it allows only every few minutes: sooner, the request is refused with
`429 policy_change_throttled` and `Retry-After` in seconds, and nothing is asked or signed; ask
again once it has passed. Once Fin has disabled the wallet, Continue wallet setup refuses its
pending `policy_update` or renewal `grant_issue` step with `403` before the signature reaches the
Agent API, so nothing is allowed or granted.

The agent's own venue accounts are allowed by naming the venue instead, so you never copy an
address: `perps` (its Hyperliquid account), `prediction` (the Polymarket bridge's deposit address
for its Polymarket account) or `solana` (its Solana account).

```http
POST /v1/users/{userId}/wallet/destinations
Content-Type: application/json

{ "venue": "perps" }
```

Fin names the exact address and chain that venue's funding pays and answers the same
`policy_update` step (its `policy.destinations` shows the account, such as `hypercore` and the
Hyperliquid address), opening the account first when it is new; opening moves no money. A venue the
user cannot use is refused with `perps_disabled`, `prediction_disabled` or `solana_disabled`, and a
Polymarket account still opening with `no_account`: ask again within a minute. Until the account
is allowed, the agent's funding of that venue is refused before any approval opens, its refusal
naming the venue, and a Solana buy the user pays in USDC (Prepare or Place a Solana trade) is
refused with `403 destination_not_allowed` before they sign; allow it once, before the user's first
funding or when that refusal arrives, and the funding can be asked for again.

Two more refusals come with `403` before anything is signed: `agent_slippage_exceeded` when a swap,
trade or transfer would lose more of its value than the wallet's owner allowed (fees, price and
slippage together, by 1Click's USD values at the quote's minimum output; very small amounts lose
more to fixed fees, so a larger amount or a smaller loss bound may pass) or its quote states no
USD value. `agent_api_orders_unavailable` means an order needs wallet setup to enable limit orders,
or its lifetime exceeds this wallet's 168-hour maximum: finish [wallet setup](#set-up-an-agent-api-wallet)
or choose at most 168 hours before trying again. Native Agent API orders are funded when placed.
A transfer the
wallet has signed cannot be called back by freezing or disabling it: it stays valid until its own
deadline (minutes for most, up to 96 hours for a payment into a 1Click deposit).

### Prove the wallet was created for this user

The wallet carries `ownership`: the policy worker's signed statement that it created this wallet
for the owner the user signed in as. Verify it in your own backend, against the worker public key
you pin from your own configuration — never against the key the receipt names:

```json
{
  "id": "0f0c…",
  "intentsAccountId": "8a88e3dd…6f5c",
  "status": "active",
  "provisionStatus": "ready",
  "ownership": {
    "statement": "{\"agentId\":\"…\",\"audience\":\"https://api.example.com\",\"intentsAccountId\":\"8a88e3dd…6f5c\",\"owner\":{…},\"v\":1,\"walletId\":\"0f0c…\"}",
    "signature": "…base64…",
    "workerPublicKey": "ed25519:…"
  },
  "createdAt": "2026-09-24T15:04:05.000Z"
}
```

For this version 1 creation receipt, the signature is Ed25519 by the worker's identity key over
`"fin.wallet-ownership.v1\n" + statement` — the exact bytes `statement` carries. Version 2
confirmation receipts use the distinct version 2 domain described above, and an Agent API wallet's
version 3 receipt (`basis: "agent_api"`, only on the wallet account routes) is signed over
`"fin.wallet-ownership.v3\n" + statement` and names `intentsAccount` instead of
`intentsAccountId`. `@fin/contracts` exports `walletOwnershipMessage(statement)` and
`walletOwnershipStatementSchema` for this. Compare the parsed statement's `walletId`, account,
`agentId` and `owner` with what you asked for, and its `audience` with your deployment; a receipt
that names anything else is not yours. `ownership` is `null` for a wallet created before this field
existed and where the worker answered no receipt, so treat `null` as unproven rather than as a
failure. Pinning the key independently and verifying locally is what makes the statement evidence:
versions 1 and 3 prove owner-signed creation, while version 2 proves owner confirmation. A pin
alone does not prove hardware attestation; that additionally needs verified measurement evidence.
No API response can vouch for itself.

## Open a perps account

Perps is off by default. Your deployment must enable the `perps` feature flag for the user
before opening an account; [List a user's features](/api-reference/users/list-features) says
whether they have it. First [create the agent wallet](#create-the-agent-wallet);
opening its separate Hyperliquid account requires no extra owner signature and moves no funds.

With your API key and the user's Fin session, call [Open a perps account](/api-reference/perps/open-account)
with a UUID `Idempotency-Key` generated once for this request. Send no request body:

```http
POST /v1/users/{userId}/perps/account
Idempotency-Key: 4f3c7d2e-9b1a-4c5d-8e6f-0a1b2c3d4e5f
```

The SDK equivalent is `user.perps.openAccount({ idempotencyKey })`. If the response is lost,
repeat with the same key. An already-opened account keeps its address and creation time.
Opening it yourself is optional: the agent's first deposit or opening order in chat opens it too.
Read it later with [Get a perps account](/api-reference/perps/get-account):

```http
GET /v1/users/{userId}/perps/account
```

The SDK equivalent is `user.perps.getAccount()`. Get returns 404 until the account is opened
and remains available for existing accounts when the `perps` feature flag is off.
Both operations return `PerpsAccount`, with a lowercase `0x` address, ISO `createdAt` and
`state` read live from Hyperliquid:

```json
{
  "address": "0x1234567890abcdef1234567890abcdef12345678",
  "createdAt": "2026-10-07T08:00:00.000Z",
  "state": {
    "status": "observed",
    "observedAt": "2026-10-07T08:01:00.000Z",
    "accountValueUsd": "0",
    "withdrawableUsd": "0",
    "marginUsedUsd": "12.25",
    "positionCount": 1,
    "positions": [
      {
        "coin": "BTC",
        "size": "-0.001",
        "entryPriceUsd": "61250",
        "positionValueUsd": "61.2",
        "unrealizedPnlUsd": "0.05",
        "marginUsedUsd": "12.25",
        "liquidationPriceUsd": "72480.5",
        "leverage": 5,
        "marginMode": "cross"
      }
    ]
  }
}
```

The USD fields are exact decimal strings, not atomic token amounts. Keep them as strings
or use exact decimal arithmetic; do not convert them to JavaScript numbers.
`positions` lists each open position, largest `positionValueUsd` first, up to 100;
`positionCount` counts them all. `size` is signed in the coin (negative is short), and a null
`entryPriceUsd` or `liquidationPriceUsd` means Hyperliquid reported none, not zero.
`positionValueUsd` is the position's notional at the mark price, not money in the account:
its unrealized PnL is already part of `accountValueUsd`, so to show what the user owns, count
`accountValueUsd` alone and never add the positions to it.
When reported, `fundingSinceOpenUsd` is the whole position's funding paid since open,
in exact USD (positive paid, negative received). It is already reflected in the account;
never add or subtract it again from `accountValueUsd`.
If the live state cannot be read, the account still returns with
`state: { status: "unavailable", reason: "…" }`. Show that state as unavailable, never as
zero or proof that opening failed; the account's address and creation time remain usable.

Venue reads have a three-second deadline and a 2 MiB response limit. Network failures,
timeouts and non-success HTTP statuses produce `provider_unavailable`; malformed or
oversized responses produce `invalid_response`. Neither reason invalidates the account.

The agent loads `perps_account`, `perps_positions`, `perps_orders`, `perps_fills` and
`perps_overview` with its perps capability pack in a run admitted with the feature enabled. These read only its own
opened account, never an address supplied in chat, and return exact decimal strings with
bounded lists and explicit truncation. A missing account asks the user or partner to open it.
`perps_markets` reads Hyperliquid's public market list (coin, index, size precision, maximum
leverage, whether it is isolated-only or strict isolated, prices and funding) in every run,
feature or not, so exits can still be placed.
There are no positions/orders/fills HTTP routes in this release; use the account API for
identity and summary state, and the tools for those detailed reads.
When starting each run, report [perps availability](/concepts#perps-availability) with the
optional `context.perpsAllowed` field computed by your trusted server, not chosen by the browser.
Admission saves that report with the opening message and updates the user's latest region
observation only if its timestamp is strictly newer; equal timestamps keep the first committed
value. An omitted field does not clear the latest saved observation. Unlike contacts, the
field belongs to retry identity: changing, adding or omitting it under the same
`Idempotency-Key` conflicts, while an unchanged retry returns the original run without
refreshing the observation time. This report does not authorize spending, and the saved
latest observation is not permission for a current interactive run.

### Approve perps funding and withdrawal

Agent funding and withdrawals use approval cards in a conversation, not another wallet
transfer endpoint. The model proposes `perps_fund` or `perps_withdraw` with an exact USDC
`amountRaw` (six decimals) and an explicit `maxValueLossBps` integer from 0 to 300. For example,
`{"amountRaw":"2000000","maxValueLossBps":100}` means 2 USDC with a 1% loss bound. A funding spends
that amount from one USDC or USDT holding of the agent wallet that covers it alone (USDC on NEAR,
Base, Arbitrum, Ethereum or Solana, or USDT on NEAR), any USDC before USDT, swapped into
Hyperliquid's USDC in the same leg under the same bound: a user holding only USDT needs no swap
first. The card names the debit as USDC or USDT, since the holding is chosen when it runs.
Before a funding's card opens, Fin checks that one holding covers the amount and prices the route
with a dry quote: a funding no single holding covers is refused naming each holding, and one whose
loss bound is below what the route costs now is refused naming the cost and the least bound that
passes, so the model can ask the user for terms that fit; no card opens for either. After the
user approves, a step refused for a moment before anything was signed (the swap provider not
answering, a quote that went stale) is tried again under the same approval, up to three times over
about a minute, before the call reports a refusal.
The card displays the direction, exact amount, loss bound and destination ownership; neither
tool lets the model select a destination. Approve it using the card's issued authorization,
the same [signed approval flow](/sdk-recipes#decide-an-approval) used by other financial requests.

### Pay a venue funding with a coin

Where the user has it, a one-shot funding they ask for in chat (`perps_fund`, `prediction_fund`,
`solana_fund`, or a `solana_buy` paid in dollars, and a funded order's funding) may pay from a coin
of the agent wallet instead of one USDC or USDT holding: NEAR, ETH, BTC, SOL, XRP, DOGE, ZEC, SUI,
ARB or LTC, never SOL for the Solana account. The approval's `input` and its contract's terms then
carry `payWith`:

```json
{
  "amountRaw": "25000000",
  "maxValueLossBps": 200,
  "payWith": {
    "tokenId": "nep141:wrap.near",
    "decimals": 24,
    "maxInputRaw": "10500000000000000000000000"
  }
}
```

`amountRaw` stays the dollars the venue receives, and every floor is still in those dollars.
`payWith.maxInputRaw` is the most of the coin the funding may spend: the dollars at the price when
the card opened, plus 5%. The user's signature covers both, and Fin spends the dollars of exactly
that coin at its own price when it runs, never a stablecoin instead; if the coin fell more than 5%
in between, nothing moves and the call refuses (`spend_cap_reached`). The coin is the one the user
named, or, when no stablecoin holding covers the funding and exactly one coin does, that coin: draw
it on the card from `payWith`, at its own decimals. An approval without `payWith` reads exactly as
before. A buy from a token's page (Prepare a Solana trade) refuses `payWith`, and no standing
grant, withdrawal or basket of two or more positions ever carries it.

For funding, supply `context.perpsAllowed: true` when starting the current run only after
your region checks permit it, and enable the user's `perps` feature. Missing or false region
evidence refuses funding before signing. Withdrawal is an exit and is never blocked by this
flag or region permission. It pays the agent's own Intents account, requires at least 1.31
USDC and leaves a 1 USDC reserve of the account's spot USDC: Hyperliquid charges 1 USDC on
every withdrawal, because each one pays a new 1Click deposit address. A lost transfer acknowledgement remains `uncertain` while
the original quote is reconciled; do not ask the model to retry it.

With the user's `cash_outs` feature on, "close it and bring the money home" is one approval: a
`composite` contract whose first piece is the immediate reduce-only close and whose second is a
`perps_freed_withdrawal`, `{ "withdrawal": { "upToRaw", "maxValueLossBps" } }`. That withdrawal
has no amount of its own: it brings back only what the close freed, as the policy worker reads it
from Hyperliquid, never more than `upToRaw`, to the agent's own Intents account, and nothing when
the close fills nothing. It exists only inside such a composite. Polymarket's
`prediction_freed_withdrawal`, `{ "withdrawal": { "upToRaw", "maxLossBps" } }`, is the same after an
immediate sale. Show `upToRaw` as the most that can come back, never as the amount.

A new Hyperliquid account starts in `default` mode, where funding lands in its perps balance;
Fin switches it to unified mode, where all USDC sits in spot and backs margin, before its first
withdrawal or order. Funding and withdrawal have settled on mainnet through this path; funding
below about 21 USDC cannot pass the 3% loss-bound cap, because of 1Click's fixed fee.

### Approve perps orders

The agent trades the account through approval cards too: `perps_order_place` for one exact
order, `perps_order_cancel` for cancelling one resting order and `perps_margin_update` for
adding or removing margin on one isolated position. Each call needs its own approval; there are
no standing trading grants. For example, a market buy of 0.01 BTC at 5x isolated with a 65000
worst price:

```json
{
  "coin": "BTC",
  "asset": 0,
  "side": "long",
  "size": "0.01",
  "leverage": 5,
  "marginMode": "isolated",
  "entry": { "price": "65000", "timeInForce": "Ioc", "reduceOnly": false },
  "takeProfit": null,
  "stopLoss": null
}
```

The model takes the coin, index and precision from `perps_markets` and asks the user for the
leverage and the margin mode with it, `cross` (the position shares the account's margin) or
`isolated` (only the margin set aside for it is at risk); it never assumes either. `marginMode`
is present exactly when `leverage` is; an order approved before margin modes existed has none and
was cross, so read its absence as cross. `Ioc` is a market order within its worst
price, `Gtc` rests on the book and `Alo` rests only as a maker order. Take-profit and stop-loss
are reduce-only market triggers with a worst fill price; with no entry they protect the
existing position. Every order pays near.com's builder fee of 0.07% of its notional, shown on
the card, on top of Hyperliquid's own fees. The first order also applies the account's
one-time settings (unified mode and the builder fee approval), which move no money.

An order may also carry Hyperliquid's trailing stop, a reduce-only market exit on the same
size that follows the best mark price and fires once the mark reverses by the retracement:

```json
"trailingStop": { "retracement": { "percent": "2" }, "activationPrice": "70000" }
```

The retracement is a percentage (`"2"` is 2%, above 0 and below 100, at most four decimal
places) or a price distance (`{ "price": "1500" }`, under the same price rules as the other
prices). With an `activationPrice` the stop starts tracking once the mark reaches it; with
`null` it tracks from placement. It is placed right after the order, or alone on the existing
position with no entry; a reduce-only entry can't carry one. The trailing stop itself pays no
builder fee.

Opening or adding to a position needs the user's `perps` feature and `context.perpsAllowed:
true` on the current run; otherwise it refuses with scope `request` or
`not_available_in_region`. Exits stay available everywhere: reduce-only orders, take-profit,
stop-loss and trailing stop on the existing position, cancels and margin changes. An order whose
numbers the market's live rules refuse (wrong index for the coin, too many size or price digits,
leverage above the market's maximum, cross margin on a market `perps_markets` marks
`onlyIsolated`) is refused with scope `order_invalid` before anything is signed.

The operation records a `PerpsOrderOutcome`: `placed` with each placement's state (`filled`,
`resting`, `triggered_pending` for a waiting exit, `triggered` for an exit whose trigger fired
and became a market order, whose fill appears in the account's fills, `rejected`) and its order
and client order ids (a trailing stop comes last, with no client order id), `rejected` with
Hyperliquid's reason (a refused leverage stops the order before it is sent), `cancelled`, or
`not_executed`. A lost answer leaves the operation `uncertain`, keeping every placement
Hyperliquid did answer; the host reconciles the rest by client order id and never submits them
again, so do not ask the model to retry. A trailing stop has no client order id: its own answer
names its order, and without one the host settles it only when exactly one unclaimed order on
the account matches its terms, otherwise it stays uncertain. While an order that set a market's
margin mode is uncertain, an order with the other mode on that market is `rejected` with "Not
sent: an earlier isolated margin order on this market is not confirmed yet" (or `cross`) and
nothing is submitted, so the first order can only ever land under the mode it was approved with.

### Approve margin changes

`perps_margin_update` moves USDC between the account and one isolated position: `add` lowers the
position's liquidation risk, so the agent can rescue a position close to liquidation; `remove`
frees margin it no longer needs and raises that risk. Its approval contract is
`type: "perps_margin"`, one exact change signed once:

```json
{ "coin": "BTC", "asset": 0, "change": "add", "amount": "25.5" }
```

The amount is an exact USDC decimal string, greater than zero, with at most six decimal places
and below a billion. It applies only to a position `perps_positions` shows as isolated, never to
a cross position. A market `perps_markets` marks `strictIsolated` refuses every removal while
the position is open, with scope `order_invalid` before anything is signed. A margin change
opens no exposure and pays no builder fee, so neither the `perps` feature nor
`context.perpsAllowed` gates it.

Its `PerpsOrderOutcome` has no placements: `applied` when Hyperliquid applied it, `rejected`
with Hyperliquid's reason, `not_executed`, or `uncertain` when the answer was lost. Fin sends
one margin change per account at a time: one approved while another is still unanswered is
`rejected` with "Not sent: another margin change on this account is not confirmed yet", and
nothing is submitted. An uncertain change is reconciled from the account's own transactions
(Hyperliquid can include it from a day before its signing time until about two days after) and
never submitted again. It stays uncertain while another identical change already sent could own
the transaction found; one that was never sent does not count. If Hyperliquid never applied it,
it ends `rejected` with "Hyperliquid never applied it" about two days later. The final answer
arrives as a `perps.reconciled` event for `perps_margin_update`. Do not ask the model to retry
an uncertain change.

### Automate perps entries, exits and margin

To open a position, reduce one or add margin when a condition holds later (funding rate, open
interest, margin ratio, liquidation distance, unrealized PnL, daily change, a time), the user
approves a `perps_automation` contract on an automation; see
[Perps automations](/automations#perps-automations). Fixed take-profit, stop-loss and trailing
stops, and an entry at a fixed price, stay native orders, as above. Opening a position or adding
margin from an automation needs the `perps` feature and a `context.perpsAllowed: true` your
server reported within the last 7 days.

## Open a prediction-market account

Prediction-market trading is off by default. Your deployment must enable the
`prediction` feature flag for the user before opening an account, and the deployment
must hold Polymarket builder credentials; [List a user's features](/api-reference/users/list-features)
says whether the user has it. First [create the agent wallet](#create-the-agent-wallet).
The account is a Polymarket Deposit Wallet on Polygon, which holds the agent's pUSD
(Polymarket USD, backed one to one by USDC) and positions; Fin holds the key that controls it.
Opening needs no extra owner signature and moves no funds.

Call [Open a prediction-market account](/api-reference/prediction/open-account) with a UUID
`Idempotency-Key` generated once for this request. Send no request body:

```http
POST /v1/users/{userId}/prediction/account
Idempotency-Key: 6b1e2f4a-3c5d-4e7f-8a9b-0c1d2e3f4a5b
```

The SDK equivalent is `user.prediction.openAccount({ idempotencyKey })`. Opening takes two
steps on Polygon, each paid by Polymarket's relayer: wallet deployment, then its trading
approvals. Once the account is recorded, Fin continues both steps automatically, even if
your app disconnects. Do not repeat Open to advance normal setup. Opening it yourself is
optional: the agent's first funding or order starts it too, and that first attempt is refused
until the account is ready, about a minute later. While `status` is
`opening`, poll [Get a prediction-market account](/api-reference/prediction/get-account)
a few seconds apart until it is `ready`; reads never submit a relayer request:

```http
GET /v1/users/{userId}/prediction/account
```

The SDK equivalent is `user.prediction.getAccount()`. Get returns 404 until the account is
opened and remains available when the flag is off. Both return `PredictionAccount`:

```json
{
  "address": "0x94bf330955a0b957662feaf878de77bf25f76cd9",
  "signer": "0x0000000000000000000000000000000000000001",
  "status": "ready",
  "createdAt": "2026-10-17T08:00:00.000Z",
  "balance": { "status": "observed", "observedAt": "2026-10-17T08:01:00.000Z", "pusd": "0" },
  "positions": {
    "status": "observed",
    "observedAt": "2026-10-17T08:01:00.000Z",
    "stale": false,
    "positions": [
      {
        "assetId": "71321045679252212594626385532706912750332728571942532289631379312455583992563",
        "marketQuestion": "Fed cuts rates in December?",
        "outcome": "Yes",
        "sizeSharesDecimal": "40",
        "averagePriceUsdDecimal": "0.25",
        "currentPriceUsdDecimal": "0.5",
        "currentValueUsdDecimal": "20",
        "costUsdDecimal": "10",
        "unrealizedPnlUsdDecimal": "10",
        "redeemable": false
      }
    ],
    "truncated": false
  }
}
```

`pusd` is an exact decimal string; keep it as a string. When Polygon cannot be read the account
still returns, with `balance: { status: "unavailable", reason: "provider_unavailable" }`: show it
as unavailable, never as zero.
`positions` comes from Polymarket's data API: each open position, settled winners awaiting
redemption included (`redeemable`), largest `currentValueUsdDecimal` first, up to 100, with
`truncated: true` when the wallet holds more. Its figures are Polymarket's display values as
exact decimals, not settlement evidence. `observedAt` is when Fin read them. While Polymarket
rate-limits Fin, the account answers with the last positions it read within the past hour,
marked `stale: true`, so `observedAt` can be minutes old: show them as last known with that time,
and never size a sale (a Half or All shortcut) or set a maximum from them. With none that recent,
`positions` is `unavailable`. What the account holds is its pUSD plus its positions'
current value; when `positions` is `unavailable` or `truncated`, that sum would understate it,
so show the account's value as unavailable rather than as its pUSD alone. After a lost Open response or `503 provider_unavailable`,
read the account: if it exists, observe its progress; if Get returns 404, retry Open with
the same key once the provider is available. Fin reconciles uncertain setup requests before
retrying them, with at least five minutes between attempts. Disabling the user, agent wallet
or prediction feature stops new setup effects. Re-enabling the user or feature lets setup
continue; a disabled agent wallet remains stopped.
An account that was ready under an older approval set can return `opening` during its
fixed setup upgrade. Fin keeps the same account and first ready timestamp. Wait for
`ready` before funding or placing an order; reads never send the upgrade themselves.


The agent loads `prediction_account` and `prediction_positions` with its predictions capability
pack in a run admitted with the flag on. They read only its own account, never an address supplied in
chat. Positions come from Polymarket's data API as display figures, converted exactly from its
JSON numbers; they are not settlement evidence. Order placement uses the signed flow
below. Eligible resolved winning positions are redeemed automatically into pUSD in the
same Polymarket account. A separate approved withdrawal returns pUSD to the agent wallet.

### Automatic redemption of resolved winnings

Fin checks ready Polymarket accounts in the background and redeems eligible resolved
winning positions into pUSD in the same Deposit Wallet. Your app does not submit a
redemption request, ask the agent to redeem or collect another approval. Losses whose
current value is zero are skipped. The `prediction` flag does not gate this exit;
disabled users, disabled agent wallets and accounts that are not ready are excluded.

Redemption is one atomic batch with temporary position-ledger permission: grant the
pinned adapter permission, redeem, then revoke it. It cannot send winnings to another
address. A relayer acknowledgement and the data API's position display are not proof
of completion: Fin requires submission evidence followed by an on-chain zero remaining
position balance. An unavailable balance is never treated as zero.

Read `prediction.getAccount()` for live pUSD after redemption. Redemption itself is not an
Intents credit or withdrawal; use the separate withdrawal approval below to transfer it back.

### Approve Polymarket funding

OpenAPI document **12.2.0** adds the `prediction_fund` approval contract,
`prediction_disabled` refusal reason, `route_unavailable` refusal scope and
`prediction.funding` journal event. Regenerate closed-enum client types and support this
approval card and event before enabling the feature for your users. No existing route or
variant is removed.

OpenAPI document **13.4.0** adds the `credited` attribution variant, named reasons for an
`unknown` attribution and the Deposit Wallet's live `balance` on the funding's result and every
`prediction.funding` event, as
described below. Regenerate closed-enum client types; events recorded earlier still parse.

Funding has two stages: Fin delivers native Base USDC from the agent wallet to the official
Polymarket bridge, then the bridge converts it into pUSD on Polygon for that same user's ready
Polymarket Deposit Wallet. The model cannot choose a recipient. Fin spends one USDC or USDT holding of
the agent wallet (USDC on NEAR, Base, Arbitrum, Ethereum or Solana, or USDT on NEAR) that alone covers the amount,
native Base USDC first, and never splits the amount across holdings. Native Base USDC is
transferred to the bridge as it is; any other holding is swapped through 1Click into native
Base USDC. Fin chooses the holding when it freezes the plan, after approval, so the approval
card cannot name it; the activity shows it once the plan is frozen. A funding the user approved to
pay with a coin (`payWith`, [above](#pay-a-venue-funding-with-a-coin)) swaps the debit's dollars of
that coin into native Base USDC instead.

**Final pUSD is estimated, not guaranteed.** The approved loss bound covers only delivery
of Base USDC to the bridge. The bridge can charge fees, delay or hold a transfer, and a
failed bridge report does not guarantee a refund. Explain these risks before approval.
Keep this internal until eligibility and applicable Polymarket terms have been checked.
Confirm with Polymarket whether your custody and trading model needs additional permission;
builder credentials do not override access restrictions.

A chat run admitted with `prediction` enabled can discover `prediction_fund`. The tool
takes an exact debit and an explicit maximum first-leg loss including first-leg fees;
for example, 10 USDC with at most 0.5% loss on delivery to the bridge:

```json
{ "amountRaw": "10000000", "maxFirstLegLossBps": 50 }
```

`amountRaw` is a positive integer string at six decimals, never a floating-point number.
`maxFirstLegLossBps` is an integer from 0 to 300 and has no default. It does not set a minimum
pUSD amount. One USDC or USDT holding of the agent wallet (USDC on NEAR, Base, Arbitrum, Ethereum
or Solana, or USDT on NEAR; any USDC before USDT) must cover the whole amount on its own, or the funding is refused before its
card opens, naming each holding, and the prediction account must already be `ready`. A
`prediction_order_place` buy the account cannot pay for (its pUSD less what open orders hold) is
likewise refused before its card, naming what it can spend; a funding credits a little less pUSD
than it moves, since the bridge keeps a fee.

Use the [normal signed approval flow](/sdk-recipes#decide-an-approval): render the exact stored terms, then submit the
owner's exact-request signature when they approve. The `prediction_fund` contract binds the
amount, first-leg loss bound and expiry, not the source holding, for one execution through the
bridge to the user's own Polymarket wallet. The same JSON on another tool is not authorized. A
saved prompt or automation cannot grant this consent. There is no separate funding HTTP route
or second approval flow.

The current flag, account readiness and provider route are checked again before dispatch.
`prediction_disabled` means the flag is off; `no_account` means the account is absent or not
ready; `evidence_unavailable` with scope `route_unavailable` means the supported route,
bridge minimum or required evidence could not be satisfied. These refusals are not a
request to change tokens, recipient or loss limits.

After approval, distinguish the first-leg result from the bridge's progress. Delivery of
Base USDC to the bridge does not mean the Polymarket account has received pUSD. An uncertain
transfer must not be submitted again: observe the original operation instead. A bridge report,
a matching amount or time, or a balance increase alone never attributes pUSD to this transfer.
A bridge failure alone must not be shown as refunded.

The tool's `submitted` result identifies the retained `operationId`; it is not a settlement
claim. Its `firstLeg` distinguishes `pending`, `delivered_to_bridge`, `refunded` and
`not_executed`. Render bridge observations separately from `attribution`, Fin's answer to
whether this funding's pUSD arrived:

- `credited` (`creditRaw`, `transactionHash`): the pUSD arrived. Fin reports it only when
  Polygon shows the bridge's conversion of the delivery: exactly one finalized transfer of the
  first leg's delivered amount of USDC.e out of the pinned bridge address after the first leg was
  signed, that no other funding of the user's could claim, in a transaction whose finalized
  canonical receipt credits the user's Deposit Wallet in pUSD. `transactionHash` is that Polygon
  transaction. Show it as this funding's receipt, for example "4.99 pUSD arrived in your
  Polymarket wallet". Once credited it stays credited. The funding call waits up to a minute for
  it, so its result is usually `credited` already.
- `unknown` with a `reason`: `not_at_bridge` (step 1 has not delivered), `delivery_unmeasured`
  (no delivered figure to match), `bridge_not_read` (Polygon could not be read just now, or the
  result was rebuilt without reading it), `awaiting_bridge` (Polygon shows no conversion of the
  delivered amount yet), `credit_not_verified` (the one matching conversion shows no single pUSD
  credit to the wallet) or `ambiguous` (several conversions, or several of the user's open
  fundings, could match). Events recorded before revision 13.4.0 say
  `provider_reports_no_source_link`. Show the stage and that the pUSD has not been confirmed yet;
  do not promise an amount.

The bridge's own rows (`bridge.observation.transactions`) are progress to show. Their `txHash` is
the bridge's and names no Polygon transaction; a row's `credit` was recorded only before
2026-11-15 and is never written now.

The tool's result and each `prediction.funding` event also carry `balance`, the Deposit Wallet's whole pUSD balance (`pusdRaw` at
six decimals and `readAtMs`) or `unavailable`. It is the wallet's balance, never this
funding's amount; it is absent only from older events and from a result rebuilt without a live
read. Apply each newer
[`prediction.funding` journal event](/concepts-journal) to that call's displayed result,
including events arriving after the run ends. Do not let a late original `tool.result`
overwrite a newer observation.

Read `prediction.getAccount()` for the wallet's live pUSD balance at any other time; pUSD on Polygon is not
credited to the agent's Intents holdings. Funding does not itself approve a trade.
Automatic redemption keeps winnings in that Polymarket account until a separately approved withdrawal.

### Approve Polymarket withdrawal

OpenAPI document **14.1.0** adds the `prediction_withdraw` approval contract and
`prediction.withdrawal` journal event. Update closed-enum clients, event handling and
approval rendering before offering it. Withdrawal uses the existing signed chat approval
flow; there is no new `/v1` route or separate SDK withdrawal command.

The agent proposes exactly an amount and loss limit, with no address:

```json
{ "amountRaw": "10000000", "maxLossBps": 50 }
```

This approves a debit of **10.000000 pUSD** from the user's own ready Polymarket Deposit
Wallet, with a **50-basis-point pre-transfer estimate limit**. `amountRaw` is a positive
integer string in six-decimal pUSD atomic units. `maxLossBps` is required, an integer
from 0 to 300, with no default. The exact one-shot `prediction_withdraw` contract binds
`withdrawal: { amountRaw, maxLossBps }` and `validUntil`. Another tool, changed terms or
an automation cannot use that approval.

The only destination is the same user's confidential Intents wallet. Fin creates a unique
native Polygon USDC 1Click deposit address for that wallet. Fin independently
verifies its live signed `FLEX_INPUT` quote against the pinned quote signer, exact
native Polygon USDC identity, own confidential recipient and refund account, deposit
minimum and send window. Polymarket's official conversion service pays native USDC
on Polygon (chain 137) to that address; there is no Base hop or direct offramp call.
Fin obtains the withdrawal mapping and quote itself, then signs only one exact pUSD
transfer from the own Deposit Wallet to that mapping. Neither the model nor your app
supplies a recipient.

The returned confidential balance is **USDC on Polygon**, which Polymarket funding does not
spend (it spends USDC on NEAR, Base, Arbitrum, Ethereum or Solana, or USDT on NEAR); using returned Polygon
USDC for it requires a separately approved wallet swap first. It is credited under 1Click's
Omni id `nep141:pol-0x3c499c542cef5e3811e1192ce70d8cc03d5c3359.omdep.near`. A withdrawal
before 2026-11-09 credited the legacy HOT id
`nep245:v2_1.omni.hot.tg:137_qiStmoQJDQPTebaPjgx5VBxZv6L`, which 1Click retired that day (as
it did every HOT id on BNB Chain, Polygon and Avalanche): such a balance stays in the
portfolio and can be swapped, but List supported assets no longer names a retired id and no
deposit is made in one.

If 1Click will not make the deposit address (it no longer quotes the asset into the
account), the withdrawal is refused `route_unsupported` with scope `route_unavailable`
before any signature, and nothing moves. Waiting does not change that answer; show it as a
route that is unavailable, not as an outage to retry.

**The limit is not a guaranteed minimum received.** Before transfer, Fin requires the
bridge's estimated Polygon USDC output to meet both the signed deposit minimum and
`ceil(amountRaw × (10000 − maxLossBps) / 10000)`. For the example that floor is
**9.950000 USDC**. This checks an estimate before sending pUSD; it is not enforced
on chain or on the final conversion or Intents credit. Bridge liquidity, fees and
conversion can delay, hold, fail or reduce delivery. A bridge failure is not proof
of a refund. Keep these risks visible before the user signs.

Withdrawal is an exit and remains available when `prediction` is off. It still requires
an enabled owner, partner and wallet, a ready own Polymarket account and live execution
authority. Switching the flag off neither approves a transfer nor cancels one already sent.

The `submitted` result retains an `operationId` and separate `transfer`, `bridge` and
`deposit` evidence. A confirmed outgoing pUSD transfer proves only that pUSD left for
the bridge. A bridge completion report, matching amount/time or balance change does not
prove arrival. Only the unique own-account deposit's final receipt establishes attributed
arrival or refund. The receipt uses the existing wallet-deposit ledger credit once:
do not add another balance credit from the withdrawal or treat external pUSD as Intents
inventory.

Apply each newer [`prediction.withdrawal` journal event](/concepts-journal) to the
original call and approval, even after the run ends or after reconnect. Keep it over a
late original `tool.result`. Pending, held, failed, reverted, refunded and uncertain
observations are not interchangeable with completion. An uncertain signature or relayer
submission is never replaced or resent; recovery only observes the retained operation.
A refusal proven to precede signing stays refused; recovery does not turn it into
`submitted`. A transfer hash identifies verified source evidence, not an unverified
relayer candidate. Identical observations produce no new event, and polling stops
after a finalized revert or a confirmed source transfer with its final linked deposit
receipt. Do not use event frequency as a liveness signal.
No funded withdrawal acceptance is claimed. Eligibility, applicable Polymarket terms and
any permission required for your custody/trading model still need review.

### Approve Polymarket orders

OpenAPI document **12.5.0** adds `prediction_order` consent, `prediction.order` journal
events and the order read/cancel routes below. Update closed-enum clients and approval
rendering before enabling placement.

The agent places an order through the signed approval flow below; the user can also place one
themselves from your screen ([Place a Polymarket order yourself](#place-a-polymarket-order-yourself)).
The agent proposes `prediction_order_place` for one exact BUY or SELL. It gets the
market's exact `marketId`, `marketQuestion`, outcome and `assetId` from
`prediction_market` or `prediction_preview`; missing identity is not guessed.
The policy worker checks those fields again against the venue.

The request includes a `limitPriceUsdDecimal`, explicit `maxFeeUsdDecimal` and
`maxSpendUsdDecimal`, and one quantity:

| Order | Quantity |
| --- | --- |
| GTC/GTD BUY or SELL | `{ "kind": "shares", "sizeSharesDecimal": "10" }` |
| Immediate FOK/FAK SELL | The same share quantity |
| Immediate FOK/FAK BUY | `{ "kind": "budget", "amountUsdDecimal": "5" }`, before fees |

These are quantity examples, not live orders. Prices, pUSD amounts and shares are exact
decimal strings with at most six places; invalid tick or quantity precision is refused.
For BUY the limit is the maximum price before fees; for SELL it is the minimum.
An immediate BUY at a better price can receive more shares than the limit-price minimum.
GTC remains open until filled or cancelled. GTD also needs `expiresAt` in Unix seconds,
at least three minutes ahead; Polymarket normally expires it one minute before that time.

Show the exact terms and these restrictions **before signing**:

- Fin checks the current fee schedule and total spend. Polymarket's signed order does
  not include fees, so these are admission checks, not a signed cap against later changes.
  The fee checked is the most Polymarket's taker fee (`shares × rate × p(1 − p)`) can be at any
  fill price the order allows: for a budget N, `N × rate × (1 − tick)`. A `maxFeeUsdDecimal` or
  `maxSpendUsdDecimal` below it is refused before the agent's approval opens, naming the least
  each must be.
- Order expiry is enforced by Polymarket, not included in the signed order.
- A match can still fail settlement. Cancellation can race a fill and cannot reverse it.

Approve the issued `prediction_order` authorization through the ordinary owner proof
flow. A changed term needs a new approval. Missing or mismatched grant data must not
show an approve control. No other standing grant places these orders: an automation places one
only under its own `prediction_automation` contract, and only the exact order its firing sealed
([Polymarket automations](/automations#polymarket-automations)).
The `prediction` flag and current account readiness gate placement, not later cancellation.

### Place a Polymarket order yourself

OpenAPI document **13.6.0** adds these two routes. The user can place an order themselves, with no
agent run or chat. Like a limit order it takes three calls: prepare it, have the user sign it,
place it. The order is the same `PredictionOrderInput` the agent's tool takes, with the same
quantity rules and restrictions as above.

**1. Prepare it.** Send the exact order:

```http
POST /v1/users/{userId}/prediction/orders/prepare
Content-Type: application/json

{ "marketId": "562793", "assetId": "1132…", "marketQuestion": "Will …?", "outcome": "Yes",
  "side": "BUY", "limitPriceUsdDecimal": "0.62", "quantity": { "kind": "shares",
  "sizeSharesDecimal": "10" }, "orderType": "GTC", "maxFeeUsdDecimal": "0.1",
  "maxSpendUsdDecimal": "6.3" }
```

The answer carries `order`, the exact order to show and sign; `requestKey`, the id of this order;
and `authorization`, the `message` the user signs, with `controllerId` and `expiresAt`. Nothing is
reserved or placed. A user without the `prediction` flag gets `403 prediction_disabled`, and one
whose Polymarket account has not finished opening gets `404 no_account`. A size finer than
Polymarket's hundredths (shares or a budget with more than two decimals) gets `400 invalid_input`.

**2. Have the user sign.** Show the order, then have them sign `authorization.message` with their
wallet. The signature names this order alone, under its own purpose: it cannot place another order,
or stand in for a swap, a withdrawal or a limit order.

**3. Place it** before `authorization.expiresAt`, with `requestKey` as the `Idempotency-Key`:

```http
POST /v1/users/{userId}/prediction/orders
Idempotency-Key: <requestKey from Prepare a Polymarket order>
Content-Type: application/json

{ "order": <order from Prepare a Polymarket order>,
  "authorization": { "controllerId": "…", "expiresAt": "…", "signature": { … } } }
```

The answer is the order, as Get a prediction order reads it. The custody worker checks the order
against the live market (its tick, its minimum size, whether it still takes orders, the current fee
and the signed fee and spend caps) and the account's balance before it signs anything. An order it
refuses answers `409 prediction_order_changed` and places nothing; prepare it again. For a
Polymarket order rule its `detail` names the rule beside the scope, for example
`it was refused (order_invalid: fee_exceeded)`; the rules are `fee_exceeded`, `spend_exceeded`,
`size_invalid`, `tick_invalid`, `price_invalid`, `deadline_invalid`, `market_mismatch` and
`market_closed`. The same
request sent again, after a timeout say, answers the same order or the same refusal, never a second
order. Another body under the same key answers `409 request_key_conflict`. An `uncertain` order
may already exist at Polymarket: keep reading it rather than placing a replacement.

### Read or cancel a Polymarket order

Use these ordinary user-authenticated routes, or the matching SDK methods:

| Route | SDK method |
| --- | --- |
| `GET /v1/users/{userId}/prediction/orders` | `prediction.listOrders({ cursor?, limit? })` |
| `GET /v1/users/{userId}/prediction/orders/{orderId}` | `prediction.getOrder(orderId)` |
| `POST /v1/users/{userId}/prediction/orders/{orderId}/cancel` | `prediction.cancelOrder(orderId)` |

The collection is `{ data, nextCursor }`; follow its opaque cursor for every page.
Each resource is `{ id, order, observation }`. Use its Fin `id` as the route's `orderId`;
the CLOB hash is `observation.venueOrderId`, not a route id. Unknown or foreign ids
return 404. Cancellation has no request body, new spending approval or replacement
order. Repeating it addresses the same order. Reads and cancellation work with
placement disabled.

`observation` separates matched/unmatched shares from trade settlement. Raw share
and receipt-backed `settledCollateralRaw`/`settledFeeRaw` values use six decimals;
missing receipt amounts are unknown, not zero. `live` and `partially_filled` are open,
`matched` is not yet confirmed settlement, and `uncertain` means the order may exist.
`cancelRequested` is a request, not proof that the venue cancelled. Even a cancelled
order can have pending earlier fills. A terminal `FAILED` trade is not a settled fill.

After an uncertain placement, keep reading this retained id; do not place a replacement.
Fin never automatically resubmits it. A durable cancellation request can continue only
against that same order after a restart. Apply later `prediction.order` journal events
to the original tool and approval row, including after its run ends. Keep them over a
late original `tool.result`. The agent's `prediction_orders` and stop-only
`prediction_order_cancel` tools use the same ownership and recovery path.

## Open a Solana account

Solana trading is off by default. Your deployment must enable the `solana` feature flag for the user
before the agent can buy, fund or search tokens; selling, withdrawing and reading the account never
depend on it, so turning it off strands nothing. [List a user's features](/api-reference/users/list-features)
says whether the user has it. First [create the agent wallet](#create-the-agent-wallet).
The account is a Solana address of its own, controlled by a key Fin holds and separate from the agent
wallet: the agent buys and holds Solana tokens there, funded from the wallet's USDC or USDT and paid back to
it as USDC when it sells. Opening needs no extra owner signature and moves no funds, and it is
optional: the agent's first approved buy or funding opens the account itself.

Call [Open a Solana account](/api-reference/solana/open-account) with a UUID `Idempotency-Key`
generated once for this request. Send no request body:

```http
POST /v1/users/{userId}/solana/account
Idempotency-Key: 9d2c5b7e-1f3a-4c6d-8e0b-2a4c6e8f0a1b
```

The SDK equivalent is `user.solana.openAccount({ idempotencyKey })`. If the response is lost, repeat
with the same key. An already-opened account keeps its address and creation time. Read it later with
[Get a Solana account](/api-reference/solana/get-account):

```http
GET /v1/users/{userId}/solana/account
```

The SDK equivalent is `user.solana.getAccount()`. Get returns 404 `no_account` until the account is
opened and remains available when the flag is off. Both return `SolanaAccount`: its address, when it
was opened and a live read of its SOL and recognized token balances.

```json
{
  "address": "BAMgx3XPWrXkNUuQiVWUZU6eB2HQZdwz9HNnT4tpo8LG",
  "createdAt": "2026-10-23T12:00:00.000Z",
  "holdings": {
    "status": "observed",
    "observedAt": "2026-10-23T12:01:00.000Z",
    "sol": {
      "lamports": "3000000000",
      "reserveLamports": "2660240",
      "spendableLamports": "2997339760",
      "priceUsd": "103.36",
      "valueUsd": "310.08"
    },
    "tokens": [
      {
        "assetId": "asset_0a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f9",
        "mint": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",
        "symbol": "Bonk",
        "decimals": 5,
        "tokenProgram": "spl_token",
        "amountRaw": "10000000000",
        "priceUsd": "0.00002",
        "valueUsd": "2",
        "averageCostUsd": "0.0000185",
        "unrealizedPnlUsd": "0.15",
        "costBasisStatus": "complete"
      }
    ],
    "valueUsd": "312.08",
    "unpricedCount": 0
  }
}
```

Every amount is exact: `lamports` (SOL, nine decimals) and each token's `amountRaw` are integer
strings in the asset's smallest unit, scaled by `decimals`, and the USD figures are decimal strings.
Keep them as strings or use exact decimal arithmetic. The reserve is the SOL the account always
keeps for rent and network fees, so it can still sell and withdraw; `spendableLamports` is what is
above it. `tokens` includes canonical wrapped SOL, tokens the venue verifies without a suspicious
flag whose decimals and token program match the mint on chain, and tokens this account has a
confirmed landed buy of. A buy paid in SOL still establishes recognition, even when it cannot
establish a USD cost basis. Recognition uses exact mint identities; a name, ticker, icon or price
alone never qualifies a token, and an approval or unfinished trade is not a confirmed buy.
Unrecognized receipts are omitted from `tokens`, `valueUsd` and `unpricedCount`. This omission does
not remove their on-chain balances. A recognized token without a price remains listed and counts
in `unpricedCount`; `valueUsd` leaves its value out rather than treating it as zero.
`averageCostUsd` is what the agent's own settled buys paid per whole token, with each sale taking its share, and `unrealizedPnlUsd` is the gain or loss
against today's price; `costBasisStatus` says how far to trust them (`complete`, `partial` or `unknown`)
and must be shown beside them. If balances or the evidence needed to recognize a held mint cannot
be read, the account still returns with `holdings: { status: "unavailable", reason }`: show it as
unavailable, never as an empty account. Recognition filters current account reads; it does not
rewrite settlement records or existing accounting observations. Future observations use the
recognized inventory. The Solana account is not part of Get balances' total;
[Get portfolio](#portfolio-and-its-history) counts it, unrecognized tokens left out.

### Find tokens and read them

Solana tokens are named by their mint address, never by a ticker: many tokens share one. The token
reads (search, lanes, one token and its chart) are in [Solana tokens](/solana-tokens). The agent
reads the same shapes with `solana_token_search`, `solana_token`, `memecoins_top` and
`solana_account`; the search and the lanes need the flag in the run, while `solana_token` and
`solana_account` need none, so what the user holds stays readable.

### Approve Solana trades and transfers

The agent buys, sells and moves money to and from the account through approval cards in a
conversation, not another transfer endpoint. The model proposes one of four calls with exact terms,
the card shows them, and approving signs them with the [signed approval flow](/sdk-recipes#decide-an-approval)
used by other financial requests. Each call in a conversation needs its own approval. The same buy
or sale can also come from your own token page, with the user's signature and no conversation; see
[Trade a token from your own screen](/solana-tokens#trade-a-token-from-your-own-screen). A buy that
names a token pins its mint, its decimals and its token program, and the call is checked against the
chain before a card opens. For example, a buy of 50 USDC of BONK with an 8% loss bound:

```json
{
  "token": { "mint": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263", "decimals": 5, "tokenProgram": "spl_token" },
  "pay": { "kind": "usdc", "amountRaw": "50000000" },
  "maxValueLossBps": 800,
  "maxSolTopUpUsdcRaw": "1000000"
}
```

| Tool | Terms | Rules |
| --- | --- | --- |
| `solana_buy` | `token`, `pay` (`{ kind: "usdc", amountRaw }` in six-decimal USDC or USDT, spent from one holding of either that covers it, any USDC first, or `{ kind: "sol", lamports }`), `maxValueLossBps`, `maxSolTopUpUsdcRaw` | Needs the `solana` feature. At least 5 USDC. An exact input only: buying an exact number of tokens is not supported. `maxValueLossBps` is 1 to 1500, the all-in loss from what is paid to what is received, fees and price impact included. `maxSolTopUpUsdcRaw` is `"0"` to `"1000000"` (1 USDC): the most extra USDC the funding may add to keep SOL in the account for network fees, added only while the account holds under 0.01 SOL; the card shows a Top-up line when it may. A token with a hard risk flag, no price or an unreadable mint is refused before the card opens |
| `solana_sell` | `token`, `amount` (`{ kind: "fraction", bps }` of the holding, or `{ kind: "exact", amountRaw }`), `receive` (`"usdc"` or `"sol"`), `maxValueLossBps` | An exit, never behind the feature. Selling ends in USDC on NEAR unless `receive` is `"sol"`, which keeps the proceeds in the account |
| `solana_fund` | `amountRaw` (six-decimal USDC or USDT), `maxValueLossBps` | Needs the `solana` feature. Moves USDC or USDT from one holding of the wallet that covers it, any USDC first, into the account as SOL. The loss bound is 0 to 300 |
| `solana_withdraw` | `amount` (`{ kind: "exact", lamports }` or `{ kind: "all_spendable" }`), `receive` (`"usdc"` or `"sol"`), `maxValueLossBps` | An exit, never behind the feature. Moves SOL back to the wallet; the reserve stays. The loss bound is 0 to 300 |

None of them accepts a destination: the account and the wallet are always the user's own. A refusal
before anything is signed names its scope: `buy_too_small`, `reserve_required` (it would spend the
reserve), `loss_bound_exceeded` (no route returned at least the approved minimum) or `token_blocked`
(the token's own rules or its missing price keep it from trading). A buy needs three minutes of its
grant left when it starts, to fund the account and swap, so its approval's `contract.validUntil` is
four minutes past the approval's own `expiresAt` (the card's countdown): a buy approved at any moment
before `expiresAt` starts with that window, and approving after it is refused as any lapsed approval
is. A call whose grant still ran out before it started is refused `authority`, and its tool result's
`hint` says when it was offered and approved. A refusal closes that attempt; a
different amount or bound is a new request that needs a fresh approval. The result is a
financial outcome with a `solana` detail: `settled`, `partial` (a buy that funded the account but never
swapped, or a sale whose proceeds stayed there as SOL, with `solLeftLamports` saying how much, or a
sale or withdrawal whose transfer back 1Click failed, which names no `solLeftLamports` because the
SOL it took is with 1Click until it refunds it), `pending`, `refunded` or `not_executed`, and each
transaction's signature, state and fee. A result that is still `pending` or unconfirmed is finished
by Fin and never submitted again: a later `solana.reconciled` event carries the final answer (see
[money events](/streaming#money-events)), and [List activity](#activity) shows the same ending as a
`solana` item.

## See what the wallet can hold

```http
GET /v1/users/{userId}/wallet/supported-assets
GET /v1/users/{userId}/wallet/balances
```

Supported assets lists every asset and network you can deposit or withdraw, with the ids to use
in requests. Use those ids; don't build your own list of chains or match assets by symbol.
Balances returns what the wallet holds, with prices and USD values read live from the provider.

Its top-level `totalUsdCents` continues to mean available wallet holdings. The required
`portfolio` object is the account's value: the wallet, its open limit orders and order payouts
on their way back:

| Field | Meaning |
| --- | --- |
| `availableUsdCents` | The same available-wallet total, or null if any wallet asset is unpriced. |
| `inOrdersUsdCents` | The funds resting in open limit orders, at current prices. Null if an order's report is missing, more than 10 minutes older than the wallet read, newer than it, or unpriced. |
| `incomingUsdCents` | Order payouts on their way to the wallet: a filled order's output or a cancelled order's refund, at the amount the order provider reports, before any settlement fee. Zero when nothing is on its way. Once a payout completes it is part of `availableUsdCents` instead. |
| `totalUsdCents` | The account's value: available plus in orders plus incoming. Null while any part is unknown. |
| `pricedSubtotalUsdCents` | Only the wallet assets that have prices, even when the complete wallet total is null. Never an estimated portfolio total; null if its exact sum exceeds the supported cent-string range. |
| `asOf`, `complete`, `reasons` | The wallet observation time, whether `totalUsdCents` is known, and why not when it isn't. |
| `hasAssets` | True when the wallet holds a positive balance or an order holds or is paying back funds; false only when both are known empty; null when an order's funds are unknown. A zero dollar value alone is not an empty wallet. |

Every amount is an exact integer-cent string or null. Preserve null as unavailable. Show the total
as the headline, with available, in orders and on its way beneath it when they are not zero.

An order counts until its payouts complete; then it adds nothing, because the wallet's own balance
holds what it paid back. The total is unknown only while an order's part can't be told:

| `reasons` value | What happened |
| --- | --- |
| `order_allocation_unknown` | An order's amounts aren't reported yet, including a funded order whose deposit the order provider hasn't seen yet, or the order read was truncated. |
| `order_observation_stale` | An order holding funds wasn't read in the 10 minutes before the wallet was. |
| `order_settlement_unreconciled` | An order's payout failed, or only some of its fills have been paid out, so what is still to come has no amount. |
| `order_prices_unavailable` | An asset an order holds or pays back has no price. |
| `orders_unavailable` | The orders couldn't be read. |

An order that never started funding does not count, and neither does one that ended with nothing
deposited and no refund reported. Until the order provider reports any other funded order's
deposit, the total is unknown (`order_allocation_unknown`): the funding transfer may still be on
its way, so the wallet read may or may not hold it. The current summary inspects at most 100
orders that may still hold funds, and 1,000 retained changes per order; exceeding either bound
leaves the order value unknown instead of reporting a partial sum. Orders the order provider
reports ended and paid out, and orders never funded that it saw no deposit for, don't count toward
that bound. Computed values exceeding the 160-digit cent-string bound are null with
`valuation_out_of_range`; they are never rounded, clamped or substituted with zero.

This view covers wallet holdings and limit orders; positions in separate Earn and perps accounts
are outside its scope. External deposits enter available holdings when observed in the wallet;
pending external transfers are not added. `hasAssets === false` establishes a currently empty
wallet and order view, not that the user never held funds. Preserve access to prior history for
withdrawn accounts. Use [the portfolio's history](#portfolio-and-its-history) for historical performance.

A transfer goes over one of two kinds of `rail`:

| Where the money goes or comes from | `rail` | `network` |
| --- | --- | --- |
| A blockchain | `chain` | the network id from supported assets |
| A public NEAR Intents account | `intents` | `near-intents` |
| A confidential NEAR Intents account | `intents` | `near-intents-confidential` |

The two Intents networks are ledgers, separate from the NEAR blockchain.

## Portfolio and its history

[Get portfolio](/api-reference/portfolio/get) is what the agent owns across every account right
now: the agent wallet, the funds in its open limit orders, its Solana, Polymarket and perps
accounts, and money on its way between them. It gives the total, each account's value, and each
holding with its amount, price, value, 24-hour change and average cost. Use it for every figure you
show. Use [Get balances](#see-what-the-wallet-can-hold) for the amounts a deposit, withdrawal or
swap can use: those come from the wallet's custodian.

```http
GET /v1/users/{userId}/portfolio
GET /v1/users/{userId}/portfolio/history?range=1W
```

Values are exact millionths of a US dollar as integer strings (`totalUsdMicros`,
`valueUsdMicros`), and amounts are in the asset's smallest unit (`amountRaw`, with `decimals`).
Each holding names its asset in `asset`, as [tokens and chains](/tokens-and-chains#assets-on-portfolio-rows)
describes.

- **`provisional`**: a figure includes changes after the account last agreed with its custodian
  (`confirmedThrough`), such as a difference one read saw and the next has not confirmed yet. Show
  the value and say it is unconfirmed; the next read confirms or corrects it.
- **`excluded`**: holdings no price values. They are left out of the total and their
  `valueUsdMicros` is `null`. Say the total leaves them out; never show them as worth zero. Tokens
  Fin treats as spam are never listed at all.
- **`price.status`**: `priced` is a recent market price, `carried` the last one up to 24 hours old,
  and `last_trade` what the user's own last trade paid, for an asset no market prices.

Opening Get portfolio also asks Fin to read again any account last read more than two minutes ago.
It does not wait for those reads; call it again a little later to see them.

[Get portfolio history](/api-reference/portfolio/history) is the data for the value chart. Its last
point is always Get portfolio's total.

| `range` | Points | `step` |
| --- | --- | --- |
| `1D` (the default) | 288 | `5m` |
| `1W` | 168 | `1h` |
| `1M` | 180 | `4h` |
| `3M` | 90 | `1d` |
| `1Y` | 365 | `1d` |
| `all` | up to 400, from the first activity | `1d`, or a few days once that is more than 400 days ago |

Pass `step` (`5m`, `1h` or `1d`) for coarser points, such as `range=1M&step=1d` for 30 daily
points. A step finer than the range keeps is refused with `400`: `5m` works only on `1D`, and `1h`
on `1D`, `1W` and `1M`.

Each point's `gainUsdMicros` is the gain from the range's first point: the change in value less
money that came in plus money that went out. `summary` gives the range's change, money in, money
out, gain, and `gainBps`, the gain as a share of the first value plus the money in. A deposit is
money in, never gain.

`marks` say where the line moved for a reason other than gain: `coverage_out` where a holding lost
its price and left the total, `coverage_in` where one gained a price and joined it, and
`unexplained` where a change no deposit, withdrawal or trade explains landed, such as a transfer
sent to the wallet from outside your app. An unexplained change counts as money in or out. None of
them counts as gain.

## Read the wallet from 1Click yourself

If your app already signs its users in with 1Click and reads their balances, history and orders
from 1Click, it can read the agent wallet with that same code instead of Get balances. Fin gives
your backend a 1Click session for the agent wallet; your backend keeps it exactly as it keeps
your users' own 1Click tokens, and talks to Fin again only when it expires.

1. When the user creates the wallet, store its `intentsAccountId` next to your own user: it is
   the agent's account, and the account its tokens sign in as.
2. Get the agent a session with the user's session token:

   ```http
   POST /v1/users/{userId}/wallet/sessions
   ```

   ```json
   {
     "intentsAccountId": "8a88e3dd…6f5c",
     "accessToken": "eyJ…",
     "accessTokenExpiresAt": "2026-09-25T15:00:00.000Z",
     "refreshToken": "eyJ…",
     "refreshTokenExpiresAt": "2026-10-25T14:00:00.000Z"
   }
   ```

3. Keep both tokens on your server or in HttpOnly cookies, never where page JavaScript can read
   them, and send the access token as `Authorization: Bearer` to 1Click's account endpoints,
   such as balances and history.
4. When the access token expires, exchange the refresh token for a new one at 1Click, the same
   refresh call you make for your own users. 1Click answers with a new access token only, so
   keep the refresh token you have.
5. When `refreshTokenExpiresAt` has passed, or 1Click refuses the refresh token, get a new
   session from Fin. That needs a live session token for the user: open one again as you do
   when it expires, and only while your own login still holds.
6. When the user signs out, delete the agent's tokens along with their other credentials.

Every call creates a separate session, and Fin keeps no copy of it. A session can read the
wallet and cancel its open orders but never move funds (see the
[security model](/authentication#security-model)). Withdrawals, swaps, trades and deposits still go through this API.

## Deposit

To show what a deposit would credit while the user picks an amount,
[get a deposit quote](/api-reference/wallets/quote-deposit). It creates nothing: no deposit, no
address, and nothing is reserved.

```http
POST /v1/users/{userId}/wallet/deposits/quote
Content-Type: application/json

{ "rail": "chain", "network": "eth", "assetId": "asset_…",
  "amountRaw": "10000000", "maxValueLossBps": 100 }
```

The answer says what the agent wallet would be credited now (`expectedCreditRaw`) and the least it
will be within the loss limit (`minimumCreditRaw`), as of `quotedAt`. Send that minimum as the
deposit's `minimumCreditRaw`. Create a deposit prices the deposit again when it issues the address,
so quote again if the user waits. Each quote asks 1Click once, so don't send one on every
keystroke. `provider_unavailable` also means 1Click can't price it within the loss limit right
now.

Generate a UUID for this deposit and keep it with the terms before you send anything. For
example, to deposit ten units of a six-decimal asset and accept at most 1% loss:

```http
POST /v1/users/{userId}/wallet/deposits
Idempotency-Key: 5a0b3f7e-8c2d-4e11-9a6b-0f3c2d1e4b5a
Content-Type: application/json

{ "terms": { "rail": "chain", "network": "eth", "assetId": "asset_…",
             "amountRaw": "10000000", "refundAddress": "0x…",
             "minimumCreditRaw": "9900000", "maxValueLossBps": 100 } }
```

Deposits need no signature. The answer is the deposit. Once `instruction` is filled in, the
user sends exactly that asset and amount from their own wallet to `instruction.address`,
including `instruction.memo` if there is one, before `instruction.sendBefore`. Each address is
for this deposit only. Sending late, or the wrong asset, network or memo, can lose the deposit.
If something goes wrong, the funds are refunded to `refundAddress`.

The amount is the deposit's: if the user sends more, the agent wallet is credited the instructed
amount and the rest goes back to `refundAddress`; if they send less, all of it goes back. The
deposit's `receipt` says what happened: `depositedRaw` is what arrived, `creditedRaw` what the agent
wallet received, `refundedRaw` what went back.

While it's under way, `seenAt` is when Fin first saw the user's transfer (it's `null` until then),
and `arrivedRaw` is what 1Click reported arriving while it confirmed it. Once credited, `value` is
what the credit was worth in US dollars at the price Fin recorded with it: `usd`, `priceUsd` and
`pricedAt`. Show these; never use them to decide anything about money.

Poll [Get a deposit](/api-reference/wallets/get-deposit) to follow it:

| `state` | Meaning |
| --- | --- |
| `preparing` | The address is being set up. |
| `awaiting_deposit` | Waiting for the user's transfer. |
| `processing` | The transfer arrived and is being credited, or what arrived beyond the instructed amount is on its way back. |
| `credited` | Done: the funds are in the agent wallet. If more than the instructed amount arrived, `receipt.refundedRaw` says how much went back. |
| `refunded` | The funds went back to `refundAddress`, as when less than the instructed amount arrived. |
| `failed` | The deposit could not be set up; nothing was sent to it. |
| `expired` | The deadline passed and no transfer was seen. Fin keeps checking, so a late transfer still shows up. |
| `unknown` | Fin saw something it could not confirm yet. Keep checking; don't send again. |

### Deposit to an address

When the user doesn't know the amount yet, such as when they withdraw from an exchange, create
a deposit address instead. It takes one transfer of any amount, so send only the asset and the
network the user sends on:

```http
POST /v1/users/{userId}/wallet/deposit-addresses
Idempotency-Key: 9c1e2f60-3b7a-4d58-8e0f-2a6b4c9d1e73
Content-Type: application/json

{ "network": "base", "assetId": "asset_…" }
```

The answer is the [deposit address](/api-reference/wallets/create-deposit-address). Once
`instruction` is filled in, show the user:

- `instruction.address`, and `instruction.memo` when it isn't `null`. The address takes one
  transfer of that asset on that network. A second transfer, another asset or another network
  can be lost.
- `instruction.minimumDepositRaw`, the least the transfer must carry. Less isn't credited: it is
  refunded to the agent wallet. It is usually worth about 25 cents; on a network where 1Click
  bridges only more (a few dollars of bitcoin, say), it is that network's own minimum.
- `instruction.sendBefore`, three days away. A transfer sent later may be refunded instead of
  credited.

When 1Click won't make an address for the asset on that network, such as a network it doesn't
quote right now or one whose minimum is more than a few dollars, creating it is refused with `400`
and `reason: "quote_refused"`, and no address is issued. Asking again on the same network gets the
same answer, so offer the user another network.

There's no refund address to ask for: anything that can't be credited goes back to the agent
wallet itself. Poll [Get a deposit address](/api-reference/wallets/get-deposit-address) while
the address is on screen. Its `state` reads like a deposit's, plus `incomplete`: less than the
minimum arrived. That transfer is refunded to the agent wallet, so tell the user not to top it
up. The `receipt` says what arrived (`depositedRaw`), what was credited (`creditedRaw`) and what
went back to the wallet (`refundedRaw`). `seenAt`, `arrivedRaw` and `value` read as they do on a
deposit: when Fin first saw the transfer, what 1Click reported arriving while it confirmed it, and
what the credit was worth. To show roughly what an amount that has arrived will credit,
[get a deposit quote](/api-reference/wallets/quote-deposit) for `arrivedRaw`, and label it as an
estimate. Both a credit and a refund are money the user put in, so
[the portfolio's history](#portfolio-and-its-history) counts them as money in, never as gain. From the moment the
user is expected to send, the address is also in [activity](#activity) as a `deposit_address`.

When the user pastes the transaction hash from their exchange or wallet,
[report it](/api-reference/wallets/report-deposit-transaction) so the transfer is found sooner:

```http
POST /v1/users/{userId}/wallet/deposit-addresses/{depositAddressId}/transactions
Content-Type: application/json

{ "transactionHash": "0x…" }
```

The answer is the deposit address as it stands. Reporting is optional, since the address is
watched either way. A hash that isn't a transfer to this address is refused with
`invalid_input`.

### Deposit limits

Fin can cap how much a user's agent wallet may hold, per partner or per user. When a limit
applies, [Get balances](/api-reference/wallets/balances) carries it:

```json
"depositLimit": { "maxWalletValueCents": "20000", "availableCents": "15000" }
```

`availableCents` is how much more the user can deposit right now, in US cents: the limit less
what the wallet is worth and the deposits still under way. Show it before the user picks an
amount, and keep a deposit within it. `depositLimit` is `null` when no limit applies.

Getting a deposit address checks the limit again, valuing the deposit at the current price. A
deposit that would pass it is refused with `429` and reason `deposit_limit_exceeded`, nothing is
recorded, and repeating the same request gets the same answer: read Get balances again and
offer an amount within `availableCents`. A deposit address already issued keeps working when a
limit changes, and since the agent wallet is credited at most the instructed amount, sending
more than instructed cannot pass the limit either.

A deposit address has no amount to check. Creating one is refused with `deposit_limit_exceeded`
only when `availableCents` is already 0. Nothing caps what the user then sends to it, so a
transfer can take the wallet past its limit. Show `availableCents` beside the address as how much
fits. What arrives counts toward the limit once it is in the wallet, so the next deposit or
address is checked with it.

To deposit from a NEAR Intents account instead, use `rail: "intents"`. The instruction is then
an Intents transfer (`instruction.kind: "intents_transfer"`) for the user's Intents wallet to
sign and submit.

## Withdraw

A withdrawal takes three calls: get a quote, have the user sign it, send it.

Tokenized stocks cannot be withdrawn: quotes and withdrawals return `403 asset_not_withdrawable`; sell them first.

**1. Get a quote.** Choose what to send and where:

```http
POST /v1/users/{userId}/wallet/withdrawals/quote
Content-Type: application/json

{ "assetId": "asset_…", "amountRaw": "1000000",
  "destination": { "rail": "chain", "network": "eth", "assetId": "asset_…", "address": "0x…" },
  "maxValueLossBps": 250 }
```

The destination can be any supported address the user chooses; Fin never infers it. The quote
answers:

- `terms`: exactly what will happen, including `minimumReceivedRaw` (the least the recipient
  gets) and `maxFeeRaw` (the fee cap; `null` means the provider didn't disclose one, not that
  it is free);
- `quotedReceivedRaw` and `quoteExpiresAt`: the current price and how long it holds;
- `requestKey`: the id of this withdrawal;
- `authorization`: the `message` the user signs, with `controllerId` and `expiresAt`.

Nothing is reserved or sent yet.

**2. Have the user sign.** Show the user the terms, then have them sign
`authorization.message` with their wallet. The message contains the same terms.

**3. Send it** before `authorization.expiresAt`, with `requestKey` as the `Idempotency-Key`:

```http
POST /v1/users/{userId}/wallet/withdrawals
Idempotency-Key: <requestKey from the quote>
Content-Type: application/json

{ "terms": <terms from the quote>,
  "authorization": { "controllerId": "…", "expiresAt": "…", "signature": { … } } }
```

The answer is the withdrawal. A successful answer means Fin accepted it, not that the money
arrived. Poll [Get a withdrawal](/api-reference/wallets/get-withdrawal):

| `status` | Meaning |
| --- | --- |
| `pending` | Accepted, not started yet. |
| `processing` | Being sent. |
| `completed` | Paid out to the destination. |
| `refunded` | The transfer failed on the way and the funds came back to the agent wallet. |
| `failed` | Nothing left the wallet; `failureReason` says why. |
| `denied`, `expired` | Refused, or the signature ran out, before it started. |
| `uncertain` | Fin couldn't confirm the result yet. Keep checking; never send a replacement. |

If sending answers `503 provider_unavailable` with `retryable: false`, nothing was sent and the
signature can't be used again: get a new quote. With `retryable: true`, nothing was sent yet:
send the same request again while the signature is still valid.

A `failed` withdrawal's `failureReason` of `quote_expired` means the quote ran out before the
provider took the transfer: nothing left the wallet, so get a new quote. A `refunded` receipt may
carry `refundReason`, 1Click's own code for why (such as `NO_LIQUIDITY`); show it, but don't
branch on it, since 1Click may add codes. `value` is what the debit was worth in US dollars when
the withdrawal ran, at the price Fin checked its plan against; it's `null` before there's a plan.

### If a request times out

Don't guess, and don't retry money with a new key. Look it up by the key you used:

```http
GET /v1/users/{userId}/wallet/withdrawals?requestKey=<requestKey>
GET /v1/users/{userId}/wallet/deposits?requestKey=<your Idempotency-Key>
```

If it's there, follow it by id. If it isn't, send the same request again with the same key and
body while its signature is valid. An interrupted withdrawal can later close with a terminal
refusal when Fin confirms nothing was sent. Signature expiry alone does not prove that an
earlier request had no effect: keep following any pending or uncertain original withdrawal,
and require a confirmed no-payment outcome before starting a replacement from a new quote. A deposit
address has no list: send the same request again with the same key, and you get the same address.

## Swap

A swap trades one asset the agent wallet holds for another, from your own screen: the user picks
the assets and the amount, and no agent run or chat is involved. What it buys stays in the agent
wallet. Like a withdrawal it takes three calls: get a quote, have the user sign it, send it.

A tokenized stock can be swapped this way too, where the user may trade it. Send the user's
country with both calls, as `context: { "country": "GB" }`: your server resolves it from the
request (your edge's geolocation), and it applies to that one request, so Fin keeps it nowhere.
Without a country where tokenized stocks are offered, or for a buy when they are not enabled for
the user, the quote and the swap return `403 asset_not_swappable`. Selling a holding never needs
them enabled. A retry that finds its swap needs no country.

**1. Get a quote.** Choose what to sell, how much, what to buy, and the most the swap may lose:

```http
POST /v1/users/{userId}/wallet/swaps/quote
Content-Type: application/json

{ "sellAssetId": "asset_…", "amountRaw": "1000000", "buyAssetId": "asset_…",
  "maxValueLossBps": 250 }
```

`sellAssetId` is an `assetId` from Get balances and `buyAssetId` an `id` from List supported
assets. The quote answers:

- `terms`: exactly what will happen, including `minimumReceivedRaw`, the least the agent wallet
  receives of the bought asset: the quote's own guaranteed amount at your loss limit;
- `quotedReceivedRaw` and `quoteExpiresAt`: what it would receive at the current price, and how
  long that price holds;
- `requestKey`: the id of this swap;
- `authorization`: the `message` the user signs, with `controllerId` and `expiresAt`.

Nothing is reserved or swapped yet. A wallet that no longer holds the amount, or an asset that
cannot be quoted, answers `409 swap_changed`.

**2. Have the user sign.** Show the user the terms, then have them sign
`authorization.message` with their wallet. The message contains the same terms.

**3. Send it** before `authorization.expiresAt`, with `requestKey` as the `Idempotency-Key`:

```http
POST /v1/users/{userId}/wallet/swaps
Idempotency-Key: <requestKey from the quote>
Content-Type: application/json

{ "terms": <terms from the quote>,
  "authorization": { "controllerId": "…", "expiresAt": "…", "signature": { … } } }
```

The answer is the swap. Fin prices it again when it runs, and swaps only if the new price still
gives at least `terms.minimumReceivedRaw` within the loss limit; otherwise nothing is swapped and
the swap is `failed` with `failureReason: "quote_rejected"`: get a new quote. Poll
[Get a swap](/api-reference/wallets/get-swap) until its `status` is final:

| `status` | Meaning |
| --- | --- |
| `pending` | Accepted, not started yet. |
| `processing` | Running, or waiting for the provider to confirm it. |
| `completed` | The bought asset is in the agent wallet; `receipts` says how much arrived. |
| `refunded` | The provider sent the sold asset back to the agent wallet. |
| `failed` | Nothing was swapped; `failureReason` says why, in the same words as a withdrawal's. |
| `denied`, `expired` | Refused, or the signature ran out, before it started. |
| `uncertain` | Fin couldn't confirm the result yet. Keep checking; never send a replacement. |

If a request times out, look it up by its key before anything else, as for a withdrawal:

```http
GET /v1/users/{userId}/wallet/swaps?requestKey=<requestKey>
```

List swaps holds only the swaps the user made this way; the agent's own trades are below.
Any retry keeps the same key and body. An interrupted preparation may later close with a
terminal refusal when Fin confirms nothing was swapped. An expired signature alone never
resolves a pending or uncertain swap; follow its original id before considering a replacement.

Each receipt carries the swap's evidence for display: `intentHashes`, the NEAR Intents ids of the
intents that settled it, to quote to support (no public explorer shows them: the agent wallet swaps
on the confidential Intents ledger), and on a refund `refundReason`, 1Click's own code for why.
The swap's `value` is what it sold was worth in US dollars when it ran. `failureReason:
"quote_expired"` means the quote ran out before the provider took the swap; get a new quote.

## Earn vaults

The agent wallet can deposit into the same curated yield vaults near.com's Earn page offers.
[List earn vaults](/api-reference/wallets/list-earn-vaults) names each one, the yearly rate its
provider states now and the user's position in it:

```http
GET /v1/users/{userId}/wallet/earn-vaults
```

Each entry carries the vault share token's `assetId`, its `symbol`, `name` and `provider`, its
total value locked (`tvlUsd`), and `rate`: `percent` as decimal text (`"5.4017"` is 5.4017%),
`type` (`APY` or `APR`), `source` (`yield_xyz` for the Gauntlet vaults, `taler` for TLO) and
`observedAt`. Fin reads each provider at most every five minutes. The rate is the provider's
variable figure, not a promise: show it as the provider's current rate and name the source.
`rate` is `null` when the provider could not be read just now; show no figure then, never an
older one. `payment` names the asset a deposit pays with and a withdrawal returns: its `assetId`,
`symbol` and `decimals`.

A deposit is a swap from the vault's payment asset into its `assetId`, and a withdrawal is the
swap back, with the calls above. Buying shares needs Earn enabled for the user; otherwise the
quote answers `403 asset_not_swappable`. Selling shares never needs it.

`position` is the user's own position in the vault, `null` while their records show no shares of
it. It covers the time since their share balance was last zero:

| Field | What it is |
| --- | --- |
| `sharesRaw` | The shares held now, in the share token's smallest unit, those set aside for a resting order included. |
| `firstDepositAt` | When the share balance last rose from zero. |
| `depositedRaw` | What buying the shares paid, fees included, in the smallest unit of `payment`. |
| `withdrawnRaw` | What selling shares returned, in the smallest unit of `payment`. |
| `costBasisStatus` | `complete` when trades in the payment asset explain every share held, `partial` when shares also moved another way. |

What a position has earned is what its shares are worth in the payment asset now, plus
`withdrawnRaw`, less `depositedRaw`; Fin states the facts and no price, so the worth uses the share
and payment prices you show. The figure holds only while `costBasisStatus` is `complete`. Shares
transferred in or out, or traded for another asset, make it `partial`: the amounts then do not say
what the shares cost, so show no earned figure. A swap a moment old may not be in `position` yet,
so compare `sharesRaw` with the wallet's balance of the share token before showing one.

## Trades

Trades are made by the agent during a run, and each one needs the user's approval (see
[the quickstart](/quickstart#when-you-turn-tools-on)) or an automation's pre-approved limits.
A trade can also pay out: to the user's main wallet or to an exact address they approved. Its
`request.actions` name the destination; `/wallet/withdrawals` lists only withdrawals the user
started themselves. List a run's trades, then read one:

```http
GET /v1/users/{userId}/wallet/trades?runId=<runId>
GET /v1/users/{userId}/wallet/trades/{tradeId}
```

A trade shows what the agent asked for, who approved it and its `status`, with the plan it ran
and each step's receipt as evidence. A run that finished, or an approval that was granted,
doesn't prove a trade settled: read its `status`. Each planned leg's `actionIndex` names the
action in `request.actions` it carries out. A leg that paid an address has `transferPayout`, as a
withdrawal's receipt does: where the payout landed and its transaction ids, for a link to that
chain's explorer. A swap's leg has no public transaction to link: the agent wallet swaps on the
confidential Intents ledger.

| `status` | Meaning |
| --- | --- |
| `pending` | Not started yet, usually waiting for the user's approval. |
| `processing` | Running, or a swap it sent is waiting for the provider to confirm it. |
| `completed` | Every swap settled, or there was nothing to swap (`outcome.status` is `no_trade`). |
| `partial` | Some swaps settled and a later one did not. The settled swaps stand; when the later swap never started, `outcome.stopped` says which one and why; independent execution can name each unstarted action in `outcome.blocked`. |
| `refunded` | The provider sent the funds back to the agent wallet. |
| `failed` | Nothing was swapped; `failureReason` says why, in the same words as a withdrawal's. |
| `denied`, `expired` | The user denied it, or its approval ran out, before it started. |
| `uncertain` | Fin couldn't confirm the result yet. Keep checking; never ask the agent for a replacement. |

Only a trade can be `partial`: a withdrawal is one transfer.

An approved `execution.mode` of `ordered` runs complete actions in order.
`parallel_independent` allows up to four complete independent payouts at once after the full
request is checked and its funding reserved; each payout is claimed once. `dependency_graph`
adds canonical predecessor rows for mixed branches, each released only after its required
actions settle. These are dependencies between initially funded actions, without output-funded
amount bindings or conditions over previous action results. A chat request's limits, the
maximum preparation attempts and the dispatch window appear on the approval before signing. An
automation's card shows its execution mode only when it is not `ordered`, and never its preparation
attempts or dispatch window; they stay in the signed contract under Exact terms. A chat
request's `dispatchWindowSeconds` is exactly 1200, counted from when its approval opened: the
approval's fifteen minutes and five more to start, so the trade starts whenever the user approves
it while the card is open. Any other value is refused before an approval opens; only an
automation's contract may sign another window, up to 86,400 seconds. A trade approved while an
earlier one still holds the agent wallet reads `processing` and waits for that one to settle, then
runs; if its window ends first it ends `failed` with nothing sent.

Let the user review safe unfinished branches after a trade closes and every submitted action has a
conclusive result. Call `POST /v1/users/{userId}/wallet/trades/{tradeId}/remaining-proposal`
with `{}` (SDK: `user.wallets.prepareRemainingTrade(tradeId)`) to keep the original loss limits,
or send `{ "originalIndices": [1], "maxValueLossBps": "650" }` when the user explicitly selects
that action and a 6.5% all-in loss limit. The SDK keeps call options second and takes this body
third: `user.wallets.prepareRemainingTrade(tradeId, { idempotencyKey }, body)`. Generate a new UUID
for each fresh review intent and reuse it with the same body after a lost response. The available limit is 0–1000
basis points, and a recovery override cannot be lower than the original limit. Fin never selects
a higher limit automatically. The default for ordinary new proposals remains 250 basis points.

The server excludes settled and unresolved original or recovery claims. A conclusively
not-executed or finally refunded latest attempt can receive a new approved attempt bound to
its immutable terminal proof. Its old claim and consumed allowance remain unchanged, and current
funding is checked again. Exact-input actions retain the original raw debit and
token identities; exact-output swaps retain the output target and may require a different
input amount at current prices. Swap and owner-withdrawal reviews derive new price limits at
current prices. A transfer payout keeps its frozen minimum unless a higher loss limit is
explicitly chosen; any independently requested minimum receive amount stays enforced even then.
Ambiguous mappings and exact-output payouts cannot be reviewed this way.

Ordered and graph reviews include unfinished prerequisites and descendants of a selected failed action. A
preceding action must have settled conclusively before it can be omitted. A refunded,
not-executed or uncertain claimed prerequisite cannot be bypassed by selecting a descendant.
Independent actions do not add preceding siblings to the selection. Always show the complete
returned request, including any included prerequisites, for the fresh signature.

The response contains `request`, `originalIndices` (zero-based original planned positions),
`proposalId`, `fingerprint`, `expiresAt`, and `run`. Follow that run in the original conversation
and show its fresh approval normally. Repeating an `Idempotency-Key` and body returns the original
proposal and run, including after settlement; another body under that key gives
`409 request_key_conflict`. A new key can request another review after the previous group closes,
including when that group settled only some actions. Different terms conflict while
a review is active or uncertain. An expired unused review or a closed unclaimed review can receive
a new immutable generation; once a selected group and its run close conclusively, another
eligible unfinished group can receive a new review, including a proven failed prior attempt. Concurrent renewal clicks return the same
generation. An earlier retired review can no longer execute. The click itself does not approve
it. Without a key, matching active or claimed selections retain the older replay behavior.
Never reconstruct executable actions in your client or send a new
model prompt to repeat the entire original trade. A `409 trade_not_recoverable` means the original
state, a required predecessor or the available subset no longer permits this review. Reviews
always target the original root trade. A recovery child cannot become another recovery source;
use the original trade and original positions supplied with the prior review. A root with
historical nested recovery metadata refuses further review until that history is reconciled.

After later receipts resolve an originally uncertain result, read
`GET /v1/users/{userId}/wallet/trades/{tradeId}/remaining-actions` (SDK:
`user.wallets.getRemainingTradeActions(tradeId)`) for current verified candidates. This read
neither creates a proposal nor authorizes execution. An empty list means no action currently
has the required proof.

Each leg carries `intentHashes`, the NEAR Intents ids of the intents that settled it, for support:
they are on the confidential Intents ledger, which no public explorer shows. A refunded leg may
carry `refundReason`, 1Click's own code for why; it is `null` when 1Click gave no code. Show both,
and decide nothing on them.

## Limit orders

A limit order sells an exact amount of one asset for another at no less than a limit price. It
rests with the provider until it fills, expires or is cancelled, and can stay open long after it
was placed. What it buys comes back to the agent wallet.

An Agent API wallet places and funds the order natively, with no separate deposit transfer.
Its maximum `expiresInHours` is **168** (seven days), not 720. Chat uses that maximum when the
user gives no duration; Fin-held wallets keep their 720-hour maximum and default. New wallets
allow limit orders. For an older wallet, call Start wallet setup with `{}`; it returns the
owner's `policy_update` step when needed. Sign and continue that existing setup flow once before
placing orders. A step with `policy.limitOrder: true` means: "Your agent can place limit orders at
the market price or better. Proceeds stay in your account." The fin app provides **Allow limit
orders** on Orders and beside the corresponding chat refusal to start this flow.
Until setup completes, or for a longer lifetime, preparation and chat approval are refused with
`403 agent_api_orders_unavailable`. An order never changes its signed lifetime to fit. The agent's
policy permits no price worse than the market when it places the order; a better limit price is unrestricted.

### Place an order from your own screen

The user can place an order themselves, with no agent run or chat. Like a swap it takes three
calls: prepare it, have the user sign it, place it.

**1. Prepare it.** Choose what to sell, how much, what to buy, the least it sells at and how long
it rests:

```http
POST /v1/users/{userId}/wallet/orders/prepare
Content-Type: application/json

{ "sellAssetId": "asset_…", "amountRaw": "100000000", "buyAssetId": "asset_…",
  "limitPrice": "0.357142857143", "expiresInHours": 720 }
```

`limitPrice` is how much of the bought asset each one sold must fetch, as a plain decimal, and
`expiresInHours` runs from 1 to 720. The answer carries:

- `terms`: the order, plus `minimumReceivedRaw`, the least the whole order receives at its limit
  price, rounded up, in the bought asset's smallest unit. This is the floor the user signs: an
  order that would receive less is never placed;
- `requestKey`: the id of this order;
- `authorization`: the `message` the user signs, with `controllerId` and `expiresAt`.

Nothing is reserved or placed yet. A wallet that no longer holds the amount, or an asset the
catalog does not list, answers `409 order_changed`. Placing orders can be turned off for a user,
which answers `403 limit_orders_disabled`; reading and cancelling their orders always work.

A tokenized stock can be traded this way where the user may trade it: send
`context: { "country": "GB" }` with both calls, as for a swap. Without a country where tokenized
stocks are offered, or for a buy when they are not enabled for the user, both calls return
`403 asset_not_tradable`. A retry that finds its order needs no country.

**2. Have the user sign.** Show the user the terms, with `minimumReceivedRaw` as the least they
receive, then have them sign `authorization.message` with their wallet.

**3. Place it** before `authorization.expiresAt`, with `requestKey` as the `Idempotency-Key`:

```http
POST /v1/users/{userId}/wallet/orders
Idempotency-Key: <requestKey from Prepare an order>
Content-Type: application/json

{ "terms": <terms from Prepare an order>,
  "authorization": { "controllerId": "…", "expiresAt": "…", "signature": { … } } }
```

The answer is the order. Fin creates it with the provider and funds it from the agent wallet
while the signature lasts: a step that has not started by `authorization.expiresAt` never starts,
and an order created but not yet funded is cancelled. A funding transfer already sent is followed
to its outcome like any other order. Once the order rests, its `state` is `funded`; when nothing
was placed, it is `abandoned` with a `failureReason`, and the user prepares and places a new one.
Terms the wallet no longer fits when you place them answer `409 order_changed` and place nothing.

If the request times out, send it again unchanged, or look the order up by its key:

```http
GET /v1/users/{userId}/wallet/orders?requestKey=<requestKey>
```

Any retry keeps the original key and body. If preparation was interrupted, Fin may later mark
the original order `abandoned` once it confirms nothing was placed. Signature expiry alone
does not prove that an `unconfirmed` order is absent; keep observing the same order.

### Orders the agent places

The agent places an order during a run, and each one needs its own signed approval. That
approval's `contract` has `type: "limit_order"` and holds the exact order in `order`, where a
trade's approval has `type: "near_intents_transfer"`, so check `type` before showing the terms.

### Follow and cancel an order

```http
GET /v1/users/{userId}/wallet/orders
GET /v1/users/{userId}/wallet/orders/{orderId}
POST /v1/users/{userId}/wallet/orders/{orderId}/cancel
```

`state` follows funding (`prepared`, `creating`, `created`, `signing`, `funded`, `abandoned`),
and `observation` holds the provider's latest view of fills and payout. `unconfirmed` means the
provider's answer was lost: an order may exist, so never place a replacement. `failureReason` says
why an `abandoned` order funded nothing; `expired` means the user's signature ran out before the
order started. `conversationId` and `approvalId` name the chat the agent placed the order in and
the card the user approved there, to link an order back to where it was asked for; both are `null`
for an order the user placed themselves and for a grid's order. `grid` is `{ gridId, cell }` for an
order a [grid](#grid-trading) placed, and `null` for an order placed on its own.

`position` is the provider-reported allocation of this order, or `null` before a usable report.
`restingInputRaw` is the input still open; canceled, expired and filled orders have zero resting
input. `filledInputRaw` and `filledOutputRaw` are cumulative successful fills, not wallet cash.
`refund.principalRaw` is the unallocated main-order input **before deductions**, not the net
amount returned. Missing or contradictory evidence leaves the affected amount `null`.

`fills` lists each fill 1Click reported, oldest first: what it sold (`inputRaw`) and bought
(`outputRaw`), when 1Click says it happened (`filledAt`) and when Fin first saw it in a report
(`reportedAt`). It's `null` whenever `position.filledInputRaw` is. `depositReportedAt` is when Fin
first saw 1Click report the order's funds arrived, and `paidOutAt` when it first saw the order end
with every payout complete. Fills and funds Fin saw before it kept these times read `null`.
`value` is what the order sells was worth in US dollars when it was placed, at the market price Fin
kept then; it's `null` when Fin kept none from just before the placement.

A canceled order funded with 2,413 raw units and no fills therefore reports zero resting input
and a refund principal of 2,413. Even if `refund.providerStatus` is `COMPLETED` and names a
`txHash`, `reconciliation` remains `unreconciled`: net wallet receipts and actual fees are not
available from that report. `withdrawals` similarly retains payout references without inventing
cash amounts. Never add refund principal or cumulative fill output to wallet holdings, or deduct
estimated fees as actual. Use the current wallet balance response for observed cash holdings;
label affected historical values incomplete and omit unknown gains.

To cancel from your own screen, show the button while `observation.cancelable` is true and call
[Cancel a limit order](/api-reference/wallets/cancel-order). The user's session is enough: no
approval or signature, because cancelling moves nothing out of the wallet. What filled stays
filled, and 1Click refunds unfilled principal, subject to deductions. It answers the order with
`cancelRequestedAt` set, which is not yet proof of a refund: read the order until
the fill status is terminal. Cancellation can race a final fill and end `FILLED`. `isPayoutStatusFinal` includes failed payouts;
`payoutStatus: "COMPLETED"` reports provider success but still does not establish an exact net
refund amount. Asking again
is safe. The recorded stop request continues after temporary credential/provider outages or
service restarts. After a timeout or `503 provider_unavailable`, read the original order to
check `cancelRequestedAt` and its current observation; neither an error nor the request timestamp
proves cancellation failed or a refund completed. An order that already filled or expired
answers `409 order_not_cancelable`.

## Grid trading

A grid buys low and sells high across a price range the user chose, on its own, with no agent run
per trade. Its `levels` are 2 to 20 strictly ascending prices of a `base` asset in a `quote` asset.
Each pair of adjacent levels is a **cell**, and a cell has at most one limit order resting at a
time:

- a **buy** of `quantityPerCell` base at its low level, or
- a **sell** of the same `quantityPerCell` base at its high level.

When a cell's buy fills and its payout reaches the wallet, Fin places the cell's sell one level up;
when the sell fills, it places the buy at the low level again. Each buy then sell is one
**cycle**, which earns `quantityPerCell × (high − low)` in the quote asset before fees. The
quantity is fixed: profits never compound. Fin re-arms cells itself, with no model and no run,
under the one approval the user signed for the whole grid.

### How a grid is created

Only in chat, and only where your deployment enabled the `grid_trading` feature for the user; it is
off by default. The agent asks the user for the range, the number of levels and the quantity, then
proposes the grid as an approval whose `contract` has `type: "grid"`, with the exact terms in
`grid` and the time the grid ends in `validUntil`. The user approves it with their signature like
any money approval (see [the quickstart](/quickstart#when-you-turn-tools-on)), and approving it
creates the grid. The grid's `approvalId` and `conversationId` name that card and its chat. No
route creates a grid; to change one, cancel it and approve a new one.

A grid runs for 1 to 720 hours (30 days) after the approval's own expiry; at `validUntil` its
orders are cancelled and it ends `expired`. A grid starts by buying, with the quote the wallet
already holds; it never swaps. Each cell's first side is fixed in the terms as `cells[i].start`,
from the price when the agent proposed it: cells below the price, and the one straddling it, start
on `buy`; cells above it are `idle` and never place. At least one cell buys.

Agent API wallets use native limit orders for every cell, including reads and cancellation.
Their applied policy must allow limit orders before approval. Each cell lasts at most 168 hours,
but the grid may still last 720 hours; Fin-held cells retain their 720-hour maximum. A native
cell expiring unfilled at its own deadline before `validUntil` re-arms on the same side without
counting toward the three-miss stall. Fill evidence is the Agent API's relay of 1Click.

A cell's buy rests with 1Click as a sale of the quote: it sells the quote that `quantityPerCell`
costs at the low level, rounded up, at a limit price rounded so that it always receives at least
`quantityPerCell` and never pays more than the low level per unit of base. That quote stays locked
in the order while it rests.

### Read a grid

```http
GET /v1/users/{userId}/wallet/grids
GET /v1/users/{userId}/wallet/grids/{gridId}
```

[List grids](/api-reference/wallets/list-grids) answers the user's grids, newest first, a page at
a time; [Get a grid](/api-reference/wallets/get-grid) answers one:

| Field | Meaning |
| --- | --- |
| `state` | Where the grid stands; see below. |
| `stopReason` | Why it is stopping or ended: `cancelled`, `expired` or `grant_revoked`. `null` while it runs or is paused. |
| `terms` | The exact terms the user approved. They never change. |
| `validUntil`, `endedAt` | When the grid ends, and when it did. |
| `cells` | Each cell, lowest first: its `low` and `high` levels, the `side` its next or current order is on, its `state`, the `order` resting or being placed now (`id`, `side`, `state`, `fillStatus`) or `null`, its `cycles` and `realizedQuoteRaw`. |
| `cycles`, `realizedProfit` | Completed cycles across every cell, and what they earned in the quote asset, as `raw` and as an exact `decimal`. |
| `heldBaseRaw` | The base the grid's filled buys hold for their sells. It stays in the wallet when the grid ends. |

| `state` | Meaning |
| --- | --- |
| `active` | Cells place orders and re-arm as they fill. |
| `paused` | No order rests and none is placed. |
| `stopping` | It was cancelled; its resting orders are being cancelled. |
| `stopped`, `expired`, `failed` | Final. The grid stays readable and takes no command. |

A cell's `state` is `pending` while it waits to place, `placing` while its order is created and
funded, `resting` once the order rests with 1Click, and `idle` when it places nothing. A
partially filled order keeps resting: only a fill of the whole order, paid out to the wallet, turns
the cell to its other side. An order that ends with nothing filled, cancelled or expired, is placed
again on the same side; after three such endings in a row the cell is `stalled` and places no more.
An order that ends partly filled, or in a way Fin cannot read, stalls its cell at once. The rest of
the grid keeps running either way.

Each cell's order is an ordinary limit order: [List limit orders](/api-reference/wallets/list-orders)
and [Get a limit order](/api-reference/wallets/get-order) answer it with `grid: { gridId, cell }`,
so an orders screen can mark it as managed by its grid. Cancelling one of them with Cancel a limit
order doesn't stop the grid: while it is active, the cell places the same side again. Pause or
cancel the grid instead.

### Pause, resume and cancel a grid

```http
POST /v1/users/{userId}/wallet/grids/{gridId}/pause
POST /v1/users/{userId}/wallet/grids/{gridId}/resume
POST /v1/users/{userId}/wallet/grids/{gridId}/cancel
```

The user's session is enough for each, with no approval or signature, and each answers the grid.
In chat the agent can do the same, each with an approval card.

- **Pause** an `active` grid: its resting orders are cancelled and nothing is placed until it is
  resumed. What filled stays filled, and what the grid bought stays in the wallet.
- **Resume** a `paused` grid: every cell places again on the side it was on, under the approval the
  user already signed. It needs at least an hour left before `validUntil`.
- **Cancel** a grid that is `active` or `paused`: its approval is revoked at once, so nothing more
  is placed. The grid answers `stopping` while its resting orders are cancelled, then ends
  `stopped` with `cancelled`. Nothing is sold: what the grid bought stays in the agent wallet.
  Cancelling a grid the user already cancelled answers it again, so a repeat is safe. Pausing and
  cancelling are never turned off.

| Status and `reason` | When |
| --- | --- |
| `409 grid_not_active` | Pausing a grid that is not `active`. |
| `409 grid_not_paused` | Resuming a grid that is not `paused`, or with less than an hour left. |
| `410 grid_ended` | The grid expired or failed, or, for pausing and resuming, was cancelled. It stays readable; a new grid needs the user's approval in chat. |
| `403 grid_trading_disabled` | Resuming a grid while grid trading is off for the user. Pausing and cancelling still work. |

## Activity

[List activity](/api-reference/activity/list) is the data for an activity screen: the agent's
trades, from chat or from an automation's run, the swaps the user made with Swap tokens, the
user's deposits, transfers to deposit addresses and withdrawals, and the changes made to
automations, in one feed, newest first.

```http
GET /v1/users/{userId}/activity?type=trade&type=swap&type=deposit&type=deposit_address&type=withdrawal
```

Each item has a `kind` and carries one object named after it: `trade`, `swap` (what Get a swap
returns), `withdrawal` (what Get a withdrawal returns), `deposit` (what Get a deposit returns),
`deposit_address` (what Get a deposit address returns, in `depositAddress`), `solana` (a buy, sale,
funding or withdrawal through the agent's Solana account that the agent asked for),
`solana_sell_many` (a sale of several Solana coins under one approval that the agent asked for:
each coin as approved, how the sale stands, what each coin did once recorded (`sales`, each with
its own swap transactions) and what the whole sale returned, in `solanaSellMany`, whose
`transactions` are the sale's one transfer back),
`solana_trade` (a buy or a sale the user placed themselves on the token's page: what Get a Solana
trade returns, in `solanaTrade`) or `automation` (the automation's id, its name, and whether it
was `created`, `paused`, `resumed` or `deleted`). Render by `kind`. `swap` is new in document
version 8.20.0, `deposit_address` in 8.24.0, `solana` in 13.3.0, `solana_trade` in 15.4.0 and
`solana_sell_many` in 16.3.0; until a client renders them, ask for the kinds it knows with `type`. A `solana` item has
one `status` in a trade's words (`pending`, `processing`, `completed`, `partial`, `refunded`,
`failed`, `denied`, `expired` or `uncertain`), the exact `request` the user approved, what it
`paid` and `received`, `solLeftLamports` when a `partial` ending left SOL in the account, and each
transaction's signature for an explorer; `uncertain` means the result is not confirmed yet, so keep
reading rather than asking the agent for a replacement. A `deposit_address` shows what
arrived in its `receipt`: what was credited, and anything below the minimum that went back into
the agent wallet (`refundedRaw`), with `state` `incomplete` while that refund is under way.
For a completed address deposit, show `creditedRaw` when credited or `refundedRaw` when
refunded as the wallet inflow; `depositedRaw` is what was originally sent, before any fees.
Edits remain in the private change journal and appear in the chat receipt and automation
detail, not in `/v1` activity. The server excludes them before source limits and merged
pagination, so visible counts and cursors stay consistent; no API reset is required.
A `trade` carries its `request` and each leg's `actionIndex`, so a trade whose actions are all
payouts (`withdraw_to_owner`, `withdraw_transfer`) can be shown as a send to its destination,
whether a chat or an automation asked for it; each leg's `inputPriceUsd` and `outputPriceUsd`
value it at the prices its plan was checked against. To show one item in full, read it from its
own route by its `id`: Get a trade, Get a swap, Get a withdrawal, Get a deposit, Get a deposit
address or Get a Solana trade.
Repeat `type` to keep several kinds; omit it for all of them. `origin=conversation` or
`origin=automation` keeps only the trades asked for in a chat or in an automation's run, and
`automation` also keeps changes to automations; the user's own swaps, Solana trades, deposits,
deposit addresses and withdrawals are left out. Pass `nextCursor` back as `cursor` with the same
filters for older items.

A deposit or a deposit address appears from the moment the user is expected to send to it. One
that expired unpaid stays out of the feed, but List deposits or Get a deposit address still
returns it.
