# Assistants Source: https://docs.circuit.org/agent-developers/cli-references/assistants Connect a personal assistant that reads your account, builds agents through Builder, and proposes changes for you to confirm. A connected assistant (Grok, Muse, a scheduled Claude Code task) reads your account and proposes changes. It never confirms, trades or moves funds: every proposal waits for you in Circuit, and confirming uses your passkey. ## Connect ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit auth login --assistant "Muse" ``` The CLI opens the same browser handoff as [`circuit auth login`](./authentication). Approve with your passkey, name the connection, choose which wallets it may propose changes for, and whether it may build new agents, propose agent actions, or propose swaps and transfers. The permit lasts one year and is saved under the assistant's name, separate from your own sign-in and from other assistants. Commands use your own sign-in when one is saved, otherwise the only assistant sign-in on the machine; when several sign-ins share a machine, the assistant sets `CIRCUIT_ASSISTANT="Muse"` (or passes `--assistant "Muse"`) for every command. Change access or remove it under Connected apps in your profile menu, beside Settings and Passkeys; every request re-reads the connection's access, so changes apply to the existing permit at once and a removed connection's permit is refused. The permit carries only `account.read`, which reads the whole account: every wallet, agent source, Builder workspace and Ask chat. The wallet choice limits proposals, not reads. Routes that need `account.write`, such as uploading code, confirming a proposal, signing and account settings, refuse it. Free-text requests to Circuit are refused too: an assistant submits reviews and builds. ## Workflow 1. **Read the account first.** `circuit ask context` prints the snapshot Circuit reasons from: wallets (id, name, address, VM family), indexed holdings, sessions with their status, P\&L and newest logs, agents with their `startingAsset` (including `minimumAmount`), pending operations, backtests, workspaces, and supported networks with their native asset. Use only ids and assets from this output. 2. **Build through Builder.** `circuit ask --build "" --wait` builds a new agent and waits for the build to finish; it needs a connection allowed to build. Assistants never edit existing agents; the user does. Never write agent files or run `circuit new` or `circuit upload`; an assistant cannot upload. 3. **Propose changes.** Write a JSON file matching `circuit capabilities --resource ask/review` and submit it with `circuit ask --review ""` (`-` reads stdin). The request text is recorded as the reason for the proposal. ## Rules Circuit enforces | Proposal | Rule | | - | - | | Run now, stop, top up | `sessionId` must be one of the user's sessions; its state is checked when the user confirms. Ended sessions need a start instead. | | Start | `agentId`, a `walletId` the user owns, `settings` (may be `[]`), and an `allocation` in the agent's `startingAsset` (same `network` and `asset`); `allocation: null` lets the user choose. the allocation must be at least `minimumAmount`, and the wallet needs it unallocated when the user confirms, so fund it first (for example with a swap proposal). | | Swap | `amount` is an exact token quantity, `{ "valueUsd" }`, `{ "balancePercent" }` or `"max"`; dollar and percent amounts convert at live prices when the proposal is prepared. | | Transfer | `to` must be `{ "walletId" }` of the user's own wallet; outside addresses are refused. | | Lending withdraw / repay | `amount` also takes `{ "sessionHolding": }`: all of what that stopped session holds of the position, sized from its shares at the live rate (the venue's full close when it holds all of it). The session must have run on the proposal's wallet and have stopped. | | Raw `evmTx` / `solanaTx` | Refused for assistants. | | Every proposal | Each wallet involved must belong to the user and be allowed by the connection, and the proposal kind (agent actions, or swaps and transfers) must be allowed too. | A refused proposal returns the reason, for example `Assistants may only propose transfers between your own wallets`. # Authentication Source: https://docs.circuit.org/agent-developers/cli-references/authentication Sign the Circuit CLI in with your passkey, how browser and CLI permits work, how long approvals last, and how to sign out or switch accounts. ### Browser and CLI authority Browser sign-in creates a seven-day permit for account access. A passkey approval authorizes the selected wallet or Kraken account for one hour. Each transaction still requires confirmation, but later confirmations reuse that authority without another passkey or extending its expiry. The same HttpOnly cookie carries account access and the expiring signing capability; switching wallets requires fresh authorization. This authority allows spending the selected wallet or Kraken account's full balance. Signing out ends that browser's permit only; your other browsers and the CLI stay signed in. Stop does not invalidate a copied permit. Adding or removing a passkey requires separate passkey-management approval. CLI sign-in authorizes account access for seven days and 24 hours of signing with every wallet, exchange account and Paper trading account you own, including ones you add later. Once that signing authority expires, the next approval opens the same handoff again and the CLI stores the new permit. Agent starts open a separate handoff for 30 days of authority over exactly the selected wallet and explicitly attached exchange credentials; renew it, or restore invalid or expired authorization, with `circuit auth agent ` or **Renew authorization** in the agent menu. A session’s stored permit never leaves Circuit, so resuming a `--target hosted-engine` session opens the same handoff again. Renewal preserves the original wallet and exchange permissions by default; explicitly supplied broader permits remain accepted. Each handoff permit is encrypted to a one-time key held by the waiting CLI. Agent code never receives the session permit: the runtime adds it to engine requests on the agent’s behalf. `circuit auth logout` revokes the CLI permit, and renewing a session revokes the permit it replaces. ### Sign in ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit auth login ``` The CLI prints an authorization link to stderr, including with `--json`, and opens it in the browser. Sign in or create an account, then review the recorded permissions and approve with your passkey. Never approve a link someone else sent you. Only the CLI holding its separate polling secret can collect the permit; it waits up to 300 seconds and stores the permit in `~/.circuit/auth.toml` under the selected environment: ```toml theme={"theme":{"light":"nord","dark":"nord"}} [production] permit = "circuit_permit_." [staging] permit = "..." ``` `circuit auth login` reuses a stored permit the API still accepts; `--force` skips that check and signs in again, and fails while `CIRCUIT_TOKEN` is set. Requests send `Authorization: Bearer `. The API resolves the owned wallet or exchange credential covered by the permit, including private reads. For headless starts and approvals, provide an independently passkey-signed `CIRCUIT_SIGNING_PERMIT` alongside your account `CIRCUIT_TOKEN`. The supplied permit must cover the session wallet and attachments, by name or with `"wallets": "all"`. `auth.toml` sections accept only a nonempty `permit` field; malformed or unknown fields fail explicitly. ### Local signing Local `circuit run --wallet` needs no sign-in: unlocking the [local keystore](./wallets) with the identity under `~/.circuit/local/` authorizes signing. It works offline without a browser or Circuit account. `circuit run --simulated`, `circuit backtest` and `circuit data` read Circuit's market data and need `circuit auth login`. ### Inspect and sign out | Command | Behavior | | - | - | | `circuit auth whoami` | Shows `username`, active `environment`, resolved `controlPlane`, credential `source` (auth file or `CIRCUIT_TOKEN`), and the decoded permit payload (`issuedAt`, `expiresAt`, `capabilities`). `--json` serializes the same fields. Never prints the raw token. | | `circuit auth logout` | Removes only the selected environment's auth-file section; deletes the file when no sections remain. Takes no parameters. | | `circuit auth token` | Prints only the bearer wire string. In CI, set `CIRCUIT_TOKEN` to it; it takes precedence over the auth file and bypasses browser sign-in. | | `circuit auth token --json` | Prints `{ "token": "circuit_permit_..." }`. | | `circuit auth token --decode` | Prints both decoded segments: payload and proof, after validating the permit envelope, without verifying the passkey signature. Combine with `--json` for one JSON document. | # Development Source: https://docs.circuit.org/agent-developers/cli-references/development Circuit CLI commands for developing agents: scaffold with circuit new, run locally or in Paper trading, backtest on recorded markets and verify code. ### Create New Agent `circuit new --name [--path ]` scaffolds TypeScript source, configuration, description, a dependency manifest, runtime configuration, SDK types and assistant instructions. The default directory derives from the name; nonempty directories are rejected. Output contains `agentId`, `name`, `directory`, and `projectDir`; `--json` emits one document. `.circuit/` is reserved for CLI state, never agent source. `circuit check` installs dependencies, writes the lockfile and regenerates `circuit-sdk.d.ts` and `circuit-settings.d.ts`. ### Pull Agent Workspace `circuit pull [--path ]` downloads an owned builder Workspace and installs its dependencies with the CLI's built-in Bun. Sign-in is required. It refuses nonempty destinations and reports `workspaceId`, `name`, `directory`, `projectDir`, and `fileCount`. Builder's **Continue locally** runs `curl -fsSL https://api.circuit.org/dev | bash && ~/.local/bin/circuit auth login && ~/.local/bin/circuit pull `: it installs the CLI, signs you in through the normal browser/passkey flow (the command carries no credential), and pulls the Workspace into `.//`. ### Discover capabilities `circuit capabilities --resource index --json` lists version-matched resources and the SDK digest. Read `sdk` for TypeScript declarations, `config` for the canonical configuration template and its executable validator (`circuit check`), `networks` for the complete compact network list with canonical dollar and wrapped-native assets, `network/` (for example `network/ethereum:5042`) for one network’s full configuration, `data/` for data discovery, `engine/` for wire inputs/results, and `action/` for the money action's SDK method, `input` and `operationResult`, derived from the action owner; `operationResult` describes the successful operation’s nested `result`, while the full operation envelope is in the SDK types, and a contract with an unsupported runtime predicate fails generation explicitly. JSON responses are compact and retain every field; capability responses contain an ordered `resources` array of `{resource,data}` entries, without character pagination. Repeat `--resource` to request related schemas in one command, for example `circuit capabilities --json --resource action/evmTx --resource engine/moneyPrepare --resource engine/moneyAction`. Any unknown resource fails the command. JSON Schema cannot express every custom refinement; the SDK types and runtime validators remain authoritative. ### Run Agent Locally `circuit run --wallet ` runs temporary local code with a local encrypted-vault wallet and embedded engine. `--target hosted-engine` runs it with the selected hosted wallet, sessions, permit and KMS-F signing and no upload: the session uses local `circuit.toml` configuration, never changes the published agent, has no server triggers and runs only from the CLI (Top up and Run now are unavailable, and changing its allocated amount means stopping and running again with `--amount`). `--target hosted` uploads current code, starts a recurring hosted session through the shared Start operation and tails the first run; the session stays active. `circuit run --simulated` runs temporary local code in Paper trading on live markets, with no wallet, keys or funds; it reads market data with your `circuit auth login` sign-in. > [!WARNING] > > Live runs can spend funds. Embedded execution requires `circuit wallet add` and local signing authorization. Preparation copies the upload file set, installs locked dependencies without scripts, strictly compiles against runtime-provided SDK declarations with a trusted compiler, then checks the production bundle and `run` export. It ignores project compiler settings. Local execution, hosted execution and replay run the prepared ESM bundle. Hosted runs execute the bundle prepared at upload; a later SDK change does not recompile it, so code that relies on a changed SDK surface fails when it calls it. Excluded files are unavailable. Preparation finishes before session changes; the temporary copy is removed afterward. Hosted-engine runs record the prepared artifact's SHA-256 hash without uploading it. NDJSON protocol 3 distinguishes the CLI `invocationId` from the admitted `runId`; `run.started` identifies the session before completion or failure. Embedded execution keeps the project's sessions, their starting allocations and its operations in the embedded engine database in `.circuit/engine`, and reconstructs allocation from them and durable venue account history the way hosted sessions do. SDK money writes execute immediately; `data.*` returns empty rows without contacting Circuit, except that `--simulated` reads Circuit's market data as the signed-in account. A Paper trading run trades an account whose `walletAddress` is its own keyless address: swaps fill at the live executable quote, venue orders against the live book and one-minute bars, Polymarket orders against the live book with redemptions paid at resolution, and transfers, raw transactions and signing fail. Explicit external reads are separate. Hosted execution resolves the named wallet, validates funding, creates or resumes a session, and routes calls to the hosted engine. First use requests a wallet-scoped passkey permit. See [Holdings](../sdk-reference/holdings). An uploaded run tails its first run to durable completion and exits nonzero on failure. The session keeps its allocation and triggers after the CLI exits, including on failure or interruption. Use **Stop** or `circuit stop --target hosted --wallet ` to stop it. Repeating an interrupted command resumes its persisted start identity; starting again on an active wallet is rejected. #### Run and stop flags | Flag | Contract | | - | - | | `--target local\|hosted-engine\|hosted` | One execution target; defaults to local. Run takes all three; stop takes `local` or `hosted`. Flags incompatible with the target fail before project loading or account access. | | `--path ` | Agent directory; defaults to current directory. | | `--wallet ` | Required except with `--simulated`; see [wallet selection](./wallets#select-a-wallet). | | `--simulated` | Run only, local only: start or resume a Paper trading session; `--amount` sets its starting asset. | | `--keystore ` | Local vault; defaults to `~/.circuit/local/keystore`. Rejected for hosted targets. | | `--var KEY=VALUE` | Run only: repeatable environment overrides, taking precedence over `.env`. | | `--rpc =` | Run only: repeatable local RPC overrides; rejected for hosted targets. | | `--amount ` | Run only, new sessions: whole tokens to allocate, or `max` for the whole unallocated balance read at admission; at least `startingAsset.minimumAmount`. Required for a new wallet session; a Paper trading session defaults to its sized deposit. For an exchange trading agent it is the exchange allocation in its `minimumAllocation` asset. Locally, `0` requires no balance read and a `minimumAmount` of `"0"`. An amount with more decimals than the asset has is rejected, never truncated. Omit when resuming. | | `--setting KEY=VALUE` | Run only: repeatable overrides of `circuit.toml` setting defaults for this invocation. Unknown keys and invalid values fail, including nonliteral booleans, unknown selection options and addresses from the wrong wallet family. | Embedded runs default to public RPC endpoints. Override one per invocation with the repeatable `--rpc =`, or persistently with `"" = ""` lines under `[rpc]` in `~/.circuit/rpc.toml`. Network IDs are `ethereum:` for a supported EVM chain or `solana`; any other ID is rejected. With `ALCHEMY_API_KEY` or `HELIUS_API_KEY` set in the environment, EVM networks read through Alchemy and Solana through Helius instead. Embedded swaps use the same providers as hosted execution. Supply `SWAPS_UNISWAP_API_KEY`, `SWAPS_JUPITER_API_KEY`, `SWAPS_RELAY_API_KEY`, `SWAPS_NEAR_INTENTS_API_KEY` or `SWAPS_ACROSS_API_KEY` where required. Credentials serve quotes/execution and are never persisted in operation records. Transaction diagnostics include explorer links where available; `run --json` emits NDJSON with diagnostics in `output` envelopes. ### Stop Agent `circuit stop` ends the project's active local session, Real money or Paper trading, and deletes its session facts and memory; a `--wallet` must match that session. With `--target hosted` and `--wallet ` it stops that wallet's hosted session, whether `--target hosted` or `hosted-engine` started it, and lists the positions the session left open; its positions and orders stay open. Stop runs no agent code ([execution model](../concepts/execution-model#sessions-and-runs)). ### Backtest Agent `circuit backtest [--from ] [--to ] [--usd ] [--setting KEY=VALUE] [--output ] [--skip-news] --json` replays the project against recorded Hyperliquid, Lighter or Lighter Robinhood markets without a wallet or network writes; it reads recorded market data and news history with your `circuit auth login` sign-in, and refuses to start without one. An agent that starts from HyperCore USDC, Lighter USDC or Lighter Robinhood USDG replays on that venue, and every venue trigger must be on it. A news trigger wakes `run` at the minute each matching item arrived, which limits the window to the last 7 days; `--skip-news` replays without news history, so news triggers never fire. A market's history loads the first time the agent orders it, and Lighter orders pin against Lighter's current size, price and minimum rules. The agent module evaluates once per replay, so unlike hosted runs, module-level variables persist between replayed runs; keep state in `agent.memory`. Its triggers wake `run` on a deterministic replay clock; positions still open at the end of the window are marked to market. Every `agent.data` read is answered for its own instant on that clock and, once the same query repeats, in batches covering the scheduled runs. Orders are sized like Paper trading orders and filled in memory by the same venue rules: perpetual orders fill at the current bar's open, or the last traded close in a bar without trades, or, for resting orders, once a later bar trades through the limit and the account has margin for the fill, with the reported fee, slippage, shared per-bar volume and leverage assumptions; positions pay funding at each hour's opening price. The account is liquidated at a bar's close when its equity there falls below maintenance margin. Cross `leverage` changes apply to margin; other money actions, spot orders, outside requests and a missing recorded funding settlement fail loudly; a failed run is reported, its failures are grouped in the report, and the replay continues. A window of any length replays in seconds within 100 agent runs: at the finest bar that fits (1-minute bars only within the last 30 days, then 5-minute, 15-minute, hourly, 4-hour or daily bars), with runs at most once per step of whole bars, so a slow schedule keeps every run and a fast one over a long window runs once per step; triggers due inside a step run once at its start, the report's `bars` assumption names the bar and step, and a market's history starts when Circuit began recording it. The window defaults to the last seven days, or the seven days before `--to` when it is given; `--to` defaults to the latest hour the venue's recorded prices and funding cover, with 1000 USD. Without `--json` it prints the window, the result, trades, fees and funding, and any warning: failed runs with their most frequent reasons, no trades with the agent's most frequent messages, liquidations, and resting orders that count as filled whenever the price trades through them. When most runs failed it prints no result. `--json` prints the compact Builder report and `--output` writes the untruncated result. The backtest, including a news trigger's search of past news, fails two minutes after it starts. Results describe the selected historical period and do not predict future performance. ### Validate Agent Project `circuit check [--path ] [--artifact ] --json` validates without executing agent code or contacting Circuit; dependency installation can contact the registry. It checks root configuration, settings, starting inventory, required project files and a production-form build. `--artifact` writes the validated production TAR after all checks pass; keep it outside authored source, such as `.builder/verified.tar`. A present `DESCRIPTION.md` must pass the same Thesis, Strategy and Exposure rules upload enforces. The CLI installs dependencies without scripts, regenerates SDK types and runs the project compiler with a CLI-owned strict configuration over collected TypeScript source. No project `tsconfig.json` is needed or read by the check. A generated type assertion verifies a callable `run` export. TypeScript does not check keys that arrive through a spread, so the check also rejects any spread into an SDK payload (a call argument, an annotated return or variable) that adds a key the payload's `kind` does not declare, naming the file, line and keys; Circuit refuses unknown keys at runtime. Keys hidden behind `any`, a cast or `Object.assign` are refused only at runtime. Upload repeats production preparation from pinned source. Invalid projects exit nonzero; passing check establishes structural validity, not strategy correctness. ### Command Inputs and Global Flags Supply required flags and use positional arguments only where shown in the command syntax. Explicit secret-prompt flags require an interactive terminal. Commands that require authentication check it before prompting. Input is hidden; Enter submits each value. Ctrl+C exits with code 130 without saving or writing JSON. See [authentication](./authentication#sign-in) to sign in. All wallet selectors use `--wallet `; see [wallet selection](./wallets#select-a-wallet). > [!WARNING] > > Direct secret flags expose values in process arguments and can put literal secrets in shell history. Hidden prompts keep values out of both, but clipboard managers and session recording may capture them. `--json` emits one document for one-shot commands and NDJSON for `run`. `--env production|staging|local` overrides `CIRCUIT_ENV` and defaults to production. `--assistant ` overrides `CIRCUIT_ASSISTANT` and acts under that [assistant](./assistants)'s saved sign-in. `--help` shows command help; `--version` reports the CLI release as its UTC release time, `YYYY.MM.DD.HHMM`. Flags have no short aliases. Project commands accept `--path`; `new` and `pull` treat it as the output directory. `circuit check --locked --json` validates against the existing lockfile without updating it. A project still holding a retired local session format fails with its path; finish that session with the previous CLI, move the files aside, and start a new session. # Operations Source: https://docs.circuit.org/agent-developers/cli-references/operations Submit, approve, and inspect money operations and Ask Circuit agent actions. `circuit operations` approves and inspects inert reviews, with separate approvals for prerequisites, durable evidence, and full selected wallet or venue account execution subject to permits and live checks. `circuit ask "" --review proposals.json` submits your own money action proposals as reviews (`--review -` reads stdin); `circuit capabilities --resource ask/review` prints the shape. | Command | Behavior | | - | - | | `approve ` | Confirm, wait while Circuit holds the response, print the resource, and exit nonzero on error. A still-pending operation keeps settling; `get ` reads its outcome. | | `get ` | Read evidence and successors; when the prerequisite succeeded or the quote is eligible for refresh, prepare the successor once (repeats return the same review) for separate approval. Observation never signs or resubmits. | | `cancel ` | Dismiss an inert review, or cancel a pending operation before its irreversible edge: one not yet started, or one its venue can still withdraw, such as a queued Papertrade intent. A broadcast operation settles on its own. | Every operation response includes its review display and lifecycle; reading it again is not required to show a prepared review. It is identified by `operationId`; its `status` is `review`, `expired`, `dismissed`, `pending`, `unproven` (submitted, past its settlement bound, and still watched until evidence settles it), `success` or `error`; and a successor's `continuation.status` uses the same vocabulary: its operation's state once prepared, otherwise `pending` while it waits or prepares, `error` when preparation failed, and `dismissed` when the previous operation did not complete. Its `title` is one verb-first sentence, such as `Supply 100 USDC to Aave`: imperative until it settles and past tense once it succeeded, the same wording Ask, Activity and the CLI show. Titles use resolved asset symbols, while raw market IDs remain execution inputs. Inspect timeout receipts instead of automatically replacing an operation. Circuit prepares a successor once its predecessor settles, and approving the predecessor also approves the successor while the approving permit still verifies and signs for the successor's wallet; otherwise the successor waits in `review`. The CLI prints `Confirm next: circuit operations approve ` only for a successor in `review`; an approve that loses the short race with the stored approval answers 409 and the successor runs once. A lower refreshed minimum requires approval. An `order` proposal on `venue: "hyperliquid"`'s `order` takes the [Hyperliquid order shape](../sdk-reference/hyperliquid), and a `cancel` there takes the `orderId` from the order's result or open orders, Hyperliquid's numeric ID for an order placed outside Circuit, or `"all"` to cancel every resting order on the account in one action; an `account` proposal on `venue: "hyperliquid"`'s `account` takes the [Hyperliquid account change](../sdk-reference/hyperliquid), whose `scheduleCancel` takes `at`, an ISO time at least five seconds ahead when Hyperliquid cancels every resting order on the account (its dead man's switch, at most ten firings a day), or `null` to clear it. Configuration-dependent sizing requires account setup first. ## Ask Circuit `circuit ask "swap 0.1 ETH to USDC on Base"` prints its Turn ID, message, operation IDs and outcomes; a proposal that failed for missing funds or gas prints `circuit ask --recover :`, which asks Circuit to fund it. Approve IDs individually or use `--approve` to execute proposed trades and agent actions in order. The first failure or still-pending operation stops approvals and preserves remaining reviews. `--json` includes the Turn, `operations`, and `agentActions`, retaining known resources on failure. Start and Top-up require reviewed inputs. `circuit ask --build ""` goes directly to Builder; build results name Turn, status and workspace. `--agent ` edits that agent instead of creating one, and `--wait` waits until the build finishes. Each CLI invocation starts a new chat; web restores the chat and agent selection. Unsized buys/longs/shorts default to 20 USDC on Hyperliquid, 10 pUSD on Polymarket, and \$20 elsewhere. Swaps, sells, sends and modifications require sizing; explicit closes select the whole identified position. Fractions stay fractions. Margin and leverage phrasing follows the [FAQ](/support#using-circuit). Absent indexed assets are read live. Ordinary-wallet sends/swaps need source gas, including swaps into gas. An unspecified destination network prefers the funding network where the exact asset exists, without substituting a wrapped asset; destinations need not be held. Arbitrary protocols and raw transactions are supported. Unresolved loan terms require clarification, and dependent funding, approval and entry receive separate reviews. Research URLs are optional and appear in raw-transaction reviews. ## Agent actions Read `circuit ask action ` and approve with `--file approval.json` or stdin `--file -`. Control input is `{ "kind": "control" }`. Circuit sizes every start and top-up itself, exactly as the start sheet shows it. Top-up takes an `amount` of `{ "kind": "topUp", "amount": { "unit": "token", "value": "25" } }` (`unit` is `token`, `usd` or `max`; `max` allocates the whole unallocated balance read at admission). Start requires `kind: "start"`, an optional `account` of `"wallet"` or `"simulated"` (Paper trading), the `walletId`, `exchangeCredentialId` or `simulatedAccountId` its plan chose, an optional `amount` in the same shape (the plan's default when absent; for agents that trade on an exchange it is also the exchange allocation), optional `settings`, and a separately requested passkey permit. Every action produces a review. Saved decisions appear while independent reviews prepare concurrently. Identical approved inputs replay the original outcome; changed inputs conflict. Receipts retain proposal, wallet, allocated amount, settings and exchange attachments. Live inventory changes reject the exact reviewed amount. Start and Top-up admit runs; one execution per session respects earlier work. Account readiness is checked again before execution. # Uploading Source: https://docs.circuit.org/agent-developers/cli-references/uploading Upload a Circuit agent with circuit upload: required files, circuit.toml checks, flags, and how a new code version reaches every running session. ### Upload Agent `circuit upload` saves the current project as the agent's code. It requires [authentication](./authentication#sign-in), valid `circuit.toml` (including starting-asset rules), `index.ts`, `package.json`, and a current `bun.lock`. | Flag | Contract | | - | - | | `--path ` | Project directory; defaults to the current directory. | | `--var KEY=VALUE` | Repeatable environment override; takes precedence over project `.env`. | Run `bun install` after dependency changes, then [circuit check](./development#validate-agent-project). Upload collects the same fixed source set, pins the source and lockfile, installs dependencies without scripts, verifies `run`, and builds in Circuit's production environment. It stores one deterministic SHA-256 code artifact and encrypted environment variables separately, returning the agent ID, code hash, whether this was the first upload, and app link. `agentId` in `circuit.toml` is the permanent [agent identity](../getting-started/circuit-toml-reference). Renaming retains its sessions and state. A successful upload replaces the agent's code, environment, setting definitions and triggers, and every hosted session runs them from its next run. Running hosted sessions keep each unchanged trigger's state, stop removed triggers and start added ones; a trigger whose filter or cooldown changed starts fresh. Failure preserves current content. Unchanged code and environment are deduplicated. Code or environment changes replace the current runnable state; an environment-only change preserves the bundle hash. The upload endpoint accepts `files`, `paths` (a JSON array with one project path per file, in file order; file part names are ignored), and optional `envVars`. Bodies may be up to 32 MiB. Installation and build validation run in an isolated builder with no backend or developer-host file access. ### Sharing All agents are public. Anyone can view an agent and start their own session once it has uploaded code. **Share** opens link and social sharing in both the builder and agent page. Every agent with uploaded code is listed on its creator's profile; the Agents page lists it once at least three people other than its creator have run it with Real money in the last 30 days. Every upload also becomes the agent's Builder Workspace, replacing any unsaved Builder changes. Builder Workspaces and chats are owner-only, and environment variables remain encrypted and separate from source. Every agent's uploaded source is visible to signed-in users, and anyone signed in can fork it. ### Fixed source exclusions The agent directory is the complete source boundary. `circuit check`, local execution, upload and Builder saves collect the same files; Circuit applies the policy again to every upload, and the code viewer shows exactly the files the published bundle was built from. Circuit excludes only these fixed patterns: * Version control: `.git`, `.gitignore`, `.svn` * Dependencies and builds: `node_modules`, `dist`, `build`, `.next`, `.nuxt`, `.cache`, `.bun`, `.npm`, `coverage`, `.nyc_output`, `__pycache__`, `.pytest_cache`, `.ruff_cache`, `.mypy_cache`, `*.egg-info`, `*.pyc`, `*.bin`, `.venv`, `venv` * Secrets and local config: `.env`, `.env.*`, `.dev.vars`, `*.key`, `*.pem`, `.npmrc`, `.pypirc`, `bunfig.toml` * Editor, assistant and OS: `.vscode`, `.idea`, `.claude`, `.claude.json`, `AGENTS.md`, `*.swp`, `*.swo`, `*~`, `.DS_Store`, `Thumbs.db` * Unsupported lock files: `package-lock.json`, `bun.lockb`, `yarn.lock`, `pnpm-lock.yaml` * Deployment and tooling: `Dockerfile`, `.dockerignore`, `wrangler.toml`, `wrangler.jsonc`, `.wrangler`, `.circuit`, `.builder`, `docs`, `*.log`, `*.tmp` Other `*.md` and `*.sh` files are source. `DESCRIPTION.md` is also sent as agent metadata. ### Environment Variables `run` and `upload` read project `.env`, with repeatable `--var KEY=VALUE` overrides taking precedence. Local execution injects values into the agent subprocess. Upload encrypts them at rest, excludes plaintext from the source bundle and code viewer, and decrypts them for deployment. Agent code reads `process.env.KEY`. Uploaded variables are limited to 3,500 bytes as serialized JSON; re-upload to rotate them. # Wallets Source: https://docs.circuit.org/agent-developers/cli-references/wallets CLI commands for managing embedded-engine signing wallets via the encrypted keystore. The `circuit wallet` namespace manages an encrypted local keystore that holds the local keys the embedded `circuit run` uses to sign. The keystore lives at `~/.circuit/local/keystore` by default, sealed with AES-256-GCM under a key derived (HKDF-SHA256) from a local identity the CLI generates on first use - there is no keystore password, and wallet commands need no login or session permit. Override the location per command with `--keystore `, or relocate the whole config directory with `CIRCUIT_CONFIG_PATH`. The keystore is always written with `0600` permissions; `circuit wallet` refuses to read one with looser permissions. Wallet families are `evm` and `solana`. ### Select a wallet Use `--wallet ` for `run`, `stop`, `wallet delete`, and `wallet export`. Names match without case; EVM addresses match without case; Solana addresses match exactly. An exact address takes precedence over a matching name. Embedded execution and wallet management select from the local keystore. Hosted execution selects from your Circuit account and never reads that keystore. The account API’s `GET /wallets/list` returns `{ wallets, markedValueUsd, holdings, retryAfterMs }` (`markedValueUsd` sums the wallets' known marked USD values and is `null` when none is known; `retryAfterMs` is the server-chosen delay before the next read; it shortens while a balance refresh is pending), with wallets and aggregated holdings from the same read. ### List Wallets ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit wallet list ``` Prints one TSV row per wallet (`ADDRESS\tVM_FAMILY\tNAME`) so the output is pipe-friendly. Use `--json` for a structured response. If no keystore exists yet, this exits 0 with an empty list. ### Add Wallet ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit wallet add --name "Trading wallet" --generate evm ``` Use `--generate evm|solana` to create a fresh keypair from OS entropy. To import a key, use `circuit wallet add --name "Trading wallet" --private-key-prompt`. Paste the key at the hidden prompt and press Enter. For direct input, supply `--private-key ` instead of `--private-key-prompt`. The key decides the wallet: 64 hex characters, with or without `0x`, is an EVM key; base58, a 128-hex-character keypair, or a JSON byte array holding a 32-byte seed or 64-byte secret key is a Solana key; a 32-byte Solana seed is never written as bare hex, so 64 hex characters always means EVM. Generation and import flags cannot be combined. `--name` is required. Names must be nonempty, have no surrounding whitespace, and cannot start with `Polymarket - ` in any letter case. Names must be unique without case within the local keystore or hosted account. Follow the [command input and secret handling rules](./development#command-inputs-and-global-flags) when supplying private keys. ### Delete Wallet ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit wallet delete --wallet --yes ``` Permanently removes the stored wallet key bytes. Requires `--yes`. ### Export Wallet ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit wallet export --wallet --yes ``` Decrypts a local key and prints it to **stderr**: `0x`-prefixed hex for EVM, base58 for Solana. Requires `--yes`; `--json` is not supported. Use `2>` only when you intend to save the key, and protect the output file. # Execution Model Source: https://docs.circuit.org/agent-developers/concepts/execution-model How Circuit runs agents: sessions, the AgentContext each run receives, session memory, triggers and run admission, execution time limits, continuous mode, and what happens when a session stops. ### Sessions and runs A session ties one agent to one wallet and its virtual allocation. Circuit supplies a fresh [AgentContext](#agent-context) to each `run` invocation. Implement `run(agent)` for the strategy; SDK methods execute the operations. Use [Memory](#memory) to persist strings between invocations; session memory ends with the session. Only one run executes per session. Start admits its initial run. Top-up allocates the amount and admits another run atomically, even while busy. Stop ends the session, cancels queued work and releases its allocation; an executing run finishes and records its own outcome. It runs no code: holdings, positions and resting orders stay open for the user to close by asking Circuit. Account requirements inferred from the starting asset must be ready before agent code executes. Hosted execution requires runtime admission: Stop winning that admission race prevents execution, while an already-admitted run may continue. An agent has one active version. Saving code moves every session, including other users' sessions of a shared agent, to it from its next run; queued and executing runs keep their admitted revision. Setting overrides affect later admissions, and an override the current setting definitions reject no longer applies. Run status reports the `codeHash` each run admitted; null means no historical revision was recorded. ### Agent context The runtime passes `AgentContext` to `run` on each trigger; agents never instantiate it, and `run` returns no value. It exposes `sessionId`, `walletAddress`, resolved [`settings`](../getting-started/circuit-toml-reference#settings-section), `trigger`, fixed `allocation`, and the SDK resources: [`log`](../sdk-reference/logging), [`memory`](#memory), [`data`](../sdk-reference/data), [`operations`](../sdk-reference/error-handling), [`transactions` and `wallet`](../sdk-reference/transactions), [`transfers`](../sdk-reference/transfers), [`swaps`](../sdk-reference/swap), [`fomo`, `solana` and `watchedWallets`](../sdk-reference/watched-wallets), [`hyperliquid`](../sdk-reference/hyperliquid), [`lighter` and `lighterRobinhood`](../sdk-reference/lighter), [`papertrade`](../sdk-reference/papertrade), [`polymarket`](../sdk-reference/polymarket) and [`kraken`](../sdk-reference/kraken). `trigger.kind` is `schedule`, `manual`, `price`, `resolution`, `allocation` (deposit or withdraw), `position`, `fill`, `news`, `walletTrade` or `webhook`. Price-trigger values are decimal strings; venue triggers identify the Hyperliquid coin or Polymarket outcome token; news triggers carry the matched `headline`, `summary`, `source`, `url` and `emittedAt`; webhook triggers carry the `provider`, the provider's event `id`, and the `payload` exactly as the provider sent it, typed `unknown`: check its fields before using them, and pass its numbers to the decimal helpers as strings; walletTrade triggers carry the watched `wallet` (lowercased on EVM) and one `trade` it made, whose `venue` is `chain` (`network`, `transaction`, `sold` and `bought` assets with whole-token amounts, and where the bought token arrived, `boughtOn` and `recipient`), `hyperliquid`, `lighter`, `lighterRobinhood` or `derive` (one fill's `asset`, `side`, `size`, `price`, `at` and `id`, Hyperliquid adding `positionAfter`) or `papertrade` (a position's `action`, `positionId`, `asset`, `side`, `size`, `entryPrice` and `leverage`); a Papertrade change also names its `positionId`, and its `before` or `after` adds `margin` and `leverage`. Methods return data or throw [structured errors](../sdk-reference/error-handling). Every amount the SDK takes or returns is a decimal string of whole tokens; the engine rounds spends down and minimums up to each token's smallest unit. Do money math with the `circuit:sdk` helpers `decimalAdd`, `decimalSub`, `decimalMultiply`, `decimalDivide` / `decimalDivideCeil(numerator, denominator, scale)`, `decimalMin`, `decimalMax`, `decimalIsZero` and `decimalCompare`: they are exact, never emit exponents, and need no configuration. Floats, `Number()`, `parseFloat` and default-precision decimal.js round money silently, and `BigInt()` of a scaled product throws once its decimals exceed the scale: products grow decimals, so truncate with `decimalDivide(x, "1", scale)` first. Every time the SDK returns is a UTC ISO string to the millisecond, exactly as `new Date().toISOString()` writes it (`2026-11-01T00:00:00.000Z`), so times compare and sort as text. A time you pass back, such as an `asOf`, covers its whole millisecond. Cursors are opaque: pass `nextCursor` back unchanged. Methods accept named requests, such as `operations.retrieve({ operationId })`; no-input methods take no arguments. Money writes return completed operations with kind-specific `result` and typed `receipts`. See [error handling](../sdk-reference/error-handling) for durable references, failure stages and cross-run observation. ### Memory `agent.memory` stores strings within a session. Use `get({ key })`, `set({ key, value })`, `delete({ key })` and `list({ prefix? })`; keys are nonempty and deletion is idempotent. Missing entries return null; entries contain `key`, `value` and ISO `updatedAt`. Keep a session under 1,000 keys: writes past that still succeed but are flagged, and `list` fails with `INVALID_INPUT` once a session holds more than 10,000; rewrite or delete keys instead of adding one per run. `list` returns all matching keys and timestamps in UTF-8 key order. Omit prefix for every key. An empty array means no matches; failed reads throw [ApiError](../sdk-reference/error-handling), never partial results. Writes are last-write-wins and enumeration is not a concurrent snapshot. Persist strategy state and admitted [operation references](../sdk-reference/error-handling), never a second execution status or holdings ledger. `agent.allocation` owns current virtual inventory. Memory is session-only; scope arguments are invalid. Stopping a local session clears its keys. ### Triggers Declare triggers in [circuit.toml](../getting-started/circuit-toml-reference#triggers-section). Rolling schedules count from the schedule's last firing, which manual, top-up and other trigger runs never move; resuming a session restarts the count; fixed schedules align to clock boundaries (hourly at `:00`, or every fifteen minutes at `:00`, `:15`, `:30`, `:45`). Hosted sessions fire at a stable second within the scheduled minute, chosen per session, so agents never start in lockstep. Every invocation receives a fresh [`agent.allocation`](../sdk-reference/holdings), refreshed after each money write. A trigger that fires while a run executes waits its turn: a session keeps the newest 200 fired triggers, handles them in order, and drops the oldest when triggers arrive faster than the agent handles them, which the session log says at most once a minute. ### Continuous agents Set `continuous = true` in circuit.toml for one long-lived process instead of one run per trigger. `run(agent)` loops on `await agent.next({ until })`, which returns the next fired trigger or `null` at `until` (epoch milliseconds), and refreshes `agent.allocation` before returning, so the session's own fills, stops and liquidations show even while other wallets' `walletTrade` events keep arriving. Continuous agents declare no schedule triggers; their cadence is the `until` they pass. In a run that is not continuous, `agent.next()` throws a `BAD_REQUEST` error that names the fix instead of waiting. Memory in variables lives while the process does; keep anything you need across restarts in [Memory](#memory). Circuit restarts the process at its next `agent.next()` when the agent's code or the session's settings change, the session is topped up or run manually, or the runtime is updated: that `agent.next()` never returns, the process exits once its pending SDK calls finish, and a new run starts with `agent.trigger.kind === "restart"` (or the queued run's trigger). No exception reaches your code and money calls are never interrupted; a process that does not reach `agent.next()` within five minutes of a restart request is stopped and its run fails. `agent.next()` delivers each fired trigger once: a run that fails after receiving one does not see it again, and the session log names the last trigger that run received. A run that ends for any other reason restarts at most once a minute. The two-hour run deadline does not apply; on Circuit, five minutes without a Circuit call still stops the run, and waiting in `agent.next()` counts as calls. `circuit backtest` replays a continuous agent on its replay clock: `agent.next()` returns the triggers that fire minute by minute and `null` at `until`. `circuit run` runs it until you stop it, and `agent.next()` returns its price, fill and position triggers as they fire on live data; price triggers need market data, so they fire under `circuit run --simulated` and are refused by a plain wallet run, and other trigger kinds fire only for agents Circuit hosts. ### Execution limits and failures On Circuit, five minutes without a Circuit call stops a run. SDK calls, including logging and data reads, reset the silence clock; reading `agent.allocation`, local sleep, hangs and computation do not. Return and continue on a later trigger when work requires a longer wait. A run fails two hours after it is due, including time spent queued behind the session's previous run; Circuit, `circuit run` and `circuit backtest` stop it at that deadline. Uncaught exceptions fail the execution and are logged automatically. Hosted runs reach outside services only over TCP ports 443 (HTTPS) and 80 (HTTP), each run from a public IPv4 address of its own (an AWS us-east-1 Elastic IP) that no other active run shares. Other ports, private addresses, and UDP other than DNS are refused. Local `circuit run` has your machine's network. Each money operation has its own lifecycle deadline: three minutes for a cross-chain swap and thirty seconds for everything else, counted from when its turn begins, so operations queued behind a conflicting one on the same wallet don't spend it waiting. High-level SDK calls may sequence multiple operations, such as approval followed by a newly quoted swap; each is separately admitted, and failure stops the sequence without retrying. Earlier successful transactions remain recorded. Stopping cannot undo provider-accepted effects. A deadline ends the wait, not the outcome: a submitted operation stays pending until evidence settles it, past its settlement bound it becomes `unproven` while Circuit keeps watching, and nothing is ever resubmitted. # Agent Structure & Configuration Source: https://docs.circuit.org/agent-developers/getting-started/circuit-toml-reference Agent entry points, DESCRIPTION.md, the complete circuit.toml contract, and multi-agent Bun workspaces. An agent contains `circuit.toml`, `DESCRIPTION.md`, `AGENTS.md`, `index.ts` exporting [`run(agent)`](../concepts/execution-model#agent-context), `package.json`, and the generated `circuit-sdk.d.ts` and `circuit-settings.d.ts`. ## DESCRIPTION.md Users review this description before Start; `circuit new` writes a starter whose every line says what belongs there. It has three sections, and upload rejects any other shape: * `## Thesis`: one sentence of at most 160 characters on what the agent trades and how it makes money. * `## Strategy`: up to three `- **Title:** rule` lines on what makes it act, when it exits and how it sizes. Titles are at most 32 characters; each rule is one sentence of at most 160. * `## Exposure`: the same six `- **Label:** answer — detail` lines for every agent, in this order: Holds, Venue, Leverage, Costs, Data, On unwind. Answers are at most 24 characters and details at most 240. Data is Circuit, or names each outside host the agent calls. ## circuit.toml | Field | Required | Contract | | - | - | - | | `agentId` | Yes | Permanent UUID created by `circuit new`; never edit it. Uploads replace its runnable content, and `circuit check` rejects duplicate IDs across a workspace. | | `name` | Yes | Display name, at most 32 characters. | | `tagline` | Yes | Card subtitle, at most 32 characters. | | `category` | No | `spread`, `index`, `prediction`, `quant`, `yield`, or `experimental`. | | `imageUrl` | No | The agent's icon, hosted by Circuit. Set it on the agent's page in Circuit or in the Builder, which writes its URL here; publishing refuses any other host. Omit it to use the agent's generated tile everywhere. | | `walletVmFamily` | Yes | `evm` or `solana`, the family of the session wallet; it must be set explicitly. | | `triggers` | Yes | One or more schedule or supported reactive triggers. | | `startingAsset` | For Start | Asset identity and `minimumAmount` in whole tokens; use `"0"` for a zero-amount start. | | `settings` | No | User-configurable values, snapshotted with each upload. | | `exchangeCredentials` | No | Required venue credential and allocation contract. | ## Account readiness Circuit infers startup account requirements from `startingAsset`: HyperCore assets require an existing Hyperliquid account; Polygon pUSD, USDC.e and outcome tokens require an account Polymarket accepts orders from: a Deposit Wallet, or an EOA with Polymarket trading history. Controlled Deposit Wallets require deployment regardless of starting asset. Circuit configures every wallet's accounts itself. No additional configuration declaration is needed. Starts check readiness. The heuristic does not predict a different venue chosen later by the strategy; transaction preparation checks every actual action, configures what it can and otherwise returns `ACCOUNT_SETUP_REQUIRED`, or `ACCOUNT_FUNDING_REQUIRED` for an account its first deposit opens, before submission. Failed reads block execution, and setup never grants signing authority. ## `[[triggers]]` Section Set `continuous = true` for a [continuous agent](../concepts/execution-model#continuous-agents); it declares no schedule and may declare no triggers at all. Each schedule has `type = "schedule"`, an `everyMs` duration in integer milliseconds divisible by 60000 (one minute), and `align = "rolling"` or `"fixed"`. `rolling` starts after the last run; `fixed` aligns to clock boundaries and must divide one hour. A price trigger uses venue `hyperliquid`, an exact canonical perp `asset`, and condition `cross`, `abs_move`, or `pct_move`. Position triggers name their `asset` (a Hyperliquid perp or a Polymarket outcome token id); fill triggers name a perp venue or Polymarket and may omit it to match any fill. A `resolution` trigger with venue `polymarket` names no asset and fires once per resolved market the session holds, carrying one held outcome `asset`; redeeming it redeems the whole market. A `news` trigger names a natural-language `prompt` (for example `"Donald Trump posts about Iran"`) and fires once for each matching news item. A `webhook` trigger names a trusted [webhook provider](../../webhooks) as `provider` (`polysights`) and fires once for each event the provider pushes; the run checks the event's own fields to decide whether it cares, and backtests never fire it. A `walletTrade` trigger names only a watched `wallet`, an EVM or Solana address (a continuous agent may omit it to watch the up to 100 wallets it sets with [`agent.watchedWallets.set`](../sdk-reference/watched-wallets), with no `cooldownMs`), and fires once for each trade the wallet makes, seconds after it lands: a transaction on any EVM network or Solana in which the wallet paid with some assets and got others, a Relay cross-chain buy it paid for, and each fill of its Hyperliquid (every perp DEX, Trade\[XYZ] included), Lighter and Lighter Robinhood main-account and Derive perp and option trades, and each Papertrade position it opens or closes. Assets it only receives (deposits, airdrops, dust) or only sends never fire it, and a transaction counts only when the wallet signed it or paid the native coin or a listed token, so a scam token's made-up transfer never does. The run receives the [trade](../concepts/execution-model#triggers) and names its copy's `once` after the trade's `transaction` or `id`. With many watched wallets, a venue fill can arrive up to a minute late while the venue is at Circuit's read capacity. Builder turns a FOMO username or leaderboard into triggers on the traders' wallets. The `cross` and `abs_move` conditions require a positive decimal `thresholdUsd` (USD mark price or USD price movement). `pct_move` requires positive decimal `thresholdPercent`: `"0.5"` means 0.5%, with no `%` or `bps` suffix. `cooldownMs` is the minimum interval between reactive firings, default zero, at most 2147483647 milliseconds (the stored integer range). ## `[startingAsset]` Section `network` is `solana`, `ethereum:`, or `hypercore`. `asset` identifies the contract or native token: EVM `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`, Solana `11111111111111111111111111111111`, or HyperCore index `0` for Core USDC. `minimumAmount` is the smallest allocation Start accepts and its default, a decimal string of whole tokens such as `"10"` for ten USDC. Derive it from the strategy: the least allocation at which its sizing places every order it holds at once at or above each venue minimum, plus the fees and gas it pays from the allocation. Top-ups have no minimum. Arc (`ethereum:5042`) starting USDC uses the native EVM sentinel; the ERC-20 interface is the same balance and is rejected as starting inventory. For an existing HyperCore perpetual, set `asset` to its exact coin (for example `"BTC"` or `"xyz:GOLD"`) and `expectedSide` to `"long"` or `"short"`; the session's holding keeps the position's direction and venue entry price, and its collateral is assigned separately. For an existing Polymarket outcome, use `network = "ethereum:137"`, `asset` set to the market's share contract (Conditional Tokens `0x4d97dcd97ec945f40cf65f87097ace5ea0476045` for markets Polymarket lists as protocol v1, PositionManager `0x006f54f7f9a22e0000cc2ab60031000000ae9fef` for v2 markets), and the decimal outcome `tokenId`. Start assigns only the selected unallocated quantity. Kraken trade agents use `"0"` because their funds are allocated on the Kraken account. An agent with a `position`, `fill` or `resolution` trigger on a venue starts on that venue's network (`hypercore` for Hyperliquid, `ethereum:137` for Polymarket), because Paper trading and new sessions fund only the starting asset; uploads reject any other start. ## `[settings]` Section Each key defines one setting (maximum 3). Types are `text`, `boolean`, `single_select`, `integer`, `number`, `percentage`, and `address`. Every setting carries a same-type `default`; users override it when they start a session. `single_select` alone requires up to 20 unique `options`, including its default. Percentages range from 0 through 100. `integer`, `number` and `percentage` alone may declare an inclusive `min`, `max`, or both, where `min` must not exceed `max`; the default and every session override must satisfy them. Addresses must match `walletVmFamily`. At runtime `agent.settings` merges every setting's default with the session's overrides, so each declared key always has a value: a string for `text` and `address`, a union of its `options` for `single_select`, a boolean for `boolean`, and a number for `integer`, `number` and `percentage`. `circuit check` regenerates `circuit-settings.d.ts` from your `[settings]` tables, so `agent.settings` carries exactly the keys you declared. Reading a key `circuit.toml` does not define is a compiler error. [`circuit run --setting KEY=VALUE`](../cli-references/development#run-and-stop-flags) overrides a default for one local invocation. ## `[exchangeCredentials]` Section One venue may be declared, with `access = "read"` or `access = "trade"`. Trading also declares a positive `minimumAllocation` in the exchange's asset code, for example `access = "trade"` and `minimumAllocation = { asset = "USD", amount = "25" }` on Kraken, or `{ asset = "USDT", amount = "25" }` on Binance. Circuit asks the user to pick the credential and allocation, scopes the runtime permit to them, and never exposes the secret or credential id to agent code. Private exchange methods use the attachment automatically. `circuit.toml` has no version field, and Circuit rejects unknown fields. Upload content is hashed and versioned by Circuit. Keep runtime assets inside the agent directory; share code through a [multi-agent workspace](#multi-agent-workspace). Circuit applies one [fixed source exclusion policy](../cli-references/uploading#fixed-source-exclusions) to checks, local runs, uploads and Builder saves. `.circuit` is reserved for CLI state. ## Multi-agent workspace The CLI detects standalone projects and Bun workspaces. Each shared package owns its dependencies; agents import packages by name. Upload sends the workspace source and lockfile. Circuit installs the agent's production dependencies into one code artifact. Keep the root `package.json` and `bun.lock` at the top, each agent in `agents//` with its `index.ts`, `circuit.toml`, `DESCRIPTION.md` and `package.json`, and each shared package in `shared//`, and declare the workspace in the root `package.json`: ```json theme={"theme":{"light":"nord","dark":"nord"}} { "private": true, "workspaces": ["agents/*", "shared/*"] } ``` Give each shared package a `package.json` with a `name` and `main`, depend on it from the agent with `"@lib/polymarket": "workspace:*"`, and import it as `import { getPositions } from "@lib/polymarket"`, without TypeScript path aliases. Run `bun install` at the root and commit `bun.lock`. Editing an uploaded workspace agent copies its uploaded workspace config, lockfile, agent directory and shared packages into the builder. Bun links the packages as in the source monorepo. The builder copy is a snapshot, not a live link to the original repository. # Install the Circuit CLI Source: https://docs.circuit.org/agent-developers/getting-started/installation Install the Circuit CLI on macOS or Linux. It scaffolds, runs, backtests and uploads TypeScript trading agents with no other runtime required. ### What you'll need * Apple Silicon macOS or glibc Linux (x64 or ARM64). Intel Macs and native Windows are not supported. * A Circuit account (for uploading agents and hosted dev runs) ### Install the CLI ```bash theme={"theme":{"light":"nord","dark":"nord"}} curl -fsSL https://api.circuit.org/dev | bash circuit --version ``` The installer puts one self-contained `circuit` binary in `~/.local/bin`. If that directory is not on your `PATH`, zsh and bash users get it added to their shell's startup file and an `export` line to run in the current terminal; run it or open a new terminal before `circuit --version`. Other shells need `~/.local/bin` added to `PATH` by hand. Run `circuit upgrade` to replace the binary with the newest release. Right after Circuit updates its API, `circuit upgrade` and the installer can answer that the new CLI is not published yet and say when to try again. ### The SDK comes with the CLI Import from `circuit:sdk`; the CLI supplies it locally and the hosted runtime supplies it after deployment. Never add the SDK as a project dependency. # Quickstart: your first trading agent Source: https://docs.circuit.org/agent-developers/getting-started/quickstart Create, run, verify and upload your first Circuit trading agent in TypeScript: scaffold with circuit new, test locally, then upload with circuit upload. ### Create an agent ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit new --name agent-name cd agent-name ``` The generated agent swaps 10% of its Base USDC allocation into ETH each run and logs the amount. Edit `index.ts`, `circuit.toml` and `DESCRIPTION.md` together. Sign-in is required only for account-backed commands. ```toml circuit.toml theme={"theme":{"light":"nord","dark":"nord"}} name = "Example Agent" tagline = "Buys ETH every 15 minutes" category = "experimental" walletVmFamily = "evm" [[triggers]] type = "schedule" everyMs = 900000 align = "rolling" [startingAsset] network = "ethereum:8453" # Base asset = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913" # USDC minimumAmount = "10" ``` ```typescript TypeScript theme={"theme":{"light":"nord","dark":"nord"}} import { MINIMUM_SWAP_USD, decimalCompare, decimalMultiply, type RunFunction } from "circuit:sdk"; const BASE = "ethereum:8453"; const USDC = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"; const ETH = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; export const run: RunFunction = async (agent) => { const usdc = agent.allocation.holdings .filter((holding) => holding.kind === "token") .find((holding) => holding.network === BASE && holding.asset === USDC); const amount = decimalMultiply(usdc?.availableQuantity ?? "0", "0.1"); const valueUsd = usdc?.priceUsd ? decimalMultiply(amount, usdc.priceUsd) : null; if (valueUsd === null || decimalCompare(valueUsd, MINIMUM_SWAP_USD) < 0) return agent.log(`Waiting for funds: ${amount} USDC is under the $${MINIMUM_SWAP_USD} swap minimum.`); await agent.log("USDC is free to spend; buying ETH with a tenth of it."); await agent.swaps.create({ from: { network: BASE, asset: USDC }, to: { network: BASE, asset: ETH }, amount, }); }; ``` ### Verify locally ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit check --json ``` For live execution, create a local wallet; the [development reference](../cli-references/development#run-agent-locally) covers hosted wallets and the risks: ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit wallet add --name "Development wallet" --generate evm circuit run --wallet "Development wallet" --amount 10 ``` ### Upload ```bash theme={"theme":{"light":"nord","dark":"nord"}} circuit auth login circuit upload ``` Put required secrets in the agent's `.env` before uploading; see [environment variables](../cli-references/uploading#environment-variables). Users can then start the uploaded agent in the [Circuit app](https://app.circuit.org). # Build a crypto trading agent with the Circuit SDK Source: https://docs.circuit.org/agent-developers/overview How to build, test, backtest and upload Circuit trading agents in TypeScript with the Circuit CLI and SDK, then run them hosted on users' wallets. ### AI-Assisted Development * [**llms.txt**](https://docs.circuit.org/llms.txt) - Lightweight site index for LLMs * [**llms-full.txt**](https://docs.circuit.org/llms-full.txt) - Complete documentation in a single file * **MCP Server** - `claude mcp add circuit --transport http https://docs.circuit.org/mcp` Circuit agents are programs that run on Circuit's infrastructure, read their session's holdings, and request transactions on behalf of users. You write a `run` function, Circuit calls it whenever a trigger declared in `circuit.toml` fires, and any transactions your code requests are routed through a secure signing layer - your agent never touches private keys. # Data Source: https://docs.circuit.org/agent-developers/sdk-reference/data Discover assets and markets; read prices, derivatives and fundamentals from every agent run. `agent.data` mirrors camel-case `circuit data` commands. [Data commands](./data-commands) defines parameters, rows, conventions and help order. Only paged methods support async iteration. Hosted and hosted-engine runs read `/data/*` with the session's permit; local wallet runs return empty rows without contacting Circuit, while `circuit run --simulated` reads the same data with your `circuit auth login` sign-in. Use `decimalCompare` for exact price comparisons. ## Discovery Contract-reference errors preserve invalid vendor claims without blocking healthy rows. Inspect errors before using catalog or pool/yield token references; request inputs reject invalid references. Resolve `asset` IDs from `assets` at runtime: they are database-specific, not symbols. `categoryKey` filters vendor categories; `underlyingAsset` finds derived assets, including tokenized stock instruments. Iterate assets to follow cursors with unchanged filters; breaking stops requests and failures throw `ApiError`. Await the call for one page and its `nextCursor`. ```typescript theme={"theme":{"light":"nord","dark":"nord"}} for await (const asset of agent.data.assets({ assetType: "coin" })) { await agent.log(asset.id); } ``` ## Prices and history `prices` names an asset as its allocation holding does and answers its newest `price` with exactly `bars` gap-free bars, oldest first, or `bars: null` while it has less history than that. ```typescript theme={"theme":{"light":"nord","dark":"nord"}} const { price, bars } = await agent.data.prices({ network: "hypercore", asset: "BTC", interval: "1h", bars: 48 }); if (!bars) return agent.log("BTC has under 48 hours of history"); ``` # Data commands Source: https://docs.circuit.org/agent-developers/sdk-reference/data-commands What every hosted data command answers, the identity its rows are keyed by, the flags it takes, and what each field means. These commands also appear in `circuit data --help`. See [Data](./data) for the TypeScript surface, where `agent.data.` calls the command of the same name in camel case. ## Across every command * Prices, amounts, percentages and fractional rates are decimal strings; counts and leverage are numbers. Units: a Base figure counts the market's base asset, and a Quote figure is stated in its quote asset. On a market row, a Usd figure is that quote figure valued at Circuit's own mark for the quote asset, null when Circuit holds no such mark. An OHLC figure is quote units per one base unit, and a rate is a fraction, never a percent. * A venue is where a thing trades; a vendor is a third party reporting facts it does not host. prices is keyed the way an allocation holding names an asset, by --network and --asset, and Circuit picks the asset's one price source. A command named for a market (markets, funding_rates, open_interest) reports what one venue saw and is keyed by --venue and --venue-symbol; asset_fundamentals reports what a vendor says about the asset across the whole market and is keyed by --asset. Every one of them is a display and accounting fact, never the price an action acts on: a swap takes its price from the executable quote it returns, and a venue order prices itself from that venue's live read; what a token or pool just did on a chain comes from pools. * Over the CLI and HTTP, a read that answers observations answers \{ rows, ageMs }, and agent.data answers it without ageMs: each key that answered contributes its own newest observation and a key that answered nothing contributes no tip, so the read's tip is the oldest of the tips that answered, and ageMs is the milliseconds from the read's instant, --as-of or now, back to it, null when rows is empty or nothing the read names answered. assets answers identity, which does not decay, so it answers \{ rows, nextCursor } with no ageMs. prices answers \{ price, pricedAt, historyStartsAt, bars }, its freshness carried by pricedAt and each bar's opensAt. * Durations are integer milliseconds and windows are positive. No read is refused for age; Circuit owns feed freshness, so agents act on every answer as served. * A venue, dex or venue symbol the catalog holds no market under fails the read with 404 MARKET_NOT_CATALOGED, naming every symbol it does not hold, rather than answering an empty envelope; a delisted market is still cataloged, so it still answers. * Collection parameters are nonempty arrays in the SDK and model tools; repeat their flags in the CLI. HTTP reads take any Circuit permit as a Bearer token and POST every parameter as one JSON body, such as POST /data/assets with \{"assetType":"coin"}. Counts such as limit are numbers and filters such as stablecoinOnly are booleans; the answer is grouped by key and every row names its own. * Times are UTC ISO strings to the millisecond (2026-11-01T00:00:00.000Z); an --as-of covers its whole millisecond. * A command that takes --lookback-ms answers, without it, its newest observation per key as of --as-of or now: the live funding or open interest row, the latest yield reading, or the newest ended day of revenue, asset fundamentals or category fundamentals. markets is the exception, where the window only adds the windowed figures. * funding_rates and open_interest over --lookback-ms, and assets, asset_fundamentals, yields, revenue and categories without --sort-by, answer up to 20000 rows per page, in key then time order, with nextCursor: pass it back as --cursor with every other parameter unchanged until it is null, and every --lookback-ms page reads as of the first page's instant while a listing without it pages by key over current values. A page's ageMs counts only the keys it finishes, null when every key continues on the next page. Every other read answers all its rows at once, a ranking its --limit rows, required except on markets, with nextCursor null. Circuit shows at most 50 rows of an answer. ## Discovery ### `assets` List asset identities, contracts, venue listings and vendor keys. Identity rather than observation, so it carries no age and states every link as of --as-of. --search is how an asset named in words is found, matching a substring of its symbol or name; a pasted contract address or mint finds the asset holding it on any chain. It is the lookup behind the other commands' keys: an asset's id is their --asset, its vendorIdentifiers carry the vendorKey asset_fundamentals reports under, its venueIdentifiers carry the venue, dex and venueSymbol the market commands take, and its contracts carry the network and address prices and pools take. One row per `id`. Parameters: `venue` (optional, string; hyperliquid, lighter, lighterRobinhood, derive, papertrade, polymarket, kraken, coinbase, binance, okx, bybit, kalshi, qfex); `venueSymbol` (optional, array); `dex` (optional, string); `asset` (optional, array); `network` (optional, string; solana, hypercore, lighter, lighter-robinhood, papertrade, derive, ethereum:1, ethereum:42161, ethereum:137, ethereum:10, ethereum:8453, ethereum:56, ethereum:143, ethereum:999, ethereum:4663, ethereum:5042, ethereum:57073, ethereum:747474, ethereum:99901); `address` (optional, string); `vendor` (optional, string; defillama, coingecko, coingecko-rwa); `vendorKey` (optional, string); `assetType` (optional, string; coin, perpetual, vault, prediction, stock, fiat, commodity, etf, bond); `categoryKey` (optional, string); `search` (optional, string); `underlyingAsset` (optional, array); `includeDelisted` (optional, boolean); `cursor` (optional, string); `asOf` (optional, string). See [definitions](#definitions). Row fields: `id`, `symbol`, `name`, `assetType`, `underlyingAsset`, `venueIdentifiers`, `venueIdentifiers[].venue`, `venueIdentifiers[].dex`, `venueIdentifiers[].venueSymbol`, `venueIdentifiers[].quoteAsset`, `venueIdentifiers[].quoteSymbol`, `venueIdentifiers[].delistedAt`, `vendorIdentifiers`, `vendorIdentifiers[].vendor`, `vendorIdentifiers[].vendorKey`, `categoryKeys`, `contracts`, `contracts[].network`, `contracts[].address`, `contracts[].error`. See [definitions](#definitions). ### `markets` Discover live venue markets and compare their trading statistics. Use --venue-symbol for exact named markets; omit it to discover the venue. A derived view that owns no fact: every figure is a join over the venue's bars and the current mid, open interest and funding, plus the quote asset's mark. Its age bounds the mid, open interest and funding; dayAgoPrice, volumeQuote and volumeUsd come from complete bars and never move the tip. dayAgoPrice is null only when the market had not traded 24 hours ago, and volumeQuote is null, never zero, when no complete hourly bar falls in the trailing 24 hours. --lookback-ms is optional and names the window for the five windowed figures, which stand as of the last complete day or settlement, contribute no tip, and read null when no window is asked for. One row per `venue, dex, venueSymbol`. Parameters: `venue` (required, string; hyperliquid, lighter, lighterRobinhood, derive, papertrade, polymarket, kraken, coinbase, binance, okx, bybit, kalshi, qfex); `venueSymbol` (optional, array); `dex` (optional, string); `assetType` (optional, string; coin, perpetual, vault, prediction, stock, fiat, commodity, etf, bond); `lookbackMs` (optional, number); `asOf` (optional, string); `sortBy` (optional, string; volumeUsd, openInterestUsd, fundingRate, cumulativeFundingRate, medianDailyVolumeUsd); `order` (optional, string; desc, asc); `limit` (optional, number). See [definitions](#definitions). Row fields: `venue`, `dex`, `venueSymbol`, `assetType`, `underlyingAsset`, `underlyingAssetType`, `baseSymbol`, `quoteSymbol`, `maximumLeverage`, `marginRule`, `minimumNotional`, `minimumSize`, `sizeStep`, `priceTick`, `price`, `priceUsd`, `dayAgoPrice`, `volumeQuote`, `volumeUsd`, `openInterestBase`, `openInterestQuote`, `openInterestUsd`, `fundingRate`, `settlesAt`, `medianDailyVolumeQuote`, `medianDailyVolumeUsd`, `observedDayCount`, `cumulativeFundingRate`, `fundingSettlementCount`. See [definitions](#definitions). ### `pools` Discover pools, new launches, constituents and windowed trading activity; only onchain pools carry liquidity and activity. Without --sort-by and --limit, name the pools with --pool; a liquidityUsd ranking answers only pools that have one. Two vendors answer side by side. A defillama row is a yields opportunity described by the vendor and carries no creation, fee, flow or liquidity, so it never matches --created-within-ms or a liquidity or activity ranking; rank onchain rows. An onchain row is a Uniswap v2, v3 or v4 or Aero Slipstream pool we read from the chain ourselves, keyed network|poolId, carrying its creation block's instant and one minute and hour of flow per token it traded. Every traded figure is derived at read time from the pool's two legs: the quote leg is the constituent among the chain's own quote tokens, the base leg is the other one, and a pool with no such leg or with other than two constituents still answers with its counts at zero and its legs null. Counts are taken once from the base leg, since one swap touches both tokens, and a buy is base leaving the pool. lastPrice, lastTradeMinute and the reserves are the pool's newest traded minute rather than the window's, so a quiet window still says where it last traded, and that minute may still be in progress. Activity figures are each pool's stored 1h, 24h or 7d window, kept as each minute of flow is recorded; --as-of anchors only pool identity and age, and an activity ranking refuses it. The read's tip is the last instant the pool detector scanned each network in scope through that chain's head, computed before the rows, so an empty answer still carries an age and a feed reading behind the head ages until it catches up; a network never scanned to its head contributes no tip, and the read has no age when none of them has. One row per `vendor, pool`. Parameters: `network` (optional, array); `vendor` (optional, string; defillama, onchain); `protocol` (optional, string); `factory` (optional, array); `pool` (optional, array); `token` (optional, array); `asset` (optional, array); `quoteToken` (optional, array); `createdWithinMs` (optional, number); `minLiquidityUsd` (optional, string); `minQuoteReserve` (optional, string); `sortBy` (optional, string; tradeCount, volumeUsd, volumeQuote, liquidityUsd, priceChangeInWindow, createdAt); `order` (optional, string; desc, asc); `limit` (optional, number); `lookbackMs` (optional, number); `asOf` (optional, string). See [definitions](#definitions). Row fields: `vendor`, `pool`, `network`, `protocol`, `factory`, `label`, `createdAt`, `firstObservedAt`, `depositToken`, `fee`, `tickSpacing`, `hooks`, `baseToken`, `baseAsset`, `baseSymbol`, `quoteToken`, `quoteRole`, `quoteAsset`, `quoteSymbol`, `tradeCount`, `buyCount`, `sellCount`, `volumeBase`, `volumeQuote`, `volumeUsd`, `baseReserve`, `quoteReserve`, `liquidityUsd`, `lastPrice`, `lastTradeMinute`, `priceChangeInWindow`, `liquidityChangeInWindow`, `constituents`, `constituents[].address`, `constituents[].symbol`, `constituents[].asset`, `constituents[].inflow`, `constituents[].outflow`, `constituents[].reserve`. See [definitions](#definitions). ## Prices ### `prices` Read any asset's price now and its last bars as one regular series. Name the asset exactly as an allocation holding names it, by network, asset and tokenId; Circuit picks its one price source: the venue's own trades for a market on Hyperliquid, Lighter or Derive (a Papertrade perp reads its Hyperliquid market and a venue token its dollar market), the vendor's price for a token the catalog lists, the live price of its most liquid pool for any other Solana token (at most 1000 bars, never as of a past instant, so backtests cannot replay it), and otherwise Circuit's own mark. price is the newest price as of the read with its pricedAt: the live mid of a venue market, else the newest observation however old. bars is exactly --bars bars of --interval, oldest first, the last one the newest bar Circuit has closed, with no gaps: a bar in which nothing traded or nothing was observed carries the previous close with volume 0, never a guessed price. bars is null whenever the asset has fewer bars than asked, and historyStartsAt says when its history begins, null when Circuit holds none; Circuit keeps 1m bars for 30 days and every coarser interval for good; price and pricedAt are null when Circuit has no price at all. A venue symbol the catalog does not list fails with MARKET_NOT_CATALOGED. One row per `opensAt`. Parameters: `network` (required, string; solana, hypercore, lighter, lighter-robinhood, papertrade, derive, ethereum:1, ethereum:42161, ethereum:137, ethereum:10, ethereum:8453, ethereum:56, ethereum:143, ethereum:999, ethereum:4663, ethereum:5042, ethereum:57073, ethereum:747474, ethereum:99901, kraken, qfex); `asset` (required, string); `tokenId` (optional, string); `interval` (required, string; 1m, 5m, 15m, 1h, 4h, 1d); `bars` (required, number); `asOf` (optional, string). See [definitions](#definitions). Row fields: `opensAt`, `open`, `high`, `low`, `close`, `volume`. See [definitions](#definitions). ## Derivatives ### `funding_rates` Read predicted next funding or settled rates over a window. The current row is the predicted rate and its settlesAt lies in the future; under --as-of it is the rate settled at or before that instant, so settlesAt lies in the past and the quantity means the same thing either way. One row per `venue, dex, venueSymbol, settlesAt`. Parameters: `venue` (required, string; hyperliquid, lighter, lighterRobinhood, derive, papertrade, polymarket, kraken, coinbase, binance, okx, bybit, kalshi, qfex); `venueSymbol` (required, array); `dex` (optional, string); `lookbackMs` (optional, number); `asOf` (optional, string); `cursor` (optional, string). See [definitions](#definitions). Row fields: `venue`, `dex`, `venueSymbol`, `settlesAt`, `fundingRate`. See [definitions](#definitions). ### `open_interest` Read current or historical market open interest. The one market fact prices cannot hold; a spot market has no row. The current row is stamped at its own refresh instant. One row per `venue, dex, venueSymbol, timestamp`. Parameters: `venue` (required, string; hyperliquid, lighter, lighterRobinhood, derive, papertrade, polymarket, kraken, coinbase, binance, okx, bybit, kalshi, qfex); `venueSymbol` (required, array); `dex` (optional, string); `lookbackMs` (optional, number); `asOf` (optional, string); `cursor` (optional, string). See [definitions](#definitions). Row fields: `venue`, `dex`, `venueSymbol`, `timestamp`, `openInterestBase`. See [definitions](#definitions). ## Fundamentals ### `yields` Compare deposit opportunities, returns, exposure and exit conditions. One token carries as many opportunities as there are protocols wrapping it, so Curve and Convex over one LP token are two rows told apart by protocol, never one. Advertised rows refresh every 1 hour and measured rows every 24 hours. A row is advertised, a rate the protocol or vendor publishes and a projection, or measured, the return a simulated withdrawal actually realized, net of queues, slippage and partial fills. Measured rows carry the exit facts and put their rate in apyExcludingRewards, since a withdrawal never receives separately-claimed incentives, which makes them directly comparable to an advertised base rate in one column. Tokens are named by contract address and carry our asset id only where we already track them, so depositAsset and a constituent's asset read null for a token outside the catalog. An answer naming nothing we hold is a known zero, never an error. A --sort-by ranking reads each opportunity's current row, so it takes neither --lookback-ms nor --as-of. One row per `vendor, pool, yieldKind, day`. Parameters: `pool` (optional, array); `depositToken` (optional, array); `depositAsset` (optional, array); `constituent` (optional, array); `protocol` (optional, string); `network` (optional, string; solana, hypercore, lighter, lighter-robinhood, papertrade, derive, ethereum:1, ethereum:42161, ethereum:137, ethereum:10, ethereum:8453, ethereum:56, ethereum:143, ethereum:999, ethereum:4663, ethereum:5042, ethereum:57073, ethereum:747474, ethereum:99901); `vendor` (optional, string; defillama); `yieldKind` (optional, string; advertised, measured); `stablecoinOnly` (optional, boolean); `singleAssetExposure` (optional, boolean); `impermanentLossRisk` (optional, boolean); `exploited` (optional, boolean); `offPeg` (optional, boolean); `sortBy` (optional, string; apyIncludingRewards, apyExcludingRewards, totalValueLockedUsd, apyVolatility); `order` (optional, string; desc, asc); `limit` (optional, number); `lookbackMs` (optional, number); `asOf` (optional, string); `cursor` (optional, string). See [definitions](#definitions). Row fields: `vendor`, `pool`, `yieldKind`, `protocol`, `network`, `label`, `depositToken`, `depositAsset`, `stablecoinOnly`, `singleAssetExposure`, `impermanentLossRisk`, `constituents`, `constituents[].address`, `constituents[].symbol`, `constituents[].decimals`, `constituents[].asset`, `day`, `firstObservedAt`, `apyIncludingRewards`, `apyExcludingRewards`, `totalValueLockedUsd`, `withdrawalOutcome`, `withdrawalEtaMs`, `withdrawableUsd`, `withdrawalSlippagePercent`, `measurementConfidence`, `borrowApy`, `borrowRewardApy`, `totalBorrowedUsd`, `availableBorrowUsd`, `loanToValue`, `exploited`, `apyVolatility`, `holderCount`, `topHoldersShare`, `offPegToken`, `pegDeviation`. See [definitions](#definitions). ### `asset_fundamentals` Read daily vendor asset statistics or rank window aggregates. One row per vendor key, so an asset the vendor prices under two ids answers two rows, told apart by vendorKey and vendor, and --vendor names one: coingecko rows are priced instruments and coingecko-rwa rows are the real-world underliers they track, whose figures are the tokenized instruments' aggregate. --category-key and --asset-type narrow the assets read, so a ranked read over one category or type is one call. A day's volume is the 24 hours ending when the sweep ran, attributed to the day that just ended; the other figures are that instant's readings. A ranked read answers one row per vendor key with the window sum of volume, the newest day of every other figure, and observedDayCount, ordered on the one --sort-by names. Rankings are stored as each day is written: the newest day, or a --lookback-ms of 86400000, 604800000 or 2592000000 ending at it, never an --as-of. A --lookback-ms listing names --asset; without --lookback-ms the newest day of each key in scope is one row. An asset with no rows has no vendor id or has not been swept yet; assets shows its vendorIdentifiers. One row per `vendor, vendorKey, day`. Parameters: `asset` (optional, array); `vendor` (optional, string; defillama, coingecko, coingecko-rwa); `assetType` (optional, string; coin, perpetual, vault, prediction, stock, fiat, commodity, etf, bond); `categoryKey` (optional, string); `sortBy` (optional, string; volume, price, marketCap, fullyDilutedValuation, circulatingSupply, totalSupply, maxSupply); `order` (optional, string; desc, asc); `limit` (optional, number); `lookbackMs` (optional, number); `asOf` (optional, string); `cursor` (optional, string). See [definitions](#definitions). Row fields: `asset`, `vendor`, `vendorKey`, `denominationAsset`, `denominationSymbol`, `day`, `firstObservedAt`, `volume`, `price`, `marketCap`, `fullyDilutedValuation`, `circulatingSupply`, `totalSupply`, `maxSupply`, `symbol`, `observedDayCount`. See [definitions](#definitions). ### `categories` Read vendor category market cap and 24h volume by day. The category keys are the ones assets --category-key filters on, and --search finds one by a substring of its key or name. A --lookback-ms listing names --category-key; without --lookback-ms the newest day of every category is one row each. A category the vendor lists without figures has no row. One row per `vendor, categoryKey, day`. Parameters: `categoryKey` (optional, array); `search` (optional, string); `lookbackMs` (optional, number); `asOf` (optional, string); `cursor` (optional, string). See [definitions](#definitions). Row fields: `vendor`, `categoryKey`, `name`, `denominationAsset`, `denominationSymbol`, `day`, `firstObservedAt`, `marketCap`, `volume`. See [definitions](#definitions). ### `metrics` Read DefiLlama's daily market figures: protocol, chain, category and market TVL, volumes, fees, revenue and open interest; stablecoin supply; ETF and bridge flows; exchange volumes; stock valuations; and lending liquidation levels. --subject-kind picks protocol (each day's figures, the protocol's token and catalog asset, and its token's price, market cap and FDV), protocol_trailing, chain_trailing and category_trailing (today's trailing 7- and 30-day fees and revenue, TVL with its 7- and 30-day change, and price-to-sales and price-to-fees, so --sort-by tvlChange30d ranks the fastest growing, small ones first: weigh each row's tvl), sub_protocol, chain, category, total (the whole market), stablecoin, etf, bridge, exchange (centralized and decentralized exchanges' spot and perpetual volume, open interest and depth), equity (each stock's price, market cap and valuation ratios) or liquidation (each token's lending collateral and how much of it liquidates within 5, 10 and 25% of today's price). Name subjects by DefiLlama key (aave, ethereum, lending, coingecko:tether, binance, NVDA, coingecko:ethereum) with --subject, or a protocol's token by catalog asset id with --asset, for each one's newest day, or every day over --lookback-ms. Without --subject, --sort-by and --limit rank the kind's subjects by one figure on its newest day, narrowed by --search or --category. Protocol, chain, category, market, stablecoin, ETF, bridge and exchange days go back to 2023-01-01; protocol_trailing, equity and liquidation exist from the day Circuit began recording DefiLlama's snapshot of them. Protocol, chain and market days also count users, newUsers and transactions. Figures are US dollars for the day, except stablecoinSupply (tokens), protocolCount, users, newUsers, transactions, the changes, ratios and yields; a figure the kind does not carry is null. One row per `subjectKind, subject, day`. Parameters: `subjectKind` (required, string; protocol, protocol_trailing, sub_protocol, chain, chain_trailing, category, category_trailing, total, stablecoin, etf, bridge, exchange, equity, liquidation); `subject` (optional, array); `asset` (optional, array); `search` (optional, string); `category` (optional, string); `sortBy` (optional, string; tvl, stakingTvl, borrowedTvl, pool2Tvl, treasuryTvl, vestingTvl, dexVolume, aggregatorVolume, perpVolume, perpAggregatorVolume, optionsVolume, optionsNotionalVolume, fees, revenue, holdersRevenue, incentives, openInterest, chainFees, chainRevenue, bridgeInflows, stablecoinSupply, etfFlow, bridgeDeposits, bridgeWithdrawals, bridgeVolume, spotVolume, marketDepth, price, marketCap, trailingPe, priceToBook, priceToRevenue, evToEbitda, dividendYield, holdersYield, collateralUsd, liquidatable5pct, liquidatable10pct, liquidatable25pct, fullyDilutedValuation, fees7d, fees30d, revenue7d, revenue30d, holdersRevenue7d, holdersRevenue30d, priceToFees, tvlChange7d, tvlChange30d, chainFees7d, chainFees30d, dexVolume7d, dexVolume30d, users, newUsers, transactions); `limit` (optional, number); `lookbackMs` (optional, number); `asOf` (optional, string); `cursor` (optional, string). See [definitions](#definitions). Row fields: `vendor`, `subjectKind`, `subject`, `name`, `parent`, `category`, `day`, `firstObservedAt`, `token`, `asset`, `protocolCount`, `tvl`, `stakingTvl`, `borrowedTvl`, `pool2Tvl`, `treasuryTvl`, `vestingTvl`, `dexVolume`, `aggregatorVolume`, `perpVolume`, `perpAggregatorVolume`, `optionsVolume`, `optionsNotionalVolume`, `fees`, `revenue`, `holdersRevenue`, `incentives`, `openInterest`, `chainFees`, `chainRevenue`, `bridgeInflows`, `stablecoinSupply`, `etfFlow`, `bridgeDeposits`, `bridgeWithdrawals`, `bridgeVolume`, `spotVolume`, `marketDepth`, `price`, `marketCap`, `trailingPe`, `priceToBook`, `priceToRevenue`, `evToEbitda`, `dividendYield`, `holdersYield`, `collateralUsd`, `liquidatable5pct`, `liquidatable10pct`, `liquidatable25pct`, `fullyDilutedValuation`, `fees7d`, `fees30d`, `revenue7d`, `revenue30d`, `holdersRevenue7d`, `holdersRevenue30d`, `priceToFees`, `tvlChange7d`, `tvlChange30d`, `chainFees7d`, `chainFees30d`, `dexVolume7d`, `dexVolume30d`, `users`, `newUsers`, `transactions`. See [definitions](#definitions). ### `statements` Read financial statements: protocols' and tokens' monthly income statements, and stocks' quarterly and annual income statements, balance sheets and cash flows. --subject-kind picks protocol (a DefiLlama protocol slug: aave, hyperliquid), token (a DefiLlama token key: coingecko:aave) or equity (a ticker of a stock or ETF Circuit lists: NVDA). Name subjects with --subject for their periods ending over --lookback-ms (about the last 13 months by default), narrowed by --statement and --period; each metric answers its total line, and --lines adds the lines that make it up. Without --subject, --sort-by names one metric and --limit ranks the kind's subjects by its total on the newest period that has finished, of one --statement (income by default) and one --period (month for protocols and tokens, quarter for stocks). Protocol and token metrics: gross_protocol_revenue, cost_of_revenue, gross_profit, incentives, earnings, token_holder_net_income, from 2018. Stock metrics include revenue, gross_profit, operating_income, net_income, ebitda, eps_diluted, total_assets, total_liabilities, free_cash_flow. Values are US dollars, except per-share and share-count metrics. One row per `subjectKind, subject, statement, period, periodEnd, metric, line`. Parameters: `subjectKind` (required, string; protocol, token, equity); `subject` (optional, array); `statement` (optional, array); `period` (optional, array); `lines` (optional, boolean); `sortBy` (optional, string); `limit` (optional, number); `lookbackMs` (optional, number); `asOf` (optional, string); `cursor` (optional, string). See [definitions](#definitions). Row fields: `vendor`, `subjectKind`, `subject`, `name`, `statement`, `period`, `periodEnd`, `metric`, `line`, `value`, `firstObservedAt`. See [definitions](#definitions). ### `calendar` Read dated events to trade around: token unlocks, equity earnings dates and SEC filings, governance votes, and protocol hacks. Answers events between --from-day and --to-day, oldest first: by default the next 30 days, and at most 366 days. --kind narrows to unlock, earnings, filing, governance or hack; --subject names a DefiLlama token key (coingecko:\), a ticker or a protocol; --asset names catalog assets, matched against the asset an unlock's token resolves to. An unlock's amount counts tokens released at once (cliff) or its weeklyRate counts tokens per week (linear), and a negative one is DefiLlama correcting an earlier schedule; an earnings row names its fiscal period and whether the date is estimated, inferred or reported; a filing row names its form (10-K, 10-Q, 8-K and their amendments, 20-F, 6-K, 40-F, S-1, DEF 14A), the period it reports and its document, over the last 90 days; a governance row is a proposal dated by when its vote closes, from 30 days back to 60 ahead, with its status, platform (snapshot or tally) and link; a hack row names the stolen and returned US dollars. Check hacks before depositing into a protocol: a recent hack is a reason not to. One row per `kind, subject, day`. Parameters: `kind` (optional, array); `subject` (optional, array); `asset` (optional, array); `fromDay` (optional, string); `toDay` (optional, string); `cursor` (optional, string). See [definitions](#definitions). Row fields: `vendor`, `kind`, `subject`, `name`, `day`, `firstObservedAt`, `asset`, `unlockType`, `recipient`, `category`, `amount`, `weeklyRate`, `linearEndDay`, `fiscalYear`, `fiscalPeriod`, `dateStatus`, `session`, `amountUsd`, `returnedUsd`, `technique`, `classification`, `form`, `reportDay`, `documentUrl`, `description`, `status`, `platform`. See [definitions](#definitions). ## Definitions * `address`: Contract address of the token, as spelled under an assets row's "contracts". * `aggregatorVolume`: US dollars routed through its DEX aggregators that day. * `amount`: Tokens a cliff unlock releases at once; null for linear rows. * `amountUsd`: US dollars stolen in the hack; null when unknown. * `apyExcludingRewards`: Annual compounded yield excluding incentives as a fraction, 0.038 = 3.8%; measured = realized exit. Null on a day the vendor published no figure. * `apyIncludingRewards`: Compounded annual yield with incentives as a fraction; APR converted. Null if measured. * `apyVolatility`: Standard deviation of the pool's daily APY over the last 30 days, as a fraction: a stable yield is near 0. * `asOf`: ISO-8601 with offset, year ≥0001; anchors windows, known catalog links and age. * `asset`: Asset id, as returned in the "id" field of an assets row; a contract as network:address or \{network, address}, or an exact symbol, names it too, and a symbol several assets share fails naming them. * `assetType`: Kind of the base asset, never of the market: coin, perpetual, vault, prediction, stock, fiat, commodity, etf or bond. An index takes the kind of what it tracks, so a stock index is stock and a crypto index is coin. On a markets row coin is a spot pair and perpetual is a perp, and the filter matches the listing's own kind or its underlying's. Options are no markets rows: derive.options.list reads Derive's. * `availableBorrowUsd`: US dollars still available to borrow from the pool; null when the pool lends nothing. * `bars`: How many bars, 1 to 5000; the answer has exactly this many or none. * `baseAsset`: Catalog asset ID of the base token; null for untracked contracts. * `baseReserve`: Latest retained base reserve in whole tokens; null without base leg, reserve or decimals. * `baseSymbol`: Ticker of the leg the row counts Base figures in: the catalog ticker of the market's base asset on a markets row, and on a pools row the constituent's own symbol for the base leg, null when the pool has no base leg. * `baseToken`: Non-quote pool constituent as network/address; null when quoteToken is. * `borrowApy`: Yearly rate a borrower pays the pool before reward incentives, as a fraction; null when the pool lends nothing. * `borrowedTvl`: US dollars borrowed from it. * `borrowRewardApy`: Yearly reward incentives paid to borrowers, as a fraction; a borrower's net cost is borrowApy minus this. * `bridgeDeposits`: US dollars deposited into the bridge that day, across its chains. * `bridgeInflows`: US dollars bridged into the chain that day net of what left it, across bridges DefiLlama does not double count; negative is a net outflow. * `bridgeVolume`: US dollars the bridge carried that day, across its chains. * `bridgeWithdrawals`: US dollars withdrawn from the bridge that day, across its chains. * `buyCount`: Window trades taking base out; zero without a base leg or activity. * `category`: DefiLlama's group for the subject: an unlock's allocation category (insiders, private-sale, farming), a metrics row's protocol category (lending, dexs), an exchange's type (cex, dex) or a stock's sector. * `categoryKey`: Vendor category ID from categories; filters assets, fundamentals and prices. * `categoryKeys`: Vendor category keys, listed by categories and filtered by --category-key. * `chainFees`: US dollars users paid the chain itself in gas that day. * `chainFees30d`: US dollars of the chain's own transaction fees over the last 30 days. * `chainFees7d`: US dollars of the chain's own transaction fees over the last 7 days. * `chainRevenue`: US dollars of the chain's fees burned or kept by its token holders that day. * `circulatingSupply`: Circulating asset units reported by the vendor; not a money amount. * `classification`: Which part of the system the hack hit (protocol-logic, infrastructure, frontend-infrastructure). * `close`: The bar's last price: the last trade on a venue market, the newest observation at the bar's close otherwise, and the previous bar's close when nothing traded or was observed inside it. * `collateralUsd`: US dollars of the token held as lending collateral in the positions DefiLlama tracks (Aave, Morpho, Spark, Maple, Sky, Kamino, Compound, Venus, JustLend, HyperLend). * `constituent`: Filter exposure by catalog asset ID; untracked assets match nothing. * `constituents`: Every token the opportunity leaves a depositor exposed to, one entry each, so a single-asset vault and a 27-token pool read the same way. Each entry carries the token's address, the vendor's symbol for it, its scale, and our asset id where the catalog already tracks the token. A pool's description is the newest one known as of the read, on every day of a window alike, since the vendor's history names the pool and not the composition it had that day. * `contracts`: Every chain contract the catalog holds for the asset as of the read, one \{ network, address } each and none at all for an asset that has no token; a reference that does not parse is kept whole under error rather than dropped. * `createdAt`: Creation block chain time; null for defillama. Not firstObservedAt. * `createdWithinMs`: How old the pool may be, by its creation block: created within this duration of --as-of, or of now without it; e.g. 900000 for 15 minutes. It is the age filter, not the activity window, which is --lookback-ms. Pool age by chain time, never when we stored it, so a pool admitted during a catch-up is as old as the chain says. Required unless --pool, --token or --asset names what to answer, and a defillama row, which carries no createdAt, never matches it. * `cumulativeFundingRate`: Sum of settled window rates; not annualized. Mean divides by fundingSettlementCount. * `cursor`: A paged read answers up to 20000 rows per page; pass back its nextCursor, other flags unchanged, until it is null. * `dateStatus`: Whether the earnings date is estimated, inferred or reported by the company. * `day`: The UTC day the figure belongs to, not the instant the vendor stamped it. An advertised yields row answers the running day, since it is a snapshot of the pool as it stands; a measured yields row, and every revenue and volumes row, answers a day once it has ended, since the vendor's figure for it is a daily measurement. firstObservedAt says when we stored it. * `dayAgoPrice`: The market's last traded price 24 hours before the read, however long before that it traded; the baseline for the rolling 24h change. * `decimals`: How many base units make one whole token, as the vendor states it. * `delistedAt`: When the venue stopped listing this market, null while it still trades. * `denominationAsset`: Catalog asset ID of the money unit the row's amounts are in. * `denominationSymbol`: Money-unit ticker for the row; supply fields count the asset itself. * `depositAsset`: Catalog asset ID of the deposit token; null for untracked contracts. * `depositToken`: Network/address reference of the token the opportunity is about: the pool's LP or receipt token, the vault's share token, null where the protocol issues none. As a filter, pass a returned object without error directly; depositAsset selects catalog IDs; either filter can match. * `description`: The filer's own description of the document. * `dex`: Hyperliquid dex the market lives on, as spelled under a markets row: main for the venue's own perps and every spot pair, otherwise the builder dex's name. Omit it to read every dex the venue lists. * `dexVolume`: US dollars traded on its spot DEXs that day. * `dexVolume30d`: US dollars traded on the chain's DEXes over the last 30 days. * `dexVolume7d`: US dollars traded on the chain's DEXes over the last 7 days. * `dividendYield`: The last twelve months' dividends over market cap, as a fraction: 0.004 = 0.4%. * `documentUrl`: The filing's primary document on the SEC's EDGAR site, or the governance proposal's page. * `error`: Invalid token reference; original network/address retained. Exclude before use. * `etfFlow`: US dollars that flowed into the ETF that day; negative is an outflow. * `evToEbitda`: Enterprise value over the last twelve months' EBITDA. * `exploited`: Whether DefiLlama marks the pool as affected by an exploit; check calendar hacks for the protocol before depositing. As a yields parameter, true answers only exploited pools and false only the rest. * `factory`: Network/address reference that emitted the pool's creation event, the deployer, which is how a fork is told from the protocol it copies since protocol names only the event interface; null where no creation event named one. As a filter, pass that reference object; it matches the network and address together. * `fee`: The pool's fee as the protocol stores it, in hundredths of a basis point, so 3000 is 0.3%. A pool whose fee is set by its hook carries the dynamic-fee sentinel instead: test fee & 0x800000 (8388608) and read the live fee from the hook rather than from this number. Null where the protocol stores no fee: Uniswap v2, and Aero Slipstream, whose hook sets the fee per swap. * `fees`: US dollars users paid the protocol, chain or category that day. * `fees30d`: US dollars users paid the protocol over the last 30 days. * `fees7d`: US dollars users paid the protocol over the last 7 days. * `firstObservedAt`: When we first stored this day's figure. On revenue and volumes a vendor restatement appends a new revision and a read returns the newest one as of the request; a yields day is written once and never restated. * `fiscalPeriod`: The earnings report's fiscal period, such as Q3. * `fiscalYear`: The earnings report's fiscal year. * `form`: The SEC form filed: 10-K annual report, 10-Q quarterly report, 8-K current report, 20-F and 40-F foreign annual reports, 6-K foreign current report, S-1 registration, DEF 14A proxy statement, /A an amendment. * `fromDay`: First day of the range, inclusive; defaults to today, or 30 days before --to-day. * `fullyDilutedValuation`: price × vendor total supply in denomination units; null if unreported. * `fundingRate`: Fraction per venue settlement interval; hourly on Hyperliquid, not annualized. Positive means long positions pay short positions and negative means shorts pay longs, as the venue publishes it; multiply by position notional for the amount charged at one settlement. * `fundingSettlementCount`: Settlements in cumulativeFundingRate; its mean denominator. * `high`: Highest price inside the bar, in the asset's quote units on a venue market and US dollars otherwise. * `holderCount`: Addresses holding the pool's deposit token. * `holdersRevenue`: US dollars of that day's revenue paid to its token holders. * `holdersRevenue30d`: US dollars paid to the protocol's token holders over the last 30 days. * `holdersRevenue7d`: US dollars paid to the protocol's token holders over the last 7 days. * `holdersYield`: The last twelve months' dividends and buybacks net of issuance over market cap, as a fraction. * `hooks`: Uniswap v4 hook address affecting swap costs or permissions; null if absent. * `id`: Circuit's own catalog id for the asset, the uuid every other command's --asset names it by. * `impermanentLossRisk`: Vendor-assessed divergence from holding constituents; also a filter. * `incentives`: US dollars of token incentives it paid that day. * `includeDelisted`: Keep delisted venue listings and assets whose every listing is delisted; false by default. * `inflow`: Whole tokens entering, both grains; "0" if none, null without decimals. Not trade counts. * `interval`: Bar length: 1m, 5m, 15m, 1h, 4h or 1d. * `kind`: Calendar event kind: unlock (a token's supply release), earnings (an equity's earnings date), filing (an equity's SEC filing), governance (a protocol's proposal vote) or hack (a protocol exploit). * `label`: Vendor opportunity name, e.g. USDC-WETH; not the non-unique deposit ticker. * `lastPrice`: The volume-weighted price over the pool's newest traded minute, quote units per one base unit as a decimal string. It is taken from the newest minute the pool traded rather than from the window, so a quiet window still answers, and it is never an hourly figure; an --as-of read finds it only within the one-minute retention. Null when the pool has no minute row, that minute moved no base token, or either side's decimals is unknown. * `lastTradeMinute`: Opening instant of the newest traded minute, which supplies lastPrice. * `limit`: Numeric integer, 1 to 100000 ranked rows, 1,000 on revenue and asset_fundamentals; required with --sort-by except on markets. * `line`: total for the metric itself, or the name of one line that makes it up (borrow_interest, liquidation_fees). * `linearEndDay`: Last day of a linear unlock's schedule. * `lines`: Also answer the lines each metric's total sums; only the totals by default. * `liquidatable10pct`: US dollars of that collateral whose positions liquidate if the token falls 10% from the day's price. * `liquidatable25pct`: US dollars of that collateral whose positions liquidate if the token falls 25% from the day's price. * `liquidatable5pct`: US dollars of that collateral whose positions liquidate if the token falls 5% from the day's price. * `liquidityChangeInWindow`: Window quote-reserve change (newest/oldest − 1); null with \<2 minutes. * `liquidityUsd`: What the pool holds, in US dollars: twice the quote reserve valued at the quote asset's USD mark, so a pool seeded with its base token alone counts only the quote it can pay out. Null, never zero, without a quote reserve, without the quote token's decimals, or where Circuit holds no mark for the quote asset. * `loanToValue`: Fraction of a deposit's value that can be borrowed against it; null when the deposit is not collateral. * `lookbackMs`: Window length back from --as-of, or from now without it; e.g. 172800000 for 48 hours. A bar is in the window when its close is. Omit it for the newest observation per key, except on pools, where it is the activity window the trade counts, volumes, price change and liquidity change are summed over: 3600000, 86400000 or 604800000, defaulting to 604800000, one row per pool either way. A revenue or asset_fundamentals ranking takes 86400000, 604800000 or 2592000000. * `low`: Lowest price inside the bar, in the asset's quote units on a venue market and US dollars otherwise. * `marginRule`: Margin modes this perpetual accepts: crossOrIsolated takes either, isolatedOnly refuses cross, strictIsolated also keeps isolated margin until the position closes. Null on spot markets and on Derive, whose subaccounts margin cross. The current rule, whatever asOf. * `marketCap`: Vendor price × circulatingSupply, in denomination units; null if unreported, and 0 beside a 0 circulatingSupply is the vendor reporting no supply, never a worthless asset. * `marketDepth`: US dollars of resting orders within 2% of the mid, summed across the exchange's markets that day. * `maximumLeverage`: Highest leverage the venue allows on this market now, whatever asOf; null when it publishes none. * `maxSupply`: Vendor maximum asset units; null if uncapped or unknown. * `measurementConfidence`: Vendor trust (high/medium/low); null for advertised or ungraded rows. * `medianDailyVolumeQuote`: Median of the window's daily volumes, each day being one 1d bar's whole-day base volume valued at that same bar's close. It is not the median of volumeQuote, which values each hour at its own close. * `medianDailyVolumeUsd`: medianDailyVolumeQuote at the current quote USD mark, not daily marks. * `metric`: The statement's figure, as DefiLlama names it in snake case: revenue, gross_profit, earnings, net_income, total_assets. * `minimumNotional`: Smallest order value the venue accepts on this market, in quote units: the size after rounding down to sizeStep times the price it trades at. Hyperliquid exempts a close of the whole position and Lighter applies it only to resting limit orders. Null when the venue sets none. The engine refuses a smaller order with BELOW_MINIMUM before submitting it. Order rules are the current ones, whatever asOf. * `minimumSize`: Smallest order size the venue accepts on this market, in base units; Lighter applies it only to orders that rest. Null when the venue sets none. The engine refuses a smaller order with BELOW_MINIMUM before submitting it. * `minLiquidityUsd`: Answer only pools whose liquidityUsd is at least this many US dollars; a pool with none is left out rather than kept, and a read where no candidate pool's quote asset carries a mark fails naming the network and the quote asset, the way ranking on liquidityUsd does. * `minQuoteReserve`: Minimum quoteReserve in whole tokens; requires one --quote-token. * `name`: The catalog's name for the asset on an assets row, the vendor's own name for the category on a categories row. An asset the catalog minted from a venue listing, or from a source that published no longer name, carries its ticker here, so name and symbol read the same on it. * `network`: Network id: ethereum:\ for every EVM chain (ethereum:1 is Ethereum, ethereum:8453 is Base), solana, or hypercore; prices also takes the venue networks an allocation holding names (lighter, lighter-robinhood, derive, papertrade, kraken, qfex). * `newUsers`: Addresses that used the protocol or chain that day for the first time. * `observedDayCount`: Contributing days, or markets 1d bars; divide window sums by this for means. * `offPeg`: true answers only pools holding a stablecoin off its peg, false only pools whose stablecoins hold it. * `offPegToken`: The stablecoin in the pool trading off its peg, by symbol; null when every stablecoin in it holds its peg. * `open`: The bar's first price; the previous bar's close when nothing traded inside it. * `openInterest`: US dollars of open positions on its derivatives at the day's end. * `openInterestBase`: Open contracts on the market counted in base-asset units, never quote or USD; null where the venue published no figure, which on a markets row is every spot market. * `openInterestQuote`: openInterestBase valued at the row's own price, in quote-asset units; null when either of them is null. * `openInterestUsd`: openInterestQuote restated in USD at the quote asset's mark, never a mark of the base asset; null when Circuit holds no such mark. * `opensAt`: The instant the bar opens; it closes one --interval later, and a 1d bar is a UTC day. * `optionsNotionalVolume`: Notional US dollars of options traded that day. * `optionsVolume`: Premium in US dollars of options traded that day. * `order`: desc (default) or asc; nulls last either way. Requires --sort-by. * `outflow`: Whole tokens leaving, both grains; "0" if none, null without decimals. Not trade counts. * `parent`: A sub-protocol's parent protocol, or the token an ETF holds. * `pegDeviation`: How far offPegToken trades from its peg, as a fraction: 0.02 = 2%. * `period`: The period the statement covers: month, quarter or year. * `periodEnd`: The last day of the period. * `perpAggregatorVolume`: US dollars of perpetuals routed through its aggregators that day. * `perpVolume`: US dollars of perpetuals traded that day. * `platform`: Where a governance proposal is voted: snapshot (offchain) or tally (onchain). * `pool`: The reporting vendor's own id for one opportunity, and the identity a yields row is keyed on beside its vendor. * `pool2Tvl`: US dollars in liquidity pools of its own token. * `price`: On a market row, the venue's mid in quote units per one base unit. On a vendor row, the vendor's reported price of one unit in the row's denomination (on a metrics row, US dollars), however the vendor derives it; a display and accounting figure, never an executable quote. Never Circuit's display mark price. * `priceChangeInWindow`: Window price change (newest/oldest − 1); null with \<2 traded minutes. * `priceTick`: Finest price step the venue accepts on this market; the engine rounds limit and trigger prices to it, and Hyperliquid also keeps at most 5 significant figures. * `priceToBook`: Market cap over shareholders' equity. * `priceToFees`: The token's fully diluted valuation over the protocol's annualized fees. * `priceToRevenue`: A stock's market cap over its last twelve months' revenue, or a protocol token's fully diluted valuation over its annualized revenue. * `priceUsd`: On a markets row, the mid restated in USD through the quote asset's mark, never a mark of the base asset, and null when Circuit holds no such mark. * `protocol`: Deposit protocol, distinguishing wrappers of one token; filter matches exactly. * `protocolCount`: Protocols the chain or category counts that day. * `quoteAsset`: Pricing-leg asset ID; for perps, the dex collateral token. * `quoteReserve`: Latest retained quote reserve in whole tokens; null without quote leg, reserve or decimals. * `quoteRole`: native or dollar (including bridged USDC); null when quoteToken is. * `quoteSymbol`: Ticker of the leg the row prices in: the catalog ticker of quoteAsset on a markets row and on an assets venue listing, and on a pools row the constituent's own symbol for the quote leg, null when the pool has no quote leg. * `quoteToken`: Network/address reference of the pool's quote leg, in the form a swap can spend: a wrapped-native constituent is reported as the native address, because a swap from wrapped native needs a wrapped balance the wallet may not hold, and the pool's own constituent is still listed under constituents. Null when the pool holds no leg among the chain's quote tokens, or does not hold exactly two tokens. As a filter, pass that reference object to select pools quoting in it. * `recipient`: Who the unlocked tokens go to, as DefiLlama names the allocation (team, investors, treasury). * `reportDay`: The last day of the period the filing reports on; null when the filing reports no period. * `reserve`: Whole tokens of this token the pool held at its newest observation carrying a reserve, never a window figure, which an --as-of read finds only within the one-minute retention; null until the token has been observed in the pool's reserves or without its decimals. A Uniswap v3 reserve is the pool contract's balance; a v4 reserve is the principal on the pool's liquidity curve, excluding uncollected fees and anything a hook holds outside it. * `returnedUsd`: US dollars returned after the hack; null when none or unknown. * `revenue`: US dollars of that day's fees the protocol kept. * `revenue30d`: US dollars the protocol kept over the last 30 days. * `revenue7d`: US dollars the protocol kept over the last 7 days. * `search`: Case-insensitive substring of an asset's symbol or name, or of a category's key or name, ignoring emoji and punctuation at word edges; two characters or more, and it narrows rather than ranks. An EVM contract address or Solana mint finds the asset holding that contract. * `sellCount`: Window trades putting base in; zero without a base leg or activity. * `session`: When on the day the company reports: before_market_open, during_market_hours or after_market_close; null when unannounced. * `settlesAt`: Funding charge instant: upcoming hour-end if predicted, past if settled. * `singleAssetExposure`: Vendor-assessed exposure to one token rather than a basket; also a filter. * `sizeStep`: Step an order's size is a multiple of on this market; the engine rounds sizes down to it, so check minimumNotional against the rounded size. * `sortBy`: Rank instead of list: aggregate this row field over the window for every key in scope and answer one row per key, ordered descending with nulls last, with observedDayCount as the mean's denominator. On pools and markets it orders the rows on the field, NULLS LAST, and a pools ranking also needs --limit and one of --created-within-ms, --pool, --token or --asset to scope it; a descending pools ranking on a window field (tradeCount, volumeUsd, volumeQuote, priceChangeInWindow) answers only pools whose tradeCount in the window is above zero. A flow such as volume or revenue is summed over the window; a stock figure such as market cap or supply takes its newest day in the window. * `spotVolume`: US dollars of spot trading on the exchange that day. * `stablecoinOnly`: Vendor assessment that all exposed tokens are stablecoins; also a filter. * `stablecoinSupply`: Tokens of the stablecoin circulating that day, summed across chains without double counting. * `stakingTvl`: US dollars of the protocol's own token staked in it. * `statement`: Which statement the row belongs to: income, balance_sheet or cash_flow. * `status`: A governance proposal's state: active, succeeded, queued, pendingexecution, executed, crosschainexecuted, extended, defeated, canceled or closed. * `subject`: DefiLlama's key for the event's or figure's subject: coingecko:\ or chain:address for a token, a ticker for an equity, a protocol, chain or category slug, or all for the whole market. * `subjectKind`: What a metrics row describes: protocol, protocol_trailing, chain_trailing and category_trailing (trailing totals and changes, today's), sub_protocol (one product of a protocol), chain, category, total (the whole market), stablecoin, etf, bridge, exchange, equity or liquidation (a token's lending collateral); on a statements row, protocol, token or equity. * `symbol`: The subject's ticker: the catalog's own ticker for the asset on an assets row and on a ranked revenue or asset_fundamentals row, and inside constituents the symbol the pool's constituent record spells for that token, null where the source published none. * `technique`: How the hack worked, as DefiLlama classifies it (private-key-compromised, oracle-manipulation). * `tickSpacing`: Allowed liquidity-bound spacing in ticks; null without concentrated liquidity. * `timestamp`: The instant the observation stands at: the refresh that read the venue on an open_interest row. * `toDay`: Day after the range ends, exclusive; defaults to 30 days after --from-day, and the range spans at most 366 days. * `token`: Pool constituent filter as a \{network, address} object; asset takes catalog IDs and network:address. * `tokenId`: Multi-token id (ERC-1155) beside a contract asset; omit it for fungible tokens. * `topHoldersShare`: Fraction of the pool's deposits the ten largest holders own: 0.6 = 60%. * `totalBorrowedUsd`: US dollars currently borrowed from the pool; null when the pool lends nothing. * `totalSupply`: Vendor minted units, including noncirculating; null if unreported. * `totalValueLockedUsd`: Vendor USD valuation, not derived from Circuit marks; null if unreported. * `tradeCount`: Trades the row counts: on a pools row the base leg's trades over the window, buyCount plus sellCount, zero where the pool has no base leg or did not trade. * `trailingPe`: Price over the last twelve months' earnings per share; null when earnings are not positive. * `transactions`: Transactions sent to the protocol or on the chain that day. * `treasuryTvl`: US dollars in its treasury. * `tvl`: US dollars deposited that day, DefiLlama's default TVL without staking, borrowed or pool2 balances. * `tvlChange30d`: TVL's change over the last 30 days, as a fraction: 0.12 = up 12%. * `tvlChange7d`: TVL's change over the last 7 days, as a fraction: 0.12 = up 12%. * `underlyingAsset`: Underlying asset ID; null if standalone. Filter lists assets deriving from it. * `underlyingAssetType`: Kind of the asset a perpetual tracks; null when no underlying is confirmed. * `unlockType`: cliff releases amount at once; linear-start begins releasing weeklyRate per week; linear-rate-change changes that rate. * `users`: Addresses that used the protocol or chain that day; a protocol's figure sums its products, so an address using two counts twice. * `value`: The figure for the period: US dollars, except per-share metrics (eps_basic, eps_diluted) and share counts. * `vendor`: The third party that reports on the asset; as a flag on asset_fundamentals it narrows to that vendor's rows. coingecko-rwa rows carry the aggregate of the tokenized instruments tracking the underlier, never the underlier's own market: price is the instruments' price, marketCap their combined tokenized float, volume their combined trading. * `vendorIdentifiers`: Every vendor key the asset is known by, and the keys asset_fundamentals reports it under. One entry per vendor and vendor key, never one per vendor, so a vendor that prices the asset under two ids contributes two entries and reading only the first drops half the asset's series. * `vendorKey`: Vendor asset ID from assets.vendorIdentifiers. * `venue`: Where the market trades, as listed under an assets row's "venueIdentifiers". * `venueIdentifiers`: Every live venue market this asset is the base of, one entry per venue, dex and venue symbol, carrying that listing's quote asset, leverage and size precision; a delisted listing appears only under --include-delisted and carries its delistedAt. * `venueSymbol`: Venue market symbol as markets returns it; a base or base/quote pair such as NVDA, HYPE/USDC or BTC/USD names the one market it matches, and fails naming the listed symbols when several match. * `vestingTvl`: US dollars of its token still vesting. * `volume`: On a prices bar, whole base tokens the venue traded inside the bar, 0 when nothing traded, and null when the price is not a venue's. Elsewhere, volume traded across every exchange the vendor aggregates, in the row's denomination: one day of it on a day row, the window sum on a ranked row; null on an asset row when the vendor reports none. * `volumeBase`: Whole base tokens traded: on pools what entered and left over the window, "0" without activity and null without decimals. * `volumeQuote`: Whole quote tokens traded: on markets the last 24 complete hourly bars, each valued at its close, null without bars; on pools what entered and left over the window, "0" without activity and null without decimals. Two quote tokens do not compare, so ranking pools on it takes one --quote-token; volumeUsd is the comparable figure. * `volumeUsd`: The row's traded volume in US dollars: volumeQuote at the quote asset's mark on a markets row, and on a pools row the window's quote-token volume valued at a dollar per dollar-role token or at the network's native mark; null, never zero, wherever that mark or the quote leg is missing. * `weeklyRate`: Tokens a linear unlock releases per week from its day; null for cliffs. * `withdrawableUsd`: US dollars a simulated withdrawal could take out; null for advertised rows. * `withdrawalEtaMs`: Queued exit wait (ms); null for advertised rows or unreported wait. * `withdrawalOutcome`: What the vendor's daily simulated withdrawal achieved, in its own words rather than a word of ours: ok_full for the whole position with no wait, ok_partial when only part could leave, delayed when it exited through a queue, no_exit_primary when the position has no primary exit route, reverted_liquidity, reverted_paused and reverted_unknown when the exit call failed for want of liquidity, because the protocol was blocking withdrawals, or for a reason the vendor did not name, and error_rpc when the measurement itself failed. Only a measured row carries one, and every measured row does. * `withdrawalSlippagePercent`: Signed percentage-point exit loss vs NAV; null for advertised rows. * `yieldKind`: advertised: vendor projection; measured: simulated return net of exit friction. # Derive trading agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/derive Circuit SDK reference for Derive agents: perp, option and spot orders, risk universes, deposits, withdrawals and vault requests. Derive settles on Ethereum. A Derive account is the wallet's set of subaccounts, one per risk universe: `PRIME` trades BTC and ETH, `MIDCAP` HYPE, `ALT` the other altcoins and `RWA` XAUT. Collateral is named `UNIVERSE.ASSET` on network `derive`, such as `PRIME.USDC` or `ALT.SOL`, and margins only the universe that holds it. Every order and fund move acts from the wallet's oldest subaccount in its universe; holdings count every subaccount. `agent.derive.orders.create` takes the [order shape every venue shares](./hyperliquid), `perpOpen` (Derive margins each subaccount as a portfolio), `perpReduce`, `spotBuy` and `spotSell`, plus `optionBuy` and `optionSell`. A perp `asset` is the base currency, such as `ETH` for `ETH-PERP`; a spot `asset` is the pair, such as `WSTETH-USDC`; an option `asset` is the instrument, such as `ETH-20261225-4000-C`, with `amount: { size }` in contracts and an optional limit price that is the premium per contract in USDC. List perps and spot pairs with [`data.markets({ venue: "derive" })`](./data). `derive.options.list({ currency })` lists the live option chain for an underlying such as `ETH`, each with expiry, strike, call or put and its `minimumSize`, `sizeStep` and `priceTick`; add `expiry: "YYYY-MM-DD"` to quote one expiry's mark, book, implied volatility and greeks. Derive groups no orders, so `perpOpen` takes no `takeProfit` or `stopLoss`: place a `takeProfit` or `stopLoss` order separately. Preparation rounds sizes down to the instrument's `sizeStep` and prices to its `priceTick`, refuses sizes below its `minimumSize` with `BELOW_MINIMUM`, the values `data.markets` and `derive.options.list` rows carry, and signs a fee cap of three times the taker fee. Results follow the [Hyperliquid order results](./hyperliquid), with `orderId` the order's signed action nonce. `agent.orders.listOpen({ venue: "derive" })` returns the session's resting orders and `derive.orders.cancel({ orderId })` cancels one; `"all"` cancels every resting order on the account, which only a Paper trading session (its account is its own) or an owner review may do. A [swap](./swap) into Derive collateral deposits it: the collateral's Ethereum token goes straight to Derive's ActionManager, and any other source routes in one operation to the wallet's Derive deposit address on Ethereum, which Derive sweeps into the subaccount a minute or two later, with no Ethereum gas needed; the first deposit into a universe creates its subaccount. Derive credits only deposits worth at least its minimum, about $5, and Circuit refuses smaller ones because Derive keeps them. A swap between two universes' collateral, such as `PRIME.USDC` to `ALT.USDC`, moves it between subaccounts, and a swap to the Ethereum token withdraws it. A [send](./transfers) of Derive collateral moves it to another wallet's subaccount in the same universe, and pays Derive's subaccount fee, about $1 in the sent asset, when the recipient has no subaccount there yet. Before the first order, Circuit registers a read-only session key derived from the wallet's signature, through a reviewed `setup` with `venue: "derive"`; it can never trade, transfer or withdraw. `derive.vaults.list()` lists Derive's vaults with their deposit asset, NAV and share price, and `derive.vaults.request({ kind: "deposit", vault, amount })`, `{ kind: "withdraw", vault, shares }` and `{ kind: "cancel", vault }` queue a vault request that the vault's curator settles later; settled shares appear in holdings at the vault's share price. Perp holdings use `kind: "perp"` with the same fields as Hyperliquid, margined in the universe's USDC; option and spot holdings follow the wallet's indexed Derive balances. # Error Handling Source: https://docs.circuit.org/agent-developers/sdk-reference/error-handling Handle Circuit SDK errors: ApiError fields, request IDs, and how to tell failed submissions from failed settlement across runs. Await SDK writes directly and let required failures end the run; no pending-trade flag or generic recovery wrapper is required. SDK methods return data or throw `ApiError` with its HTTP status, code, cause and receipts, plus `requestId` whenever a request was sent. Arguments rejected before sending throw `code: "BAD_REQUEST"` with a message naming the method and no `requestId`, so treat `requestId` as optional and branch on `code`. Every failure propagates, and missing live data never becomes a default. Missing memory returns null. Money submissions throw `MoneyActionError`, an `ApiError` whose `outcome.status` says whether anything can still happen: `rejected` means the request was refused before an operation existed; `error` carries the finished `operation`, whose effects `agent.allocation` already includes; `unresolved` carries the `operationId` of an operation that is pending, whose response was lost, or whose settlement Circuit is still proving (status `unproven`, `error.code` `OPERATION_UNPROVEN`, `operation` attached). After `rejected` or `error`, decide again from the current allocation; after `unresolved`, do not act on that intent again until the operation leaves `operations.pending()`. `completedOperations` retains successful prerequisites. `error.moneyFailure` is `{ stage: "preparation", operationId: null }` for `rejected`, where nothing exists to follow, and otherwise `{ stage: "execution", operationId }`: follow `outcome.status` and never resubmit within the run. A money create, cancel or redeem method's optional second argument `{ once, per? }` names the decision it carries out, such as `{ once: "buy", per: "week" }`; `per` (`hour`, `day` or `week`, UTC periods Circuit's clock decides) scopes the name to the current period. Circuit holds at most one successful operation per name in a session: a later write with a succeeded name, in any run, returns that operation without preparing again; while an operation holding the name is pending, the write throws `MoneyActionError` with outcome `unresolved` and that `operationId`; a failed operation frees the name, so the next write decides again. When the write needs an approval or funding step first, the name is held from that first step and a later write answers with the chain's latest operation; if the requested operation fails, the name is freed. `operations.retrieve({ operationId })` is the authority on an operation: `pending` means observe, `success` retains its recorded `result`, and `error` retains failure evidence. `operations.cancel({ operationId })` withdraws one of the session's pending operations while nothing irreversible has happened. An operation still waiting to start ends at once; a submitted one ends when its venue confirms the withdrawal, as Papertrade does for an intent still in its queue. It returns the operation: `error` with code `CANCELED`, or the outcome it reached first. It throws when the operation is already broadcast on chain or its venue is already executing it; that operation settles on its own. The write still awaiting a canceled operation throws `MoneyActionError` with code `CANCELED`; find the ID to cancel in `operations.pending()`. `operations.pending()` returns every one of the current session's pending operations, including those still settling past their settlement bound (`unproven`) and admissions whose response was lost; `operations.list()` pages through all outcomes. Each row is the same operation resource returned by `retrieve`, plus `sessionId` and `walletId`. Unreadable details appear in `readError`; recorded facts and neighboring entries remain available. Unavailable settlement evidence and missing admission timestamps stay null. Historical `kind` and `status` are strings; `request`, `error` and `result` are unknown recorded data, while `action` is the admitted money action from `request`, or null when it no longer parses. Receipt networks and reference kinds are recorded strings, including retired values. Narrow fields before using them; never replay a historical action. Fresh money method results remain typed by action kind. Follow `list`'s `nextCursor` or use `for await` to cover every page. Timestamps are UTC ISO-8601 instants with six fractional digits (`2026-10-24T20:00:00.123456Z`); receipts distinguish submission from observed settlement. Logs and memory references cannot override these resources. `VENUE_PAUSED` means the venue refused the action because it is paused, such as Papertrade before it opens intake; nothing changed. `OPEN_INTEREST_CAP` means the venue refused an open because that side of the market is at its open-interest cap, such as Papertrade when longs are crowded; nothing changed. These two are the errors worth catching: check `error.code`, log that the venue refused and return, and the next trigger tries again. Uncaught, they fail the run. `BELOW_MINIMUM` means the action is below a rule the code can read before sizing: a market's `minimumNotional` or `minimumSize` (`data.markets`, `exchanges.markets.list`, `derive.options.list`, `polymarket.markets.retrieve`), Papertrade's `minimumStake`, `MINIMUM_SWAP_USD`, or a swap whose route fees exceed its amount; the message names the rule and nothing changed; size the action at or above it. `ACCOUNT_SETUP_REQUIRED` and `ACCOUNT_FUNDING_REQUIRED` carry the exact requirement in `error.details.detail.requirement`. [Account readiness](../getting-started/circuit-toml-reference#account-readiness) says who completes setup; `ACCOUNT_FUNDING_REQUIRED` means the venue account does not exist or has no deposit yet, and its first deposit opens it. Failed state reads remain errors rather than setup instructions. `LIFECYCLE_TIMEOUT` means the deadline passed before Circuit submitted anything; nothing changed, and the outcome is final. When a provider read was still unanswered at that deadline, the code is `PROVIDER_UNAVAILABLE` and the message names the provider's host; nothing changed either. `CAPACITY_EXHAUSTED` means Circuit's own share of a provider's limit stayed in use for the whole deadline; nothing was sent, and the message names the provider. `TOO_MANY_REQUESTS` from a quote (`swaps.quote`, `transfers.quote`, `polymarket.orders.quote`) means the session used its 60 live quotes a minute; the message says when the next one is available. An `unproven` operation passed its settlement bound without evidence; Circuit keeps observing it, later evidence settles it as `success` or `error`, the SDK reports it as `unresolved` with code `OPERATION_UNPROVEN`, and it stays in `operations.pending()` until then ([execution model](../concepts/execution-model#execution-limits-and-failures)). A hosted run that ends on an uncaught error is your agent's failure, recorded as `AGENT_FAILED` with the error's message, because your code controls everything its sandbox reports. Circuit owns a run's failure only when Circuit saw it fail on its side: a lost runtime host, or an uncaught SDK error carrying a failure Circuit or a provider owns, which Circuit signed when it answered your run. `circuit run` reports the first known code in the error's cause chain. # Coinbase, OKX, Binance and Bybit agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/exchanges Trade spot pairs on a connected Coinbase, OKX, Binance or Bybit account. `agent.coinbase`, `agent.okx`, `agent.binance` and `agent.bybit` share one shape and trade spot only, from the exchange account the session was started with. They exclude margin, derivatives, trigger orders and withdrawals. Orders and order reads require a hosted target or a Paper trading session; local `circuit run` rejects them. `agent.exchanges.markets.list({ exchange, base?, quote? })` returns that exchange's spot pairs with `tradable` and order rules (`minimumSize`, `minimumNotional`, `sizeStep`, `priceTick`); `agent.exchanges.markets.list({ exchange: "binance", base: "BTC", quote: "USDT" })` finds one pair. A pair's `asset` is `:/` in the exchange's own asset codes, such as `BINANCE:BTC/USDT` or `COINBASE:ETH/USD`; pass it unchanged. `orders.create(order, options?)` takes the [order shape every venue shares](./hyperliquid): `{ kind: "spotBuy" | "spotSell", asset, amount, execution? }`, with `amount` `{ size }` in the base asset or `{ value }` in the quote asset, rounded down to the pair's `sizeStep`. Circuit refuses an order below the pair's `minimumSize` or `minimumNotional` with `BELOW_MINIMUM` before anything is sent. Omit `execution` for a market order within 1% of the mid; `{ kind: "limit", price, timeInForce }` rests per timeInForce ("gtc" rests, "ioc" fills what crosses now, "alo" is post-only). Its result is the venue order every venue returns. `agent.orders.listOpen({ venue: exchange })` returns the session's resting orders, and `orders.cancel({ orderId, asset }, options?)` cancels one the session placed. options take a [`once` name](./error-handling). Circuit signs each order once and submits it once. An order the exchange never reports by the end of its signed request's validity window settles as not executed. Size from the allocation balance; fills record net amounts and fee currencies. ## Connect a credential `circuit exchange connect --venue coinbase|okx|binance|bybit --credentials-prompt` connects an account (OKX also asks for its passphrase); without a key it prints where to create one and, for Binance, OKX and Bybit, Circuit's IP addresses for the key's allowlist. `circuit exchange remove ` removes one. Circuit reads the key's permissions from the exchange: a key that can trade spot gets trade access, any other key read access. | Exchange | Trade permission | | - | - | | Coinbase | Secret API key with the Ed25519 signature algorithm, View and Trade | | OKX | Read and Trade | | Binance | Enable Reading and Enable Spot & Margin Trading | | Bybit | Read-Write with Spot Trade | Declare the venue under [`exchangeCredentials`](../getting-started/circuit-toml-reference#exchangecredentials-section), then pass the account ID from `circuit exchange list` as `--exchange-credential ` with a hosted target. # Holdings Source: https://docs.circuit.org/agent-developers/sdk-reference/holdings Read the session allocation and attributed holdings used to size agent work. `agent.allocation` is the session's allocation and attribution snapshot, read when the invocation starts, refreshed before each money write resolves and as the [execution model](../concepts/execution-model#continuous-agents) describes; it is not shared-wallet holdings or a signing boundary. If a refresh fails, reading it throws that failure. Construction fails if Circuit cannot build it. `holdings` is a closed union narrowed on `kind`. Every row, whatever its kind, carries `network`, `asset`, `tokenId`, `symbol`, signed decimal `quantity` (negative for a short or a borrowed position), `priceUsd`, `entryPriceUsd`, `valueUsd`, `unrealizedPnlUsd` and `pricedAt`, which is set whenever `priceUsd` is. `quantity` is whole tokens, the unit swap and transfer amounts take. `token` is fungible inventory, including tokens Circuit prices as a rate × another asset (ERC-4626 vault shares, stETH, stake-pool tokens, Kamino reserve tokens, Pendle PTs), `supplied` and `borrowed` are lending and liquidity positions, `perp` is perpetual exposure on a perp venue, and `prediction` is a Polymarket outcome-token position; each adds its own fields at the top level of the row. A `token` row adds `availableQuantity`, what a new order can spend: `quantity` less the margin the session's open perps hold in that collateral and their unrealized losses, never below 0. `supplied` (value supplied to a lending or liquidity protocol, including collateral posted to secure loans) and `borrowed` (debt owed to a lending protocol) add `protocol` (Circuit's id for the protocol, such as `aave` or `morpho`, or null for a position Circuit knows no protocol for), `market` (the market [`agent.lending`](./lending) names: the Aave or Spark pool, the Aave V4 `/`, the Euler vault, the Morpho market id or the Kamino lending market; a liquidity position names its pool (the pool contract on Uniswap v3 and Aero, the poolId on Uniswap v4)), `underlying`, `underlyingQuantity` and `apy`. A liquidity position is several `supplied` rows sharing its `position`, the value [`agent.liquidity`](./liquidity) takes to add or remove (null on every other `supplied` row); select it by `position`, never by parsing `asset`, and its `apy` is null. Its rows also share `range`, `{ lowerPercent, upperPercent, inRange }`: the position's live span as percent offsets from the pool's current price, the coordinate `open` takes, and whether that price is inside it; `range` is null on every other `supplied` row and when the read failed, which `errors` names. A Metric position, on the networks whose `protocolDeployments` list `metric`, is `/` with two rows with `protocol` `metric` per held bin, one per pool token, whose `asset` is `:claim:metric:///:supply`: `quantity` is the position's shares in that bin at 18 decimals, and `underlyingQuantity` that token's part of the bin's balance, fees included. A Uniswap v3 or v4 position is its position manager NFT id with four rows with `protocol` `uniswap-v3` or `uniswap-v4`, principal and uncollected trading fees per pool token, whose `asset` is `:claim::/<0|1>/:supply`: each `quantity` is the session's share of the NFT's liquidity at zero decimals, moved only by the session's own receipts, and `underlyingQuantity` that currency's live principal or fees for it. An Aero Slipstream position (`protocol` `aero-slipstream`) has the same four rows, which stay the wallet's while its pool's gauge stakes the NFT; the AERO it earns staked is a [reward](./rewards), not a holding. `quantity` is in the position's native unit (the token's balance, which grows with interest for a lending supply or debt, or the protocol's shares or collateral units for a position without a token) and `priceUsd` is per native unit, so `valueUsd` is `quantity` times `priceUsd` as for every kind. A `supplied` row also carries `securesLoans`, true when the protocol counts it as collateral for loans in its lending account; posted collateral earns nothing, so its `apy` is 0. A `borrowed` row's `quantity` and `valueUsd` are negative. `underlyingQuantity` is `quantity` in whole units of `underlying`: the same number for a token whose balance grows with interest, else `quantity` at Circuit's latest share rate; `apy` is the current annual rate as a fraction (`0.05` is 5%). A position without a token has the Circuit position key ending in `:collateral`, `:supply` or `:borrow` as its `asset`; a token position's `asset` is its contract. A `borrowed` row also carries `loanToValue` (the wallet's whole lending account, the market, pool or obligation the protocol liquidates together, including other sessions' and manual positions there: its loans over the collateral securing them, both at Circuit's marks, which can differ slightly from the protocol's oracle), `liquidationLoanToValue` (the securing collateral's liquidation thresholds averaged by collateral value) and `healthFactor` (their quotient; liquidatable below 1); both are null when the protocol publishes no liquidation threshold Circuit reads. A `supplied` or `borrowed` row's `quantity`, its USD fields and `underlyingQuantity` are null when Circuit holds no current share rate for the position, and its `errors` says why; it is empty otherwise. Read these facts here rather than from chain reads. `asset` is the string that network's operations take: a contract address or mint for transfers and swaps; on `hypercore` a `token` holding's `asset` is the token index (`0` is Core USDC) while an order's `asset` comes from `agent.data` (`BTC`, `xyz:GOLD`) or `spotMarkets.list()` (`@107`); `KRAKEN:XBT` matches a Kraken catalog `base` or `quote`; a `perp` or `prediction` holding's `asset` goes into orders and triggers. `tokenId` is null unless the holding is an ERC-1155 id. Holdings use operation asset identities. `entryPriceUsd` is this session's own average entry, `priceUsd` the current price of one whole unit, and `unrealizedPnlUsd` the difference across `quantity`. Each is null when Circuit holds no such price; null means unknown, never zero. `valueUsd` is `quantity` times `priceUsd`, which for a `perp` is signed notional exposure rather than collateral. These four USD fields and the ratio fields carry at most 18 decimal places, truncated toward zero, while `quantity` stays exact at its asset's own decimals, which can exceed 18. Polymarket enrichment can be null when venue metadata reads fail. Exact share quantities remain present, and `errors` explains missing facts. Treat unknown redeemability or price as unknown; execution rechecks its own prerequisites. A `prediction` holding's `acceptingOrders` is false once Polymarket stops taking orders on its market, including while resolution is pending: skip quoting or selling it and redeem it once `isRedeemable`, which follows the payout Circuit has recorded and turns true about a minute after the market resolves on chain. Each session is its own virtual wallet: holdings change only through its allocations, its own fills and fees, realized P\&L against its own entry, funding on its own perpetuals and interest on its own balances. Deposits, withdrawals, manual trades and other sessions never move them, so a holding can go negative or oppose the account's live position. A Hyperliquid account liquidation shrinks the sessions holding the liquidated side in proportion to their holdings, and a [Papertrade](./papertrade) position closed outside its session counts as the opening session's own. Close a session position with a plain opposite order, and a Papertrade position by its holding's `positionId`. Allocation guides honest but fallible agents and attributes effects; the transaction SDK adds no allocation enforcement. Multiple sessions of different agents share wallet signing authority and funds, and Hyperliquid liquidation risk, since positions net at the account; the same agent cannot have two active sessions on one wallet. Size typed SDK and raw-wallet actions from the session allocation. Ask Circuit and reviewed operations can use the full selected wallet or venue account, overriding attribution. Every surface shares the signer and transaction lifecycle and enforces its request, permit, policy and live checks. # Hyperliquid trading agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/hyperliquid Circuit SDK reference for Hyperliquid trading agents: perp and spot orders, limit, post-only and trigger orders, sizing, positions, funding and HIP-3 markets. `agent.hyperliquid.orders.create(order, options?)` takes the order shape every venue shares, the one Ask Circuit reviews use: `{ kind: "perpOpen", asset, side: "long" | "short", amount }`, `{ kind: "perpReduce", asset, expectedSide?, amount }`, `{ kind: "spotBuy", asset, amount }` or `{ kind: "spotSell", asset, amount }`, each with optional `execution` and `message`. `asset` names the market as its allocation holding does. `amount` is `{ size }` in base units or `{ value }`, the order's notional in the market's quote asset, never margin; `perpReduce` and `spotSell` sizes and `spotBuy` values may be `"max"`. `perpOpen` takes an optional `margin`, `{ mode: "cross" | "isolated", leverage? }`: before the order, Circuit sets the market to that mode at that leverage, or at its `maximumLeverage` when `leverage` is omitted, as its own operation that the order's preparation returns first. Cross is refused where `marginRule` is not `crossOrIsolated`, a leverage above `maximumLeverage` is refused, and a market holding an open position keeps its margin mode until the position closes. Without `margin`, the order trades at the account's current setting (cross at 20x, or `maximumLeverage` if lower, on an untouched market); only when the order would not fit there does Circuit first raise a cross market to its `maximumLeverage`. A market set to isolated, or one whose `marginRule` allows only isolated, is never changed without `margin`. Omit `execution` for a market order within 1% of the mid, or pass `{ kind: "market", slippage }`, `{ kind: "limit", price, timeInForce: "ioc" | "gtc" | "alo" }`, or on `perpOpen` and `perpReduce` `{ kind: "takeProfit" | "stopLoss", triggerPrice }` or `{ kind: "takeProfitLimit" | "stopLossLimit", triggerPrice, price }`. `"ioc"` fills what crosses now and cancels the rest, `"gtc"` rests until filled or canceled and `"alo"` rests as maker only. A `perpReduce` pinning `expectedSide` fails against an opposite live position; omit it to reduce either side. `perpReduce` and `"max"` measure the session's own holding, never the account: a reduce is a plain opposite order capped at the session's position, and only trigger orders on `perpReduce` are reduce-only. The engine reads the mid and sizes the order; the optional second argument takes a [`once` name](./error-handling). Results are the venue order every venue returns: `orderId` (here the client order ID Circuit assigns before sending, which `cancel` takes), `asset`, `side`, `size`, `type`, `triggerPrice`, `reduceOnly`, `limitPrice`, `filled`, `averageFillPrice` and `state` (`open`, `filled` or `canceled`); `operations.retrieve` and `operations.list` report their current values. `limitPrice` is the worst price the order accepts; `averageFillPrice` is the size-weighted average price of the fills Circuit recorded for the order, before fees, to 18 decimals truncated toward zero, never rounded to a price tick; it is null when nothing filled or the recorded fills do not yet account for `filled`, and its SDK type is optional, so treat a missing value as null. Paper trading and Real money accounts derive it from the same recorded fills. Circuit keeps observing a resting order, attributes later fills to the placing operation and session, and updates `filled` and `averageFillPrice` together. Orders never automatically resubmit. A market or limit `perpOpen` may carry `takeProfit` and `stopLoss`, each `{ triggerPrice, price? }`; the same fields work on Hyperliquid and Lighter. Circuit sends the entry and its exits as one venue order. Each exit is a reduce-only take profit or stop loss for the entry's size: at market within 10% of the mark, or a limit at `price` when given. A long's take profit must trigger above the entry price (the limit price, or the mid for a market entry) and its stop loss below; a short's the reverse. Exits are open orders from placement, listed by `agent.orders.listOpen({ venue: "hyperliquid" })` with `reduceOnly: true` `entryOperationId` set to the entry's operation and `entryOrderId` set to the entry's order id while that entry still rests, and each can be canceled on its own. A market entry's exits take its fill; a resting entry's exits activate only once it fills completely. Canceling a partly filled entry cancels its exits and leaves the filled part unprotected, so manage an unfilled entry by reading it, canceling it, and placing a new entry with new exits. When one exit fills, the venue cancels the other. One venue exception: if Hyperliquid cancels a partly filled resting entry for insufficient margin, it places the exits at the entry's full size. Trigger orders wait until the mark price crosses `triggerPrice`. Take-profit and stop-loss orders then execute at market, and the venue accepts fills within 10% of the mark; take-profit-limit and stop-loss-limit orders then rest as a limit order at `price`. Direction follows the order's side: a sell's take profit sits above the mark and its stop loss below, a buy's the reverse, so a buy stop loss on `perpOpen` enters a breakout. Preparation rejects a trigger that would fire immediately. Results and `agent.orders.listOpen` rows carry `type` and `triggerPrice`, which is null for limit orders; the order stays `open` until it fills or is canceled. Engine preparation rounds prices to the precision the venue allows: buys round down, sells round up, tightening the requested limit. Sizes round down to the market's `sizeStep`; a size that rounds to zero fails preparation. Preparation rejects a limit order whose rounded value is below the market's `minimumNotional` in quote units with `BELOW_MINIMUM`, before anything is sent, valuing a buy at the lower of its limit and the best ask and a sell at the higher of its limit and the best bid, where it would trade. Closes and reduce-only orders get no exemption, matching Hyperliquid, except an order that closes the whole perp position, which Circuit sends reduce-only, or sells the whole spot balance rounded to the market's `sizeStep`; Hyperliquid accepts those at any value. Take-profit and stop-loss orders keep the venue's own rule. Perps use catalog coins such as `BTC` or DEX-prefixed symbols. Spot uses catalog coins such as `@107` or `PURR/USDC`; buys spend quote tokens, sells spend base tokens. Outcome markets (HIP-4) trade through `spotBuy` and `spotSell` with the `#` coin from `hyperliquid.outcomes.list()`, whose rows name each `outcome`, its `side` (0 or 1), `sideName`, `name`, `description`, `question` and current `mid`; shares buy and sell in whole units for USDC, settle to between 0 and 1 USDC each, and carry no Circuit-side minimum order value. Circuit charges no builder fee. HyperCore starting assets require an existing account. Circuit keeps the account mode the owner chose. Unified and portfolio-margin accounts spend one balance per token; a never-configured or standard-mode account keeps spot and each perp DEX apart, so when an order, transfer or swap draws on a short balance, preparation returns a `move` account change from the account's other balance as the step to run first. The engine rechecks precision; the venue atomically enforces balances and margin. Use [`data.markets` and `data.assets`](./data) for perp identities, volume, open interest and each market's order rules: `minimumNotional`, `minimumSize`, `sizeStep`, `priceTick`, `maximumLeverage` and `marginRule`, the values preparation enforces. Main perps use dex `main` and bare symbols; builder-DEX markets retain their prefix and dex. `hyperliquid.spotMarkets.list()` returns live spot coins and their base/quote indices; their order rules are on `data.markets` rows. Pass catalog identities unchanged. Size from session collateral and the `kind: "perp"` rows of `allocation.holdings`, not whole-account balances. Close with `{ kind: "perpReduce", amount: { size: "max" } }`. `agent.orders.listOpen({ venue: "hyperliquid" })` returns the session's resting orders from Circuit's order record, refreshed about once a minute; `hyperliquid.orders.cancel({ orderId })` cancels one the session placed and completes with the order's `state` if it already closed. A perp holding publishes `priceUsd`, `entryPriceUsd`, `valueUsd` and `unrealizedPnlUsd` in USD, and adds `collateralAsset`, `collateralSymbol`, `marginMode`, `marginUsedInCollateralHolding`, `liquidationPrice`, `returnOnEquity` and `cumFundingSinceOpenCollateral` in collateral units; margin stays inside the session's collateral token holding, so equity is that holding's `valueUsd` plus each perp's `unrealizedPnlUsd`, and new orders spend from its `availableQuantity`, which leaves out that margin and open losses; an unknown price or entry basis remains null. Never substitute zero or a live mark for missing basis. Allocation guides sizing; live venue facts authorize execution. Human-reviewed [account operations](../cli-references/operations) own their `execution` options. `hyperliquid.account.update(account)` changes the account: `{ kind: "isolatedMargin", asset, change: "add" | "remove", amountUsdc }` moves isolated margin on an open isolated position of a USDC-margined market, and strict-isolated markets never release margin; `{ kind: "staking", change: "deposit" | "withdraw", amount }` moves HYPE between HyperCore spot and staking, a withdrawal reaching spot after Hyperliquid's 7-day queue; `{ kind: "delegation", change: "delegate" | "undelegate", validator, amount }` moves staked HYPE; `{ kind: "vault", vault, change: "deposit" | "withdraw", amountUsdc }` moves USDC into or out of a vault such as HLP, subject to its lockup; `{ kind: "move", from, to, amount }` moves collateral between a standard-mode account's own balances, each `{ kind: "spot" }` or `{ kind: "perps", dex }`; owner reviews alone may also schedule Hyperliquid's cancel of every resting order on the account, which agent sessions cannot, as a wallet session cannot cancel `"all"` (a Paper trading session can: its account is its own). Each is its own reviewed operation, never part of an order, that completes once Hyperliquid records the action, with any HYPE or USDC it moved; Paper trading accounts trade cross at each market's maximum leverage and apply `isolatedMargin`, each isolated position holding its own margin and liquidating alone, and reject the rest. `hyperliquid.staking.retrieve()` returns the wallet's `staking` (`delegated`, `undelegated` and `pendingWithdrawal` HYPE) and `vaults` (`vault`, `equityUsdc` and `lockedUntil` per vault); they are not session holdings. # Kalshi agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/kalshi Trade Kalshi prediction market contracts from a connected Kalshi account. `agent.kalshi` trades Kalshi outcome contracts from the Kalshi account the session was started with. A contract pays 1 USD when its outcome happens and nothing otherwise, and Kalshi settles held contracts into the account's USD itself; a Paper trading session's contracts settle the same way the next time its account acts. Orders and order reads require a hosted target or a Paper trading session; local `circuit run` rejects them. Kalshi accounts are funded on kalshi.com; Circuit neither deposits nor withdraws. `events.search({ query })` returns up to 20 series whose title, category or tag match the query, `events.search({ seriesTicker })` a series' open events, and `events.search({ eventTicker })` one event with its markets. Each market has a `ticker`, `title`, `yesSubTitle`, `noSubTitle`, `closeTime`, `volume24h`, `trading`, and `yes` and `no` quotes with the contract's pair id `asset` (`KALSHI:.YES/USD`) and its best `bid` and `ask` in USD per contract, null when the book has none. `agent.exchanges.markets.list({ exchange: "kalshi", base: ".YES" })` returns one contract's order rules; Kalshi markets are listed one contract at a time. `orders.create(order, options?)` takes the [order shape every venue shares](./hyperliquid): `{ kind: "spotBuy" | "spotSell", asset, amount: { size }, execution }`, with `size` in contracts at 0.01 steps and `execution` `{ kind: "limit", price, timeInForce }` priced in USD per contract of the pair's outcome ("gtc" rests, "ioc" fills what crosses now, "alo" is post-only). Buying No is buying the `NO` pair; Circuit translates it to Kalshi's single YES book. Kalshi nets the two outcomes of a market, so preparation refuses a sell of more contracts than are free to sell and a buy while the account holds the other outcome; sell that one instead. `agent.orders.listOpen({ venue: "kalshi" })` returns the session's resting orders, and `orders.cancel({ orderId, asset }, options?)` cancels one the session placed. ## Connect a credential `circuit exchange connect --venue kalshi --api-key --private-key-file ` connects an account with the private key file Kalshi downloads; Ed25519 and RSA keys both work. Keys locked to a numbered subaccount are refused, since Circuit trades the primary account. A key with the Write scope gets trade access, a Read key read access. Declare the venue under [`exchangeCredentials`](../getting-started/circuit-toml-reference#exchangecredentials-section), then pass the account ID from `circuit exchange list` as `--exchange-credential ` with a hosted target. # Kraken trading agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/kraken Connect a Kraken API credential, discover Kraken spot markets and trade exact base and quote quantities. Credentials remain outside the SDK. `agent.kraken` supports spot limit and trigger orders across the live pair catalog, including non-dollar quote currencies; it excludes margin, derivatives and withdrawals. Kraken orders and order reads require a hosted target; local `circuit run` rejects them. `agent.exchanges.markets.list({ exchange: "kraken", base?, quote? })` returns the same market rows as [every exchange](./exchanges): the spot pairs with `tradable` and order rules (`minimumSize`, `minimumNotional`, `sizeStep`, `priceTick`). A pair's `asset` is `KRAKEN:/` in Kraken's own asset codes, such as `KRAKEN:XBT/USD`; pass it unchanged. `agent.exchanges.markets.list({ exchange: "kraken", base: "BTC", quote: "USD" })` finds that pair from Kraken's code or its ticker (`XBT` or `BTC`). Read prices with [`agent.data.prices`](./data). `orders.create(order, options?)` takes the [order shape every venue shares](./hyperliquid): `{ kind: "spotBuy" | "spotSell", asset, amount, execution? }`, with `amount` `{ size }` in the base asset or `{ value }` in the pair's quote asset, which the engine sizes at the order's price and rounds down to the pair's `sizeStep`. Circuit refuses an order below the pair's live `minimumSize` or `minimumNotional` with `BELOW_MINIMUM` before anything is sent. Omit `execution` for a market order within 1% of the mid; `{ kind: "limit", price, timeInForce, expiresAt? }` rests per timeInForce ("gtc" rests, "ioc" fills what crosses now, "alo" is post-only and rejected if it would take), an ISO expiresAt within the next 28 days resting it only until then; `{ kind: "stopLoss" | "takeProfit", triggerPrice }` sells or buys at market once Kraken's last price crosses triggerPrice, and the "stopLossLimit" and "takeProfitLimit" forms then rest at price. Paper trading expires orders at expiresAt like live ones. options take a [`once` name](./error-handling). Its result is the venue order every venue returns, with `averageFillPrice` the size-weighted price of the order's recorded trades before fees, to 18 decimals truncated toward zero, null when nothing filled; `operations.retrieve` reports its current values while the order rests. `agent.orders.listOpen({ venue: "kraken" })` returns the session's resting orders from Circuit's order record, and `orders.cancel({ orderId }, options?)` cancels one the session placed, completing with `{ orderId, state }`. Size from each allocation balance's quantity, never pooling USD and USDC; credential-wide balances do not establish session ownership. Inventory includes resting-order commitments, so inspect open orders. Venue balances and limits validate execution. Opposite orders unwind inventory; cancel exits a resting order. Observed fills account for net amounts and fee currencies; inconsistent ledger evidence fails observation. Writes submit once and preserve [failure evidence](./error-handling). ## Connect a credential `circuit exchange connect --venue kraken --credentials-prompt` asks for the API key and API secret with hidden input. Alternatively, supply both `--api-key ` and `--api-secret `. Do not combine direct credentials with `--credentials-prompt`. `--label ` names the account (default Kraken). The same command connects [Coinbase, OKX, Binance and Bybit](./exchanges) accounts. Circuit verifies the key's permissions with Kraken. A key that another app also uses can be refused with `CREDENTIAL_REFUSED`; the refusal says how to set its Nonce Window. | Access | Required Kraken permissions | | - | - | | Read | Funds → Query. Circuit shows the account's balances under Wallets and on Home. | | Trade | Funds → Query; Orders and trades → Query open orders & trades, Query closed orders & trades, Create & modify orders and Cancel & close orders; Data → Query ledger entries. | Extra permissions neither block admission nor expand Circuit's operations. Partial trading permissions yield read access. `circuit exchange list` returns each account's `id`, `venue`, `label`, verified access and the trading permissions it still lacks. Pass the ID as `--exchange-credential ` alongside the [run flags](../cli-references/development#run-and-stop-flags) for an agent declaring `[exchangeCredentials.kraken]`. Trading agents ([`exchangeCredentials`](../getting-started/circuit-toml-reference#exchangecredentials-section)) take `--amount ` in their `minimumAllocation` asset at start. `--exchange-credential` requires a hosted target. Only Circuit's signing boundary receives the credential; agent code cannot select or inspect it. # Lending agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/lending Circuit SDK reference for lending agents: supply, borrow, withdraw and repay on Aave V3 and V4, Spark, Euler, Morpho and Kamino, collateral and category changes, and the markets each venue lists. `agent.lending` supplies, borrows, withdraws and repays on Aave and Spark pools, Euler vaults, Morpho markets and Kamino lending markets through one set of calls. Every call is one operation; a prerequisite Circuit derives, such as a token approval or an Aave or Spark category switch, runs first as its own operation and the call continues after it. `agent.lending.markets.list({ network, protocol? })` returns `{ markets, unavailable }`. `markets` has one row per asset a venue lists on that network: `protocol`, `market` (the Aave or Spark pool, the Aave V4 `/`, the Euler vault, the Morpho market id or the Kamino lending market), `name`, `asset`, `symbol`, `decimals`, whether you can supply or borrow it, `supplyApy` and `borrowApy` as fractions, the asset's own `loanToValue` and `liquidationLoanToValue`, `collateral` (for a borrow row, what it accepts: the `market` to supply the collateral to, its `asset` and LTV pair) and `categories` (the Aave or Spark e-mode categories or Kamino elevation groups the asset belongs to, each with its integer `id`, `securesLoans` when the asset counts as collateral inside it and `canBorrow` when it can be borrowed inside it; a Kamino group lends exactly one asset). A venue or market Circuit cannot read is left out of `markets` without blocking the rest and named in `unavailable` (`protocol`, `market`, null when the whole venue failed, and `error`), so a missing venue reads as unreadable rather than as offering nothing. Supply and borrow check only their own target market on chain, so an unreadable listing never blocks them. `agent.lending.positions.supply({ network, protocol, market, asset, amount, category? })` supplies `asset` to a market from a row, opening the wallet's default account there (on Kamino, its default obligation). `agent.lending.positions.supply({ network, position, asset, amount, category? })` adds to the lending account a held position sits in, named by its `holding.asset`; on Kamino this reaches multiply and leverage obligations too. `agent.lending.positions.borrow(...)` takes the same two forms. `amount` is whole tokens, `"max"` (supply only: the whole token holding) or `{ balancePercent }`; a borrow also takes `{ loanToValue }`, the account's loan-to-value after the borrow on the scale of the holding's `loanToValue`. `category` is a row's `categories[].id`; 0 is none. Aave and Spark switch it first as its own operation; Kamino requests the elevation group inside the supply or borrow's own transaction. `agent.lending.positions.withdraw({ network, position, amount })` and `agent.lending.positions.repay({ network, position, amount, payWith? })` reduce a held position. `amount` is whole tokens, `{ balancePercent }` of the session's holding, `{ loanToValue }` or `"max"`. For an agent, `"max"` is the session's own holding; when the session holds the whole position, Circuit uses the venue's own full close, which also covers interest accrued since. A rebasing holding (Aave, Spark, an Euler loan) is compared in the venue's own shares at the live rate, so accrued interest never makes a whole position look partial; a manual position on the same wallet is never closed by an agent. `payWith: "supply"` repays from the account's supply of the same asset where the venue allows it (Aave, Spark, Euler). Kamino refuses a `"max"` withdraw while a loan is open, because its program withdraws only down to the limit: name an amount or repay first. `agent.lending.positions.update({ network, position, securesLoans })` turns a supply's collateral use on or off (Aave V3 and V4, Spark, Euler). `agent.lending.account.update({ network, protocol, market, category })` or `({ network, position, category })` switches the account's category (Aave and Spark e-mode, Kamino elevation group); the venue refuses a switch its held positions do not allow, and Kamino sets a category only on an obligation that holds a deposit. A Kamino supply or borrow with `category` sets the elevation group in the same transaction as the action, so a first supply can name its group. Circuit derives each venue's setup itself: token approvals (a full repay approves the debt plus 0.1%, so interest that accrues before the repay lands stays covered), Euler's collateral and controller switches inside the same EVC batch as the deposit or borrow (a first deposit into a vault secures loans unless the account already uses ten vaults as collateral, the EVC's limit), Kamino's user metadata, obligation and farm accounts and a requested elevation group inside the same transaction as the action, and a first Aave V4 supply turning the reserve on as collateral in the same spoke `multicall`. Lending operations need a live wallet: Paper trading and backtests refuse them. [Holdings](./holdings) report supplies and loans as `supplied` and `borrowed` rows; pass a row's `asset` as `position`. Its `market` is the market a `markets.list` row names. # Lighter trading agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/lighter Circuit SDK reference for Lighter and Lighter Robinhood trading agents: perp and spot orders sized against the session's holding, order types, positions and account setup. `agent.lighter.orders.create` takes the [order shape every venue shares](./hyperliquid), `perpOpen`, `perpReduce`, `spotBuy` and `spotSell`, sized the same way against the session's own holding; a `spotBuy` names its `size` or `value`, never `"max"`, and a `perpOpen`'s `leverage` defaults to cross margin. `asset` is a Lighter perpetual symbol from [`data.markets({ venue: "lighter" })`](./data), such as `ETH`, or a spot pair such as `ETH/USDC`, which trades from the account's spot balance. `"gtc"` and `"alo"` limits rest at most 28 days, Lighter's maximum order expiry. Results and their observation follow the [Hyperliquid order results](./hyperliquid), with `orderId` the client order index Circuit assigns before sending. `perpOpen` takes [`takeProfit` and `stopLoss`](./hyperliquid) with the same rules; a Lighter exit waiting on its entry reports the entry's size until it activates, then the entry's fill. Preparation rounds sizes down to the market's `sizeStep` and tightens prices to its `priceTick`, both on its [`data.markets`](./data) row. Lighter applies its minimums to orders that rest: a resting or trigger order below the market's `minimumSize`, or a resting limit below its `minimumNotional`, is refused with `BELOW_MINIMUM` before anything is sent. Market and `"ioc"` orders, which never rest, carry no minimum. `agent.orders.listOpen({ venue: "lighter" })` returns the session's resting orders and `lighter.orders.cancel({ orderId })` cancels one the session placed, completing with the order's `state` if it already closed. `lighter.margin.update(margin)` takes the [Hyperliquid account change](./hyperliquid) `isolatedMargin`, or moves USDC between perps margin and the spot balance (`{ kind: "routeTransfer", to: "spot" | "perps", amountUsdc }`); Paper trading handles leverage and `isolatedMargin` as the venue applies them, and their spot buys spend only the collateral that open positions leave free. A Lighter account belongs to the wallet's Ethereum address. A [swap](./swap) into Lighter USDC from any source creates the account: the first deposit bridges to Ethereum USDC, then deposits through the `lighter` provider; later deposits and withdrawals route through Relay. Before the first order, Circuit registers a per-wallet API key derived from the wallet's signature. Lighter USDC is asset `3` on network `lighter`, and perp holdings use `kind: "perp"` with the same fields as Hyperliquid. `agent.lighterRobinhood` trades Lighter's separate deployment on Robinhood Chain with the same methods and rules. It has its own account, markets and API key setup (`setup` with `venue: "lighterRobinhood"`), margins in USDG, asset `3` on network `lighter-robinhood`, and lists stock and ETF perpetuals such as `NVDA` and spot pairs such as `NVDA/USDG` in [`data.markets({ venue: "lighterRobinhood" })`](./data). Its spot pairs trade straight from the unified USDG collateral, so `routeTransfer` is refused. `value`, `amountUsdc` and `minimumNotional` count USDG there. Its first deposit comes from Robinhood Chain USDG through the `lighter` provider; later deposits and withdrawals route through Relay. # Liquidity agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/liquidity Circuit SDK reference for liquidity agents: quote, open, add to, remove and stake Metric, Uniswap v3, Uniswap v4 and Aero Slipstream positions through one set of calls. `agent.liquidity` opens, adds to and removes liquidity positions on Metric, Uniswap v3, Uniswap v4 and Aero Slipstream (formerly Aerodrome) through one call, and stakes Aero positions in their pool's gauge. Each change is one operation; each token approval it needs (an ERC-20 approval of the budget, through Permit2 for Uniswap v4) runs first as its own operation and the change continues after it. Circuit builds and bounds the calls; never send raw LP calldata. `agent.liquidity.pools.retrieve({ network, protocol: "metric", pool: { pool } })` returns a Metric pool's live `span`, `{ lowerPercent, upperPercent }`: the bins it has now as offsets from its current price, which an open's `range` must fit inside. `agent.liquidity.positions.change({ network, action })` changes a position. `action.kind` is `open` (`protocol`, `pool`, `range`, `budgets`, `slippagePercent`), `add` (`protocol`, `position`, `budgets`, `slippagePercent`) or `remove` (`protocol`, `position`, `percent`; 100 closes it). `protocol` is `metric`, `uniswap-v3`, `uniswap-v4` or `aero-slipstream`. A Metric `pool` is `{ pool }`, a green-tier pool from Metric's metadata; a Uniswap v3 `pool` is `{ token0, token1, fee }` (sorted ERC-20 tokens and the fee tier in millionths, such as 500 for 0.05%) of a pool the network's canonical Uniswap v3 factory deployed, and an unknown fee tier or missing pool is refused; a Uniswap v4 `pool` is the hookless, static-fee pool key from `agent.data.pools`; an Aero Slipstream `pool` is `{ token0, token1, tickSpacing }` (sorted ERC-20 tokens and a tick spacing of 1, 10, 50, 100, 150, 200 or 250) of a pool the network's registered Aero factory deployed, found in `agent.data.pools` with protocol `aero-slipstream`, and a missing pool is refused. Uniswap v3 and Aero pools hold only ERC-20 tokens, so budget WETH rather than the native coin. `range` is `{ lowerPercent, upperPercent }`, offsets from the pool's current price rounded outward to whole Metric bins (whose widths vary; a range wider than the pool's bins is refused) or Uniswap and Aero ticks. A range spanning the current price needs both pool tokens and is refused with only one budgeted, and a range funded by one token must clear the price by more than `slippagePercent`, or the price could move into it before it lands. A session starts with one token, so swap part of it first or use such a one-sided range. `budgets` are `[{ token, amount }]` spend ceilings in whole tokens by pool token (the native coin is the zero address); a pool token left out is not spent. `position` is the `position` field of the session's `supplied` [holdings](./holdings): `/` for Metric, the NFT id for Uniswap v3 and v4 and Aero (a Paper trading Uniswap or Aero position reads `p.....`, with fee 0 for Aero). For an agent, `percent` is of what the session holds, so 100 removes exactly the session's share and never another holder's. A Uniswap or Aero removal carries 1% slippage floors on both tokens and collects the position's uncollected trading fees with it; a Metric removal is priced by the pool's oracle and has no onchain floor, and a partial removal that would leave a bin below the pool's minimum shares is refused. An Aero position earns trading fees, less the pool's unstaked fee, until it is staked in its pool's gauge; staked, it earns AERO (xAERO on networks other than Base) only while in range, and no trading fees. `action.kind` `stake` (`protocol`, `position`) stakes a position you hold in a pool with a live gauge, after its own approval of the gauge for that NFT; `unstake` (`protocol`, `position`) returns it to fees and claims its AERO; to take the AERO and stay staked, claim it with [`rewards.claim`](./rewards). Claiming or unstaking before the gauge's minimum stake, a few blocks to a few minutes after staking, forfeits that AERO. A staked position can't change in place: an `add` or `remove` on one runs an unstake first as its own operation, and the position earns fees until staked again. Paper Aero positions can't be staked. Paper trading runs the same call at live pool state: an open or add spends the sized amounts from the Paper trading balance, and a remove returns the position's share of the live pool. A Paper trading position never touches the pool, so it neither moves the price nor dilutes other liquidity, and it can only go into Metric bins that already hold liquidity. Each Paper trading Metric open is a new position, as onchain; Paper trading Uniswap positions are one per pool and range, so opening the same range again adds to it. Paper trading Uniswap positions value principal only and earn no trading fees; Paper trading Metric positions earn the fees that compound into their bins. Backtests do not replay liquidity. # Logging Source: https://docs.circuit.org/agent-developers/sdk-reference/logging Write user-readable activity messages with agent.log. `agent.log(message, options?)` requires a string and writes to the user's activity feed. The only option is `{ error: true }`. Objects, arrays and unsupported options fail typechecking and throw at runtime; valid log delivery is best-effort and never fails the run. ```typescript theme={"theme":{"light":"nord","dark":"nord"}} await agent.log("Selected Bitwise Premium RWA USDC at 5.33% APY"); await agent.log("Deposit submitted; awaiting confirmation."); console.log({ vault, deposit, previewShares }); ``` Explain decisions and outcomes with symbols, formatted amounts and percentages. Never call a submitted transaction confirmed without evidence. Transaction cards own transaction details; keep raw units, addresses, hashes and intermediate variables in console diagnostics. Do not bypass the string contract with `JSON.stringify`. Preserve full non-secret provider errors and causes. Console output is process diagnostics, not user-visible activity. # Papertrade trading agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/papertrade Circuit SDK reference for Papertrade agents: open and close isolated synthetic perps settled on HyperEVM, margin and leverage, and PAPER staking and claims. [Papertrade](https://papertrade.xyz) trades real USDC, unrelated to Paper trading (`circuit run --simulated`); a Paper trading session trades Papertrade with Papertrade's live prices, rules and rates, without its intent queue or payout queue. It settles synthetic perpetuals on HyperEVM against its own liquidity pool at Hyperliquid's order-book mid: no order book, spread, slippage or funding. Every trade is its own isolated position with fixed margin and leverage up to 1000×; there are no resting orders, partial closes or margin top-ups. `agent.papertrade.positions.open({ asset, side, amount: { value }, leverage, fundFrom })` opens a position with the fields of the [shared `perpOpen`](./hyperliquid): `asset` is a market Papertrade lists, such as `"BTC"` or `"ETH"`, as `markets.list()` names them; `side` is `"long"` or `"short"`, `value` is the position's USDC notional, and its margin is value ÷ leverage, truncated to 18 decimals. `fundFrom: "queued"` takes that margin from `queued` winnings instead of the available `balance` (the default): Papertrade pays winning profit it cannot cover into a payout queue, so queued margin keeps that capital trading. Such a position's surviving margin returns to `queued` when it closes, and a liquidation forfeits it. Papertrade's keeper moves the minimum margin and notional; read them from `markets.list()` below rather than remembering them. Circuit refuses an open below either with `BELOW_MINIMUM` before anything is sent. The result is the shared [venue order](./hyperliquid): `orderId` is the venue's `positionId`, `size` is in the market's base asset and `averageFillPrice` is the entry. `agent.papertrade.positions.close({ positionIds })` closes one to twelve positions at the current mid and returns one reduce-only order per position, its `averageFillPrice` the exit and its `venueStatus` `Liquidated` when a liquidation closed it first. `agent.papertrade.positions.closed({ positionIds })` returns how each named position that has closed ended, however it closed: its `exitPrice`, `pnl` in USDC after Papertrade's win impact and fee, the `paperMinted` PAPER a losing close earns, and whether a liquidation closed it (`liquidated`). Papertrade queues every intent and executes it in a later batch; the write resolves when it executes or its one-hour deadline passes. `agent.operations.cancel({ operationId })` withdraws an open, a one-position close, a stake, an unstake or a claim while it still waits in that queue, such as the other leg of a pair when one leg is refused. `agent.papertrade.account.retrieve()` returns the session wallet's live Papertrade account: available `balance`, `queued` winnings, every open position on the wallet, including ones opened elsewhere, and `paper` with unstaked `balance`, `staked` PAPER and claimable USDC `rewards`. A paper session reads its own paper account, whose `queued` is always `"0"`. PAPER, which Papertrade mints to traders and which cannot be transferred, earns USDC rewards while staked. `agent.papertrade.paper.stake({ amount })` and `agent.papertrade.paper.unstake({ amount })` move PAPER in or out of staking instantly with no lockup; amounts are PAPER decimal strings, and Circuit refuses a stake below `markets.list()`'s `minimumStake` with `BELOW_MINIMUM` before anything is sent. `agent.papertrade.paper.claim({}, options?)` credits every claimable reward to the wallet's Papertrade USDC balance and returns the `claimed` USDC, which is `"0"` when nothing is claimable. Papertrade USDC is asset `0` on network `papertrade`, with 18 decimals. A [swap](./swap) from dollars on any network deposits into the wallet's Papertrade deposit address in one transaction: HyperCore USDC moves directly, and other networks bridge straight to the deposit address. A swap back withdraws to HyperCore USDC; each way moves at least 10 USDC. Papertrade credits a deposit once its sweeper moves the funds, usually within minutes. Before the first trade, Circuit registers a 30-day session key derived from the wallet's signature and renews it before it expires. A session key registered elsewhere, such as on papertrade.xyz, does not count: Circuit registers its own alongside it. [Holdings](./holdings) report each of the session's open Papertrade positions as its own `kind: "perp"` holding with its `positionId`, valued at Hyperliquid's mid, with its isolated margin as `marginUsedInCollateralHolding` and its `liquidationPrice`. A liquidation, or a close sent from papertrade.xyz with another session key, counts as the opening session's own close, so its holdings and P\&L follow it. The PAPER the session's closes minted, less what it staked, is a token holding on `ethereum:999`, and its staked PAPER a token holding `STAKED_PAPER` on `papertrade`. Every session shares Papertrade's limits; a session may use at most a quarter of them, and a call waits for its turn within its deadline before failing with `CAPACITY_EXHAUSTED`. Read once per decision, never retry a failed read or refused action on a timer, and time periodic work such as staking from a per-session offset of `agent.sessionId` on the wall clock rather than from process start, since Circuit restarts every continuous session within a few minutes of each release. `agent.papertrade.markets.list()` returns one entry per market Papertrade lists, with the rules Papertrade enforces right now; Circuit reads them live, sharing Papertrade's venue state for up to 5 seconds and `winFeeRate`, a venue-wide contract setting, for up to a minute, and owns Papertrade's formats, so read this instead of exchange.papertrade.xyz. `paused` maps each of Papertrade's actions, `openPosition`, `closePositions`, `paperStake`, `paperUnstake`, `paperClaim`, `registerDeposit`, `withdrawToCore` and `registerSessionKey`, to whether Papertrade refuses it now with `VENUE_PAUSED`; `openPosition` also covers a global trading pause and a paused market. `minimumMargin`, `minimumNotional` and `maximumNotional` are USDC, with `maximumLeverage`; `minimumStake` is the smallest PAPER stake. `headroom.long` and `headroom.short` are the largest notional in USDC one open on that side fits under Papertrade's per-side open-interest cap now, valued at Hyperliquid's best bid/ask midpoint: a larger open fails with `OPEN_INTEREST_CAP`, and others' opens can take the room before yours lands. Rates are fractions, 0.02 meaning 2%. A losing close pays only its loss. A winning close keeps notional × move × (1 − `impact.baseRate`) / (1 + 1/(move × `impact.rateMultiplier`) + `impact.referenceNotional`/(10^6 × move × `impact.positionMultiplier`)), where move is the exit's distance from entry as a share of entry less `impact.deadband`, and nothing when that is not positive; Papertrade then keeps `winFeeRate` of it. A long liquidates at entry × (1 − 1/leverage) × (1 + `bustBuffer`) and a short at entry × (1 + 1/leverage) × (1 − `bustBuffer`), forfeiting its whole margin, so a leg never loses more than its margin. A market fact Circuit cannot read is null and that market's `errors` says why, without blocking its other facts or other markets: never act on a null fact; skip what it governs and surface the error. When Papertrade's venue-wide state is unreadable, the call throws. `agent.papertrade.headroom.list()` returns only each market's `asset`, `long` and `short` headroom and `errors`. # Polymarket trading agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/polymarket Circuit SDK reference for Polymarket agents: search and screen markets, quote, trade and cancel outcome share orders, split, merge and redeem, and Deposit Wallet setup. Circuit deploys a wallet's Deposit Wallet on first use. Agents cannot change account identity; readiness checks the exact selected account. Polymarket accepts orders only from an EOA with trading history; any other EOA cannot start a Polymarket agent (starting asset pUSD, USDC.e on Polygon or an outcome token) and runs it on its derived Deposit Wallet instead. From a regular wallet, approvals and USDC.e wrapping use separate operations with independent deadlines; each approval is unlimited, so it runs once per spender, and a wrap converts all of the wallet's USDC.e to pUSD at once. A Deposit Wallet swap runs as one relayed batch from the Deposit Wallet through the quoted provider; a pUSD swap to anything but USDC.e first unwraps to USDC.e in its own operation, because the relayer approves pUSD to no router. Discover identities with `events.list({ rail })` or `events.search({ query })`, which returns slug/title/startDate references; both are listings shared across agents, refreshed every 15 seconds and every minute, so read current prices from `markets.retrieve` or a quote. `events.retrieve({ slug })` includes companion events and all readable active, unarchived, open markets accepting orders; malformed market rows are omitted with error diagnostics so healthy markets remain available. `markets.retrieve({ asset })` reads any listed market, open or closed, with question/outcome names, `acceptingOrders` (false once it stops trading) `resolving` (true while a proposed UMA resolution is pending, when Circuit refuses buys) and the order rules preparation enforces: `minimumNotional` for a market buy's `value`, fees included, and `minimumSize` and `priceTick` for a limit order, all null once the market stops taking orders (`minimumSize` is 0 when the market sets no minimum). `prices.list({ asset })` returns ISO timestamps and decimal pricePusd history. Never invent token IDs. `markets.screen` filters endsWithinMs, lowestPricePusd/highestPricePusd, minLiquidityPusd, stakePusd and sportsMarketTypes, ranking by orderBy. It uses execution's book walk and rounding: pricePusd is the limiting price, estimatedShares the encoded quantity, and excludesFees=true. The price band applies to the limit. Screening omits funding and approval checks; orders.quote includes fees and Review checks readiness. Screen results group outcomes under event slug, with null-slug markets forming their own groups. Rows include conditionId, volume24hPusd and liquidityPusd (decimal strings), sportsMarketType, line, gameStartTime, negRisk and groupItemTitle. An event ranks by its best outcome; sportsMarketTypes selects indexed market types. For negRisk groups exactly one leg resolves YES; a complete set costs less than its guaranteed payout only when asks sum below 1. tagSlug includes and excludeTagSlugs removes matching markets before pricing, such as excluding sports. Every fillable outcome is returned. scanned counts examined markets before tag exclusion, including unreadable rows; truncated means the scan stopped at its first 500 markets in orderBy order before the window ended, so exclusions cover only examined rows; raise minLiquidityPusd or shorten endsWithinMs to cover the rest. orders.quote and orders.create take the [order shape every venue shares](./hyperliquid) with the outcome's token id as `asset` (markets on Polymarket's protocol v2 return position ids in the same field, still a decimal string): `{ kind: "spotBuy", asset, amount: { value } }` spends at most `value` pUSD and `{ kind: "spotSell", asset, amount: { size } }` sells `size` shares. Circuit charges no builder fee. A buy's value includes Polymarket fees; a sell rounds shares down to venue precision; on create, `size: "max"` sells the session's whole holding of that outcome. These fill-or-kill market orders require current ticks, including 0.005 and 0.0025, and accept prices up to the book walk's worst level plus 1%, rounded away from the book to at least one tick; one the book moved past before it matched fails with `SLIPPAGE_EXCEEDED` and trades nothing; Circuit refuses with `BELOW_MINIMUM`, before anything is sent, a buy whose `value` is below the market's `minimumNotional` from `markets.retrieve`, which is 1 pUSD after its taker fee. A limit order takes `amount: { size }` and `execution: { kind: "limit", price, timeInForce, expiresAt? }` and trades exactly `size` shares (two decimals) at the tick-aligned `price` or better: `"gtc"` rests until filled or canceled, `"alo"` rests as maker only (post-only) and is refused if it would cross, `"ioc"` fills what crosses and drops the rest, and `expiresAt` (at least 2 minutes ahead) ends a resting order on its own. Resting orders need the market's `minimumSize` shares. Every order's result is the venue order every venue returns; a limit order's operation records each fill until the order fills, is canceled or expires. `agent.orders.listOpen({ venue: "polymarket" })` lists the session's resting orders and `orders.cancel({ orderId })` cancels one, completing once Polymarket reports it canceled or filled. Paper trading runs the same order checks: market and `ioc` orders take the live book level by level within their limit, market orders whole or not at all, resting orders fill when recorded Polymarket trades cross their price, and they cancel and expire at `expiresAt` like live ones. Quote returns price, signedSharesChange and expectedPusdAmount, or null when the book cannot fill the order; create refuses that order. Create accepts the optional [`once` name](./error-handling), rechecks live balances and submits once. A market order's result is `filled`, with `size` the shares it bought or sold, `limitPrice` the worst pUSD per share it accepted and `averageFillPrice` the fills' pUSD per share before fees, to 18 decimals truncated toward zero; its legs carry the pUSD it moved. Completed operations retain fills and settlement receipts; activity links open Orbscan. Use the `kind: "prediction"` holding's quantity for session shares and its nullable entryPriceUsd for historical basis; conditionId lives on that holding and in redemption results. Never replace missing basis with a wallet-wide average. Size trades from the pUSD and outcome holdings in `agent.allocation`; see [holdings](./holdings). `positions.redeem({ asset }, options?)` selects one entire resolved binary market: all YES and NO account holdings redeem together. isRedeemable marks a held outcome that pays out once its market resolves; a losing outcome is never redeemable. Deposit Wallets batch approval/redemption; eligible EOAs approve separately and pay Polygon gas. To redeem several markets, select one outcome per conditionId and call sequentially, retaining each completed operation. Redemption returns one completed operation. result.redeemed includes both outcomes, including zero holdings, with asset, conditionId, shares, formattedShares, question and outcome. A market whose holdings pay nothing, because they lost or are already gone, completes without a transaction, spends no gas and returns an empty result.redeemed; its losing shares stay held. An unresolved market fails. Each operation retains its own identity and receipts. options can persist those references before execution. `positions.change(change, options?)` takes one of three kinds. `{ kind: "split", asset, amountPusd }` turns pUSD into as many shares of each outcome of the asset's binary market; `{ kind: "merge", asset, shares }` turns that many shares of each outcome back into pUSD. `{ kind: "convert", assets, shares }` takes No outcomes of one negRisk event and turns `shares` of each, net of the market's fee, into Yes shares of every other question plus pUSD for all but one converted question. A Deposit Wallet runs a convert as one transaction; a regular wallet runs its Router calls as chained steps, each step resuming after the call before it. Each checks balances first, batch approvals like redemption, settle on Polygon and return a null result; their movements are the operation's legs. Paper trading settles them against the same on-chain market terms. # QFEX agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/qfex Trade QFEX perpetuals on stocks, indices, FX and commodities from a connected QFEX account. `agent.qfex` trades QFEX perpetuals from the QFEX account the session was started with. QFEX lists perpetuals on stocks, indices, FX, commodities and pre-IPO companies, margined in USDC. Orders and order reads require a hosted target or a Paper trading session; local `circuit run` rejects them. Ask Circuit deposits USDC on Arbitrum One to a connected QFEX account and withdraws USDC from it to the account's registered Arbitrum One address; agents neither deposit nor withdraw. `agent.data.markets({ venue: "qfex" })` lists QFEX markets with the symbol orders take (such as `AAPL-USD`), their order rules, maximum leverage, price and funding rate. `orders.create(order, options?)` takes the [perp order shape every venue shares](./hyperliquid): `{ kind: "perpOpen", asset, side: "long" | "short", amount, execution? }` or `{ kind: "perpReduce", asset, amount, execution? }`, with `amount` `{ size }` in contracts or `{ value }` in USDC notional. Omit `execution` for a market order, sent as an ioc limit within the slippage of the mid; `{ kind: "limit", price, timeInForce }` rests per timeInForce ("gtc" rests, "ioc" fills what crosses now, "alo" is post-only). Each order uses the leverage the QFEX account already holds for that market; Circuit never changes it. Positions appear in `agent.allocation` as perp holdings on network `qfex`. `agent.orders.listOpen({ venue: "qfex" })` returns the session's resting orders, and `orders.cancel({ orderId, asset }, options?)` cancels one the session placed. ## Connect a credential Under **Wallets → Add wallet → Connect QFEX**, pick one of your EVM wallets and accept QFEX's terms. Circuit signs QFEX's message with that wallet under your passkey, creates the wallet's QFEX account, and seals its key; you never see or paste one, and connecting the same wallet again keeps the existing account. If QFEX refuses the account's key, choose **Reconnect** on the account under Wallets (or run the CLI connect again) to issue it a new key; the account and its history stay. A Solana or Polymarket Deposit Wallet can't hold a QFEX account. From the CLI, `circuit exchange connect --venue qfex --wallet ` prints the message QFEX asks the wallet to sign, and `--accept-terms` signs it with that wallet and creates the account. Declare the venue under [`exchangeCredentials`](../getting-started/circuit-toml-reference#exchangecredentials-section), then pass the account ID from `circuit exchange list` as `--exchange-credential ` with a hosted target. # Rewards agent SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/rewards Circuit SDK reference for rewards (Merkl rewards and Aero gauge AERO): read what the session wallet can claim, and claim it. `agent.rewards.list({ network? })` returns the session wallet's claimable rewards as Circuit last indexed them (hourly, and after each transfer into the wallet): one row per Merkl reward token, and one per Aero pool whose gauge holds AERO (xAERO outside Base) for the wallet, from its staked positions. `network` limits the rows to one EVM network. Each row has `network`, `claim` (what `rewards.claim` takes to claim it: `{ protocol: "merkl", tokens: [token] }` or `{ protocol: "aero-slipstream", pool }`), `asset` (the token a claim pays: the reward token, or the token a wrapped reward unwraps to), `symbol` (of `asset`, null if unknown) and `claimable` (whole units). `agent.rewards.claim({ network, claim }, options?)` claims what `claim` names on `network` in one transaction and returns a completed operation, the same `rewardsClaim` operation Ask and the web app submit. A Merkl `claim` takes one to fifty reward token contracts in `tokens`, or null for everything claimable on the network; Circuit reads Merkl's proofs and the Distributor's claimed amounts live when the claim commits. An Aero `claim` names one `pool` and takes all the AERO its gauge holds for the wallet; the positions stay staked, and claiming within the gauge's minimum stake after staking forfeits part of it. Circuit refuses with `INVALID_INPUT` when nothing named is claimable or Merkl pays a reward to a recipient other than the wallet. The claimed tokens join the session that claimed them; rewards are not [holdings](./holdings) until claimed. # Crypto swap and bridge SDK Source: https://docs.circuit.org/agent-developers/sdk-reference/swap Circuit SDK reference for swaps: quote and execute same-chain swaps and cross-chain routes across Circuit's networks with slippage and minimum output. `agent.swaps` accepts one semantic intent. `quote(request)` inspects it; `create(request, options?)` takes the same request, obtains a fresh executable route and never broadcasts the preview. Both size the request the same way. The request has these fields: | Field | Contract | | - | - | | `from`, `to` | `{ network, asset }`; the SDK supplies the session wallet on both sides. `to` may instead be `{ stock: "NVDA" }`: Circuit buys whichever Ondo, xStocks, Backpack, Coinbase or Robinhood token on the session wallet's chain family yields the most shares, comparing live executable quotes net of fees. Tickers resolve against the hosted catalog, so `circuit run` rejects them. | | `amount` | Source quantity in whole tokens, rounded down to the token's smallest unit, or `"max"` or `{ balancePercent }` of the session's own holding of `from`; `"max"` never exceeds what the wallet can spend after the selected route's source transaction costs. | | `slippage`, `minimumReceive` | Optional percent string (default 1% on every route) and optional destination floor in whole tokens, rounded up. Executable construction preserves the higher floor. | | `engines` | Optional routing allowlist, for example `["uniswap"]`. | | `confidential` | Optional `true` routes only through NEAR Intents Confidential Intents, same-chain included, hiding the link between deposit and delivery; `engines` may name only `nearIntents`. | `create`'s `options` take a [`once` name](./error-handling), and its result carries the `received` amount of the destination asset. A quote's `assetSend.amount` is the amount it sized. Circuit refuses a swap worth under `MINIMUM_SWAP_USD`, which `circuit:sdk` exports, with `BELOW_MINIMUM` before anything is sent. A quote is an estimate: it inspects unfunded intents, never simulates source calls and never submits. Create qualifies a fresh route after required funding/setup settles. Each prerequisite and the swap receives a separate operation ID, receipts and [deadline](../concepts/execution-model#execution-limits-and-failures); a failed swap may still have observed source debits or partial destination credits. Source amount, recipient, provider selection and explicit minimum remain binding. A review pins expected output less slippage, rounded down to the destination token's smallest unit with a minimum of one, or a higher inherited or explicit floor. Prerequisite continuations retain that floor; a separately approved review may tighten it, while execution preserves it. Existing approved floors are never implicitly lowered. An ineligible higher-output provider cannot hide an eligible alternative; provider restrictions remain binding. `circuit capabilities --resource networks --json` lists each network's gas and dollar assets, wrapper and `swapProviders`. Across also supports incoming HyperCore and Lighter USDC; a Solana recipient must already have its USDC associated token account. Across never spends from Solana; Solana-source bridges route through Relay or NEAR Intents, and same-chain Solana swaps through Jupiter or NEAR Intents. Jupiter quotes compare its Metis router with a JupiterZ market-maker fill at a firm price; Jupiter lands a JupiterZ fill, and a market maker that declines or lets its quote expire fails the swap with `SUBMISSION_REJECTED` before anything is sent. ERC-4626 routes run only where the vault router is deployed, which enforces the minimum atomically; a deposit above the vault's current `maxDeposit` fails with `NO_ROUTE_AVAILABLE` before routing. A provider's route that does not execute in Circuit's pre-sign simulation fails with `PROVIDER_UNAVAILABLE`, `SLIPPAGE_EXCEEDED` when it reverts at its slippage guard, or `INSUFFICIENT_BALANCE` when the wallet no longer holds the amount; routes Circuit builds itself (wrap, vault, HyperCore, Lighter, Derive and Papertrade) and approvals keep `SIMULATION_FAILED`. Direct `velora` quotes use Market v6.2 and are same-chain only. `metric` quotes Metric’s oracle-priced pools on Ethereum, BNB Chain and Robinhood Chain, same-chain only, through at most one intermediate token, and prices each route onchain; a pool whose latest price has not reached the chain does not quote. Direct `cowswap` quotes sell ERC-20 tokens through CoW Protocol; the source wallet pre-signs the order in one transaction, a solver batch delivers it within 20 minutes, and an unfilled order expires without moving funds. Direct `uniswap` quotes use the Uniswap Trading API’s v2/v3/v4 pool routing through Universal Router 2.1.2: the source wallet approves Permit2 once per token without limit, and each swap embeds a Permit2 permit for exactly its input, signed with the swap’s own confirmation. `nearIntents` (NEAR Intents 1Click) is opt-in: it quotes only when `engines` names it or `confidential` is set, same-chain or cross-chain; it delivers HyperCore and HyperEVM USDC but never spends them; the source wallet deposits once to a 1Click address, delivery often takes minutes, and refunds return to the source wallet. Every swap settles as a signed transaction; required ERC-20 approvals receive separate confirmations. Liquidity management is outside the swap API. Circuit compares eligible providers by exact destination output. Quoted USD costs are informational. Quote returns provider, exact assets/addresses, required `assetReceive.minimumAmount` (the provider's executable guarantee, which can exceed the approved floor), `venuePriceImpact` when available, `feeBreakdown` and `quoteFreshness: { issuedAtMs, ttlMs }`. Every eligible route guarantees at least its applicable floor before selection. Route construction may enforce a stricter minimum from the current quote, but never lowers the approved floor. `feeBreakdown` lists every fee the route reports as `{ kind, amount?, symbol?, asset?, amountUsd? }` with `amount` in whole tokens. `kind` is one of `network` (the source network's fee for the transactions the wallet signs, paid on top in that network's fee token), `execution` (delivery on the destination by a relayer, solver or bridge, including its gas and any destination account activation) or `liquidity` (liquidity providers, pools, solver rebalancing and the routing provider's own fee). `execution` and `liquidity` fees are already taken out of the quoted output, so do not subtract them again. Fees come from each provider's quote; Solana network fees are the exact message fee. Hosted quotes convert any fee the provider reports only in tokens into USD with Circuit's prices, and `circuit run` leaves those in tokens. An entry without amounts is charged but not itemized, such as aggregator pool fees priced into the rate; a kind with no entry is unknown, never zero. `amountUsd` is negative when the provider pays the user. USD values are display facts, never transaction authorization. Price impact is reflected in expected output; slippage allows additional execution deterioration. Review warns above 2% estimated impact, independently of the 1% default slippage. Reported impact is advisory; swaps have no configurable price-impact cap. Slippage and minimum-output floors do not guarantee a maximum price impact. HyperCore sides use venue token indices, including USDC `"0"` and HYPE `"150"`. The `hypercore` provider transfers native HYPE and venue-linked ERC-20s between Core and HyperEVM. Native HYPE on HyperEVM uses `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`. Direct transfers preserve the wallet; Circle USDC deposits can name another recipient. Decimal conversion rejects dust instead of burning it. ERC-20 withdrawals simulate delivery and check Core HYPE for destination gas; final success requires both observed movements. Other routers determine their token coverage from executable quotes; none swaps two HyperCore assets, which trade as Hyperliquid spot orders. Mode, exact balance, provider currencies and scales are rechecked before submission, without resizing or retrying. Arc mainnet (`ethereum:5042`) uses USDC for gas and its canonical dollar asset: the native sentinel `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`. Its ERC-20 USDC interface at `0x3600000000000000000000000000000000000000` spends the same balance. Circuit counts that balance once; there is no wrap or unwrap operation. Relay supports Arc bridging with EVM networks, Solana and HyperCore. Across supports Arc↔EVM and Arc→HyperCore, but currently rejects Arc↔Solana pairs. Relay, KyberSwap and Uniswap support same-chain swaps. Across and Uniswap translate native USDC into its ERC-20 denomination: Circuit rounds inputs down to whole micro-USDC, minimum outputs round upward, and Max reserves gas then rounds input downward. Velora and ERC-4626 routing are unavailable on Arc. Agent starting inventory uses native USDC. Native transfers, ERC-20 transfers and raw EVM calls use the shared transaction lifecycle. # Transactions Source: https://docs.circuit.org/agent-developers/sdk-reference/transactions Read observed session movements and execute unsigned wallet transactions. `agent.transactions.list({ cursor? })` returns one page of observed session movements, including venue fills, oldest first, as `{ rows, nextCursor }`, on hosted targets; local `circuit run` rejects it. Pass `nextCursor` back for the next page, or use `for await (const movement of agent.transactions.list())` to walk every page. Rows contain `operationId`, `observationIndex`, `role` (`principal`, or `network_fee` for gas the session wallet paid), network, canonical assetKey, signed whole-token amount, nullable priceUsd, timestamp and typed references. Negative quantities are debits; positive quantities are credits. Perp movements retain fill prices. References may be empty; order IDs are never transaction hashes. Use [`agent.lending`](./lending) for Aave V3 and V4, Spark, Euler, Morpho and Kamino and [`agent.liquidity`](./liquidity) for Metric and Uniswap v3 and v4 rather than raw transactions. Use external SDKs for discovery, verified identities, live reads and unsigned construction beyond the typed catalog. Circuit's wallet owns signing and execution. Size effects from [session allocation](./holdings), not whole-wallet balances. `wallet.transactions.preview({ network, request })` accepts EVM `{ toAddress, data, valueWei }`, or Solana `{ hexTransaction }`, an unsigned serialized version 1 transaction; Circuit rejects legacy and version 0 transactions with `INVALID_INPUT`. `wallet.transactions.create({ network, request }, options?)` accepts the same request directly. Preview is optional and carries no execution authority; create always validates and simulates through engine preparation before admission and rechecks live facts before execution. On Base, the signed transaction's calldata is `data` followed by Circuit's ERC-8021 builder code suffix; a suffix already in `data` stays before it, and ERC-8021 parsers read Circuit's. A request that reverts when previewed or prepared throws `AGENT_TRANSACTION_REVERTED`, naming the target and the revert reason, error name or raw selector; nothing was sent and the failure is your agent's. It returns a completed [operation](./error-handling); options can persist its admitted reference. Input cannot select another signer, and preview does not enforce allocation. An optional gasBalanceWarning reports that the ETH left after this transaction's worst-case fee may not cover another worst-case fee like it; it never blocks spending. Decoded Solana requests may instead provide `{ instructions }`: each has programAddress, ordered accounts (address/isSigner/isWritable), and ordered data parts: integer (value and bytes 1/2/4/8/16), address, utf8, hex or anchor. The engine constructs the initial message and blockhash; supplied serialized messages retain their blockhash. Ethereum mainnet broadcasts identical signed bytes concurrently to MEV Blocker fullprivacy and the run's read endpoint: Alchemy for hosted runs, the public Ethereum endpoint for embedded runs. Either acknowledgment starts chain observation. MEV Blocker offers no backrun rebates; Alchemy retains its own privacy policy. There is no public-mempool fallback or next-block guarantee. Explicit local RPC overrides use only that endpoint. `wallet.messages.sign` signs EIP-191 or EIP-712 and returns v/r/s plus the signature. Signatures may authorize external effects; their use is not constrained by allocation. # Transfers Source: https://docs.circuit.org/agent-developers/sdk-reference/transfers Quote and submit exact wallet transfers, including HyperCore and Lighter tokens between venue accounts. `agent.transfers.quote({ from: { network, asset }, to: { address }, amount })` returns the `amount` and the most it pays in `fee` of `feeSymbol`, or rejects a transfer that cannot execute with its reason; `transfers.create(request, options?)` executes the same request, sized the same way. Both engines use the session wallet as sender. The optional second argument retains its [admitted operation reference](./error-handling). `amount` is whole tokens, rounded down to the token's smallest unit, or `"max"` or `{ balancePercent }` of the session's own holding of `from`. `"max"` never exceeds what the wallet can send after fees. Solana quotes simulate and report live fees and recipient-account rent, sized for a new associated token account's extensions; reverts preserve detail and failed RPC reads reject. Solana transfers use the mint's owning SPL Token or Token-2022 program and check the mint and decimals. Transfer fees follow the mint's rules and can reduce the amount credited to the recipient; transfer hooks requiring extra accounts and mint/account restrictions still fail simulation. Create rechecks balance, gas and policy, returning a completed operation with receipts. gasBalanceWarning reports that the ETH left after this transfer's worst-case fee may not cover another worst-case fee like it; it never blocks execution. No future-transaction reserve applies. HyperCore sends use the same API with `from.network: "hypercore"`, a token index as `asset`, and the recipient's EVM address. USDC is `"0"` and HYPE is `"150"`. Never pass a ticker or hexadecimal token ID as `asset`. Sendable quantity is `max(0, total - (spotHold ?? hold))`; Circuit adds no reserve. Creation rechecks exact spot availability before signing and submission. Sends credit the recipient's spot compartment through `sendAsset`; Core↔EVM movement uses [swaps](./swap). Insufficiency fails without resizing or retrying. Lighter sends use `from.network: "lighter"`, a Lighter asset index as `asset` (USDC is `"3"`), and the recipient's EVM address. The recipient must already have a Lighter account; otherwise swap the funds to another network for that address with [swaps](./swap). Lighter charges its transfer fee in USDC on top of the amount; `transfers.quote` reports it as `fee` and rejects USDC amounts that leave no room for it. Lighter Robinhood sends work the same way on `lighter-robinhood`, with USDG (`"3"`) in place of USDC. # Watched Wallets Source: https://docs.circuit.org/agent-developers/sdk-reference/watched-wallets Follow other traders from a Circuit agent: FOMO leaderboards, the trades of watched wallets on chains and perp venues, and memecoin candles for copy trading strategies. `agent.fomo.leaderboards.retrieve({ window, top? })` returns FOMO's ranking for `"24h"`, `"7d"`, `"30d"` or `"all"`, up to 150 traders with `rank`, `pnlUsd` and `volumeUsd` (decimal strings), `trades` and `wallets.evm` / `wallets.solana`. Circuit reads it from FOMO at most every six hours, and every agent shares that answer, so a ranking can be up to six hours old. `agent.fomo.traders.retrieve({ username })` resolves one trader; a trader whose wallets Circuit has seen on any leaderboard or lookup in the last seven days answers from that, so a wallet FOMO changes can take up to seven days to appear, a lookup FOMO is still resolving is retried after 15 minutes, and an unknown username is retried after a day. A wallet is absent while FOMO is still resolving it. `agent.solana.holdings.retrieve({ wallet })` reads any Solana wallet's `sol` and per-mint `tokens` now, at most 60 calls a minute per account. A token's price and bars, fresh pump.fun tokens included, come from [`agent.data.prices({ network: "solana", asset: mint, interval, bars })`](./data): a token the catalog does not list is priced from its most liquid pool in USD, at most 1000 bars, live only, so a backtest cannot replay it. Prices and holdings are signals, never swap prices. A continuous agent whose `circuit.toml` declares a `walletTrade` trigger without a `wallet` or `cooldownMs` watches the up to 100 wallets it passes to `agent.watchedWallets.set({ wallets })`, which replaces the list. Each trade one of them makes arrives from `agent.next()` seconds after it lands as a `walletTrade` trigger naming the `wallet` and the `trade`: a chain swap the wallet paid for (`venue: "chain"`, with `sold` and `bought`), a Relay cross-chain buy it paid for (the same, with the bought token's network in `boughtOn` and its wallet in `recipient`), one Hyperliquid, Lighter, Lighter Robinhood or Derive fill, or a Papertrade position opened or closed (see the [`walletTrade` trigger](../getting-started/circuit-toml-reference)). Deposits, airdrops, dust and made-up transfers of scam tokens never arrive, so agents need no token checks of their own. Copy a trade at most once by naming the write's `once` after its `transaction` or `id`, and keep entry snapshots and rolling windows in [memory](../concepts/execution-model#memory). ```ts theme={"theme":{"light":"nord","dark":"nord"}} import type { RunFunction } from "circuit:sdk"; export const run: RunFunction = async (agent) => { const { traders } = await agent.fomo.leaderboards.retrieve({ window: "24h", top: 100 }); await agent.watchedWallets.set({ wallets: traders.flatMap((t) => t.wallets.solana ?? []) }); for (;;) { const trigger = await agent.next({ until: Date.now() + 60_000 }); if (trigger?.kind !== "walletTrade" || trigger.trade.venue !== "chain") continue; for (const { asset } of trigger.trade.bought.filter((moved) => !/^1{32}$/.test(moved.asset))) { const { bars } = await agent.data.prices({ network: trigger.trade.boughtOn, asset, interval: "1m", bars: 6 }); const last = bars?.at(-1); const high = (bars ?? []).slice(0, -1).reduce((max, bar) => Math.max(max, Number(bar.high)), 0); if (last && Number(last.close) > high) await agent.log(`${asset} broke out after ${trigger.wallet} bought it`); } } }; ``` # Get Started Source: https://docs.circuit.org/agent-users/get-started Get started with Circuit: sign in with a passkey, create or import a wallet, fund it, and start your first AI trading agent in Paper trading. Circuit is available at [app.circuit.org](https://app.circuit.org/). You can use it directly from your browser, or add it to your home screen for a mobile-app-like experience: * **iOS**: Open `app.circuit.org` in Safari, tap Share, then Add to Home Screen. * **Android**: Open `app.circuit.org` in Chrome, tap **⋮**, then Add to Home Screen. ### Create an account Create an account with a passkey, then sign in with it. Use a password manager such as iCloud Keychain, 1Password, or Google Password Manager to access it across devices. Add backup passkeys under **Settings → Passkeys**, which retains a current credential and, when recovery is enabled, a recovery-capable credential. To replace your recovery passkey, sign in with it, add a recovery-capable replacement, then sign in with the replacement and delete the old one. Recovery transfers locally when both passkey ceremonies provide PRF output; plaintext recovery keys never leave the browser. Other passkeys can still be added for sign-in, but cannot replace the last recovery-capable credential. ### Ask Circuit Type or paste a question, trade, or strategy into the message box. See the [FAQ](/support#using-circuit). Ask Circuit is one chat for questions, trades and agents. Name an agent to change it, or open its page and say what to change: the Builder updates and verifies its code, Circuit prepares any funding or agent action the fix needs, progress shows on the agent's card, and successful changes apply wherever the agent runs, from its next run. Trades and questions work in the same chat, so you can fund an agent between changes. **New chat** starts over. Attach images alongside your message using the image button, paste, or drag-and-drop anywhere in the chat panel. Preview and remove images before sending. JPEG, PNG, WebP and GIF are supported, up to eight images, 3 MiB each and 6 MiB total. Images remain available in chat history and when Circuit hands a request to the builder. When the message box shows a microphone, tap it to dictate. It finishes when you stop speaking; **Done** ends recording immediately. Review the text, amounts and token names, then press Send. Cancel discards the recording; recordings stop after two minutes. Allow microphone access when your browser asks. Circuit does not save the audio. ### Set up your wallets Agents need a wallet to run on. You can create a new self-custodial wallet or import an existing wallet by private key. See [Wallets & Security](/agent-users/wallets-and-security) for key export and signing protection. # Running Agents Source: https://docs.circuit.org/agent-users/running-agents Browse, start, top up and stop AI trading agents on Circuit, switch from Paper trading to Real money, and read each agent's activity. ### Browse and start Browse agents built by Circuit, by you and by the community. Each description gives the agent's thesis, strategy and exposure. Compare returns and onchain activity. An agent's return is its Paper trading benchmark: \$1,000 in the agent's starting asset, on default settings, that Circuit runs in Paper trading for every agent that can and keeps running as the agent's code changes. The agent's page charts it under **Paper trading**. Order **Agents** by **Popular** (most people running it), **Return** (best 30-day benchmark return) or **New**. Agents support Ethereum, Solana, Base, Hyperliquid, Polymarket, and more. Select an agent, wallet, and amount. Compatible wallets under **Needs setup** remain selectable, but starting stays blocked until their venue account requirements are satisfied. It begins under your passkey-signed permit and runs in the background until stopped. Start and top-up allocate existing unallocated funds and never bridge: ask Circuit to obtain the agent's starting asset, on its network and at least the minimum shown at Start, in the selected wallet first. Circuit checks availability live and rechecks when you confirm. Agents start in **Paper trading** by default: live markets, with no Real money moving. Swaps fill at the live executable quote and pay its network fee from about \$10 of Paper trading gas, which stays out of the session's value and return the way a wallet's gas stays out of its allocation, so only the fees spent count against it; Hyperliquid, Lighter and Kraken orders fill against the live book and one-minute bars with the venue's fees, funding and liquidation rules, and a position on a market with no recorded price, such as a delisted one, settles at its last price without a fee; Polymarket orders fill against the live book and redemptions pay the market's resolution; Papertrade positions open and close at Hyperliquid's live mid with Papertrade's win impact and fee, mint PAPER on losses at its live rate, liquidate at their bust price, and staked PAPER earns what the same stake earns on Papertrade. Agents that start from an open perp position, transfers and raw transactions cannot run in Paper trading and fail. Switch to **Real money** to pick a wallet. Paper trading is a stage of an agent, not a second copy: **Use Real money** starts it on a wallet with the same settings and stops its Paper trading, and an agent trading Real money can't run in Paper trading until you stop it. They are public like Real money agents and labeled **Paper trading** wherever they appear, but never count toward wallet P\&L or the amount allocated to an agent. ### Manage agents | Control | Effect | | - | - | | Active agents | See running agents and their wallets. Run multiple agents on one wallet or across wallets. | | Stop | Stop the agent and release its allocated funds immediately. Its perp, prediction and liquidity positions and resting orders stay open: Stop lists the positions and offers to close them in Terminal, one reviewed confirmation per transaction, sized to what the session holds. A liquidity close returns the pool tokens to the wallet, without a swap. | | Activity | Inspect actions, amounts, network icons, and direct explorer links. Unknown actions retain contract-interaction or balance-change labels. Global Activity is public: it includes usernames, agent lifecycle events, and Circuit-originated transactions. | ### Ask Circuit Ask which agents are running, find a recurring strategy, or name an agent and wallet to start. Circuit reads agent status, settings, and recent logs; ambiguous targets require clarification. Recommendations describe catalog strategies without promising performance. Agent actions: Run now, Stop and Top up require confirmation. Their Review uses the transaction card layout, with the same dismiss control and a Start or Top up button in the confirm position. These buttons open the existing amount and settings panel with your requested inputs filled in. Top up allocates the amount and admits a run together, even while busy. Accepted cards show run outcomes and link to the agent's activity. # Wallets & Security Source: https://docs.circuit.org/agent-users/wallets-and-security Import or export a wallet's private key, how Circuit protects keys and authorizes every wallet operation with your passkey, and how first-deposit gas works. ### Import or export a wallet Open **Settings → Wallets**, tap **Add wallet**, choose **Import wallet** and paste the wallet's EVM or Solana private key. Circuit detects the wallet type and shows the address before you import. The wallet keeps working in your other wallet app, and Circuit and your agents can trade its holdings directly. You can export a wallet's private key at any time: open **Settings → Wallets**, tap **⋯** on the wallet, select **Export private key**, and confirm with your passkey. Copy the key and store it somewhere safe. > [!WARNING] > > Anyone with your private key has full control of that wallet. Never share it, and store it securely. ### Exchange accounts Under **Wallets → Add wallet**, connect a Kraken, Coinbase, Binance, OKX, Bybit or Kalshi account with an API key, or create a QFEX account for one of your EVM wallets: accept QFEX's terms and Circuit signs for that wallet under your passkey and seals the account's key, so you never see one. Circuit reads its balances and the key's permissions every minute and counts the balances on Home and in your total; select the account in Wallets to see Home for it alone. If the exchange refuses the key, Circuit tries it again every 15 minutes until it answers or you connect a new key. A key with spot trading permissions can also trade through Ask Circuit and fund agents; Kraken and QFEX accounts can also deposit and withdraw through Ask Circuit; a QFEX withdrawal sends USDC on Arbitrum One to the wallet the account was created for, and these accounts have no QFEX login. If QFEX refuses its key, remove the account and connect the wallet again to issue a new one; the QFEX account and its funds stay. Coinbase needs a Secret API key using the Ed25519 signature algorithm, and OKX keys need the passphrase you set. Balance changes count as deposits and withdrawals, so an exchange account's P\&L is the price movement of what it holds. Remove an account from its **⋯** menu to stop reading it; connecting the same key again brings it back. Circuit seals each API secret in its key management service and never shows it again. ### Safety Circuit wallets are self-custodial: each wallet and its private key are yours. The key is created, or sealed when you import it, inside attested hardware enclaves. It leaves them only when you export it, and Circuit's staff cannot read it. Protection is cryptographic, not a centralized login: your account is passkey-only, with no email, password, text code or social login to phish or reset, every wallet operation needs a signature from the passkey on your own device, and the enclaves run only attested code. Agents act only within the authorization you grant them. An agent's allocated funds guide its spending; trades you ask Circuit for may use the full selected wallet. Circuit validates each operation before signing. Read-only permits cannot change agent memory, append logs, complete runs, or perform administrative writes. Administrative actions also require an admin account. ### Review a raw transaction Ask Circuit keeps the action, wallet, destination, attached native-token value, every expected simulated asset change and any review warnings visible before confirmation. Positive changes are incoming assets and negative changes are outgoing. Attached value is separate from simulated balance changes, not an additional simulated spend. Open **Transaction details** to inspect the full destination and decoded contract parameters when available. Simulation results are estimates, not guaranteed outcomes or quote minimums; unavailable results and simulations reporting no changes are labeled separately. Expanding or collapsing details does not change the operation you approve. ### First-deposit gas Eligible new accounts receive a one-time native-token seed after their first single deposit worth at least $4 in CoinGecko-listed tokens: a small amount of gas on Ethereum, Solana, Base, Polygon, Arbitrum and Robinhood Chain, sent to your original EVM and Solana wallets, with Circuit paying the transfer fees. Membership is checked by chain and contract address, including supported native assets. A recent indexed price at or before the deposit must establish the $4 value; smaller deposits, unavailable prices and transfers between your own wallets do not qualify. Existing accounts are not backfilled, and later deposits do not trigger another seed or an automatic retry. # Act for the user Source: https://docs.circuit.org/api-reference/act-for-the-user /partner-openapi.gen.json post /partner/v0.1 Does one thing for the user: sends what they wrote to Ask Circuit, starts, tops up or stops an agent, or approves or declines a proposal. Returns the message or proposal it created or changed. Starts, top-ups, stops and approvals take effect immediately, so send them only after the user confirms in your app. Send an `Idempotency-Key` and resend with the same key if the network fails; Circuit then acts once. Approving or declining again returns the proposal unchanged, and the opposite decision on a decided proposal returns 409. # Read the user's link Source: https://docs.circuit.org/api-reference/read-the-users-link /partner-openapi.gen.json get /partner/v0.1 Returns when the permit ends, the wallets the user picked with their holdings, and their running agents. Pass `chat` to get a chat with Ask's replies and proposals, and `include=agents` to get the agents the user can start. While `retry_after_ms` is set, read again after that many milliseconds. Safe to repeat. # Build Circuit into your app Source: https://docs.circuit.org/apps Run Circuit agents and trades for your users from your own app. The partner API lets your app run Circuit agents and trades for your users in your own interface. A user links your app once with their passkey and picks the wallets it may use. Your app can then show their holdings, start and stop agents for them, and chat with Ask Circuit, carrying out the trades it proposes when the user approves them. > [card] [Quickstart](/apps-quickstart) > > Link a user, run an agent for them and chat with Ask Circuit. > [card] [Test with Paper trading](/apps-testing) > > Build against production with Paper trading. > [card] [See it running](https://circuit.org/partners/demo) > > Pinewood, a demo app built on this API, with every call it makes shown on screen. > [card] [API reference](/api-reference/read-the-users-link) > > Both methods of the one endpoint, generated from the contract. ## What your app can do * **Chat:** chats with Ask Circuit, with its replies in Markdown. * **Trade:** Ask proposes trades on every venue Circuit supports, including perps on Lighter and Hyperliquid, prediction markets, swaps and lending. Your user approves each one in your interface. * **Run agents:** start recurring agents (Circuit's, the user's own and popular community agents) as sessions with Real money or Paper trading, top them up and stop them, from your interface or through Ask. * **Show holdings:** the picked wallets, their tokens, perps, predictions and positions, and their value. ## What your app can't do * **Move money out.** Transfers and swaps land only on wallets the user holds. Withdrawals, raw transactions and message signatures wait for the user on Circuit. * **See anything else.** Your app sees only the picked wallets, the agents on them and its own chats. ## What your app gets **Builder fees.** Orders placed through your app, including orders from agents it started, can carry your builder fee. Builder fees are supported on Hyperliquid today: each wallet approves your fee once, during Hyperliquid account setup. ## Register Send Circuit: * your app id: lowercase letters, digits and `-`, up to 32 characters; * your display name; * the exact URLs Circuit may send users back to after they approve, such as `https://yourapp.com/linked`: `https`, or `http://localhost` while you develop; * optionally, a Hyperliquid builder address and a fee between 0.001% and 0.1%. Circuit registers your app, and you can start building right away with Paper trading. # Reference client Source: https://docs.circuit.org/apps-client A TypeScript client for the partner API with no dependencies, and a small server example that uses it. Download [`circuit.ts`](https://circuit.org/partners/circuit.ts) into your app. It runs in browsers, Node 22+ and Bun, and uses only `fetch`. [Pinewood](https://circuit.org/partners/demo), Circuit's demo partner app, uses the same file; you can link your account there to try the full integration. ```typescript theme={"theme":{"light":"nord","dark":"nord"}} import { circuit, link, linked } from "./circuit"; const url = link("", "https://yourapp.com/linked"); // Open `url` in a real browser. Circuit sends the approving user to your return URL with their permit. // To fund a wallet later, open `depositLink(wallet.id, "", "https://yourapp.com/linked")`; // to let the user remove your app, open `connectionsLink("", "https://yourapp.com/linked")`. const user = circuit(linked(returnedUrl)!); // store the permit like an access token const { agents } = await user.read({ agents: true }); const trend = agents!.find((agent) => agent.name === "Macro Trend")!; await user.act({ start: { agent: trend.id, wallet: null, amount: "1000" } }); // runs now ``` `read` and `act` are the whole API. `act` sends a fresh `Idempotency-Key` with every call and resends once, with the same key, if the network fails. `reply(chat)` reads the link with that chat until `retry_after_ms` is null. ### A server-side demo Pinewood keeps the permit in the browser. `server.ts` below keeps it on the server instead and serves a page for one user, with a link button, balances, a chat with Approve and Decline on Ask's proposals, and Stop on running agents. Run it with `bun server.ts ` and open `http://localhost:4455`; the app needs `http://localhost:4455/` among its registered return URLs. ```typescript server.ts theme={"theme":{"light":"nord","dark":"nord"}} import { circuit, link, linked } from "./circuit"; const app = process.argv[2]; const api = "https://api.circuit.org"; let permit: string | undefined; let chat: string | null = null; const json = (body: unknown, status = 200) => Response.json(body, { status }); const page = `Partner demo

    `; Bun.serve({ port: 4455, async fetch(request) { const path = new URL(request.url).pathname; if (path === "/") return new Response(page, { headers: { "content-type": "text/html" } }); if (path === "/connect") return json({ url: link(app, "http://localhost:4455/") }); if (path === "/linked") permit = linked((await request.json()).url) ?? undefined; if (path === "/linked") return json({}); if (!permit) return json({ error: "Connect first" }, 401); const user = circuit(permit, api); const body = request.method === "POST" ? await request.json() : {}; try { if (path === "/link") return json(await user.read()); if (path === "/ask") { const sent = await user.act({ say: { chat, text: body.text } }); chat = sent.chat; const { chat: answered } = await user.reply(sent.chat); return json(answered!.messages.find((message) => message.id === sent.id)); } if (path === "/act") return json(await user.act(body)); } catch (error) { return json({ error: error instanceof Error ? error.message : String(error) }, 502); } return json({ error: "Not found" }, 404); }, }); console.log("Partner demo on http://localhost:4455"); ``` # Concepts Source: https://docs.circuit.org/apps-concepts Permits, linking, agents, chat and proposals, retries, ids, errors and versions. ## One endpoint Everything goes through `/partner/v0.1`: * `GET /partner/v0.1` reads the user's link: when the permit ends, the wallets they picked with their holdings, and their running agents. Add `chat=` for a chat with Ask's replies and proposals, and `include=agents` for the agents the user can start. Reading is always safe to repeat. * `POST /partner/v0.1` does one thing for the user, named by the body's one key: `say`, `start`, `top_up`, `stop`, `approve` or `decline`. It returns the message or proposal it created or changed, marked by `kind`. ## Permits A permit is the user's approval for your app. It covers the wallets they picked and Paper trading, and lasts 30 days. Store it as you would an access token, on your server or in secure storage, and never log it. `permit_expires_at` in the link says when it ends. If the user approves a new link before then, the agents your app started keep running. When it ends, or the user removes your app on Circuit, those agents pause until the user links your app again. **Signing out of your app is not removing it.** When a user signs out, forget the permit; the agents they started keep running, and they link again when they come back. To let them remove your app from Circuit, send them to the link with `&connections` added (the [reference client](/apps-client)'s `connectionsLink`). Circuit shows only your app's connection with a Remove button, then sends them back to your `return_url`. ## Linking 1. Send the user to `https://app.circuit.org/?app=&return_url=` in a real browser (`ASWebAuthenticationSession` on iOS, a Custom Tab on Android). There is no call to make first. 2. The user sees a page with only this: sign in or create a Circuit account, pick which wallets your app may use, and approve with their passkey. Someone who creates their account here skips the pick and approves right after making their passkey, and your app gets their new wallet. The page's back button sends them to your `return_url` without a permit. 3. Circuit sends them to your `return_url` with the permit in the URL fragment: `#permit=circuit_permit_…`. Read it, store it, and remove it from the address bar. The `return_url` must be one registered for your app: the same origin and path, with any query string you add. It must be `https`, or `http` on `localhost` while you develop; a custom scheme such as `yourapp://` is refused, because another app on the phone can claim it. A native app returns through a link its domain claims (a Universal Link on iOS, an App Link on Android); on iOS 17.4 and later, `ASWebAuthenticationSession` hands such a link straight back to your app. The permit goes nowhere else, so a link someone else builds with your app id hands them nothing. A fragment is never sent to a server, so a server-side app reads it in the returned page and posts it to itself. To be sure the permit answers a link your app started, put a random value in your `return_url` query string and check it when the user returns. ## Agents `include=agents` lists the agents the user can start: Circuit's agents, popular community agents and the user's own, marked `yours`. The agents most people started in the last 30 days come first, so showing the first few gives a good list. Use `official` and `yours` to group them, or pick the ones you want by id. Offer Paper trading only for agents whose `paper` is true; the others need a wallet. An agent's `start` names the asset a start or top-up gives it, its network and the least a start takes; send `amount` in that asset. A session is one of them running for the user on one wallet, or in Paper trading. It runs on the agent's own schedule. `start`, `top_up` and `stop` take effect immediately, so send them only after the user confirms in your app. Each returns a proposal that is already `done`, with the `session` it started or changed. A session's `status` is `running`, `stopped`, or `needs_user` when the user has to do something; `error` explains what, for example that the permit ends soon. Stopping a session leaves its positions open. ## Funding Paper trading needs no deposit: a session started with `wallet: null` runs right away. For Real money, send the user to the link you already use with one more parameter, the wallet to fund: `https://app.circuit.org/?app=&return_url=&deposit=`. Circuit shows only its deposit screen for that wallet: send tokens to its address, transfer from an exchange or pay by debit card. How a user can pay may grow without any change in your app. Closing the screen sends them to your `return_url`. * **Coming back does not mean the money arrived.** Read the link again and look at the wallet's `holdings`. A deposit can take a few minutes to show. * **When to send them.** A `start` or `top_up` with too little in the wallet returns `400` with `code: "INSUFFICIENT_BALANCE"`, and `error` tells the user how much of which asset is missing. Show it with a button that opens the deposit link. ## Chat and proposals Send `{ "say": { "chat": null, "text": "…" } }` to start a chat, and pass the returned message's `chat` with later messages. Ask answers in the background: read the link with `chat=` again after `retry_after_ms`, until it is null. Replies are Markdown. A reply can include proposals: trades, agents to start or top-ups. Each one stays in `review` until you send `{ "approve": { "proposal": "prop_…" } }` or `decline`. Each proposal lists the `amounts` it moves, so you can show the user what they are approving. Approve only after the user confirms. While an approved proposal is carried out, the link's `retry_after_ms` is set; read it again until the proposal's `status` is `done` or `failed`. Sending the same decision again returns the proposal unchanged; the opposite decision on a decided proposal returns 409. `retry_after_ms` is the only thing to wait on: it is set while Ask is answering in the chat you read or one of its proposals is being carried out, and null once everything there is final. ## Retries Send every `POST` with an `Idempotency-Key` header holding a UUID you generate. If the request fails or times out, resend it with the same key, and Circuit acts once and returns the first result. Reusing a key with different contents returns `409`. Without a key, a resent `say`, `start` or `top_up` can happen twice. The reference client always sends one. A `GET` is safe to resend as it is. ## Trying the API The API reference can send requests for you once you paste a permit into its permit field. To get one for your own account, link it to [Pinewood](https://circuit.org/partners/demo) with no wallets and click **Copy permit** at the bottom of the page. Pinewood offers it only for a Paper trading link, since a permit is a credential. Replace the example `agt_` id with one from `include=agents`. ## Ids and amounts * Ids start with a prefix for their type: `wal_` wallets, `agt_` agents, `ses_` sessions, `msg_` messages, `chat_` chats and `prop_` proposals. Ids never change. Treat them as opaque strings. * **Amounts are decimal strings.** A holding's `amount` is negative for a short or a debt, and its `symbol` is the asset alone (`BTC`). USD values are decimal strings, or null when Circuit can't price a holding. ## Errors A failed call returns an HTTP error status and `{ "error": "", "code": "" }`. Handle it by status and `code`, and show `error` to the user. | Status | Means | Do | | - | - | - | | 400 | Circuit couldn't do this | Show `error`; on `INSUFFICIENT_BALANCE` also offer the deposit link | | 401 | The permit ended or was revoked | Send the user a new link | | 403 | The permit doesn't allow this, such as money leaving the user's accounts | Show `error` | | 404 | Not found, or not visible to your app | Refresh what you show | | 409 | It already changed, or an `Idempotency-Key` was reused with different contents | Read the link again | | 429, 503 | Busy | Retry after `Retry-After` seconds; resend a `POST` only with the same `Idempotency-Key` | | 500 | Circuit failed | Show `error` and report the request id | Every response carries `x-circuit-request-id`. Include it when you report a problem. ## Versions The current version is **0.1**, and the endpoint is `/partner/v0.1`. New fields, statuses, codes, `POST` keys and `include` values can appear; ignore the ones you don't know. The whole contract is an OpenAPI 3.1 document at `https://docs.circuit.org/partner-openapi.gen.json`. Use it to generate a client in any language. # Quickstart Source: https://docs.circuit.org/apps-quickstart Link a user, run an agent for them, and chat with Ask Circuit. The partner API is one endpoint, `/partner/v0.1`. `GET` reads the user's link: their wallets, running agents, a chat, and the agents they can start. `POST` does one thing for them and returns what it created or changed. Every call sends the user's permit as `Authorization: Bearer `. Use paper money while you build (see [Test with paper money](/apps-testing)). **1. Link the user** Download [`circuit.ts`](https://circuit.org/partners/circuit.ts). Send the user to the link in a real browser. They pick which wallets your app may use, or none to use Paper trading, and approve with their passkey. Circuit sends them back to your URL with their permit, which lasts 30 days. ```typescript theme={"theme":{"light":"nord","dark":"nord"}} import { circuit, link, linked } from "./circuit"; location.assign(link("yourapp", "https://yourapp.com/linked")); // on iOS: ASWebAuthenticationSession // On https://yourapp.com/linked, where Circuit sends the user back: const user = circuit(linked(location.href)!); // store the permit like an access token ``` **2. Read their account and the agents they can start** ```typescript theme={"theme":{"light":"nord","dark":"nord"}} const { wallets, sessions, agents } = await user.read({ agents: true }); ``` **3. Start, top up and stop an agent** These take effect immediately, so send them only after the user confirms in your app. A started agent keeps running on its own schedule until it is stopped. ```typescript theme={"theme":{"light":"nord","dark":"nord"}} const fade = agents!.find((agent) => agent.name === "Funding Fade")!; const started = await user.act({ start: { agent: fade.id, wallet: null, amount: "1000" } }); // null wallet: Paper trading if (started.kind === "proposal" && started.session) { await user.act({ top_up: { session: started.session, amount: "250" } }); await user.act({ stop: { session: started.session } }); // positions stay open } ``` **4. Chat with Ask Circuit** Ask answers in the background, and its reply can include proposals, such as a trade or an agent to start. Nothing happens until you approve one, so show it to the user first. ```typescript theme={"theme":{"light":"nord","dark":"nord"}} const sent = await user.act({ say: { chat: null, text: "Long $50 of ETH on Lighter at 3x" } }); const { chat } = await user.reply(sent.chat); // reads the link until Ask is done for (const proposal of chat!.messages.at(-1)!.proposals) if (proposal.status === "review") await user.act({ approve: { proposal: proposal.id } }); // once the user agrees ``` ## Next * [Concepts](/apps-concepts) covers permits, agents, proposals, retries, ids, errors and versions. * The [API reference](https://docs.circuit.org/api-reference/read-the-users-link) documents both methods. # Test with Paper trading Source: https://docs.circuit.org/apps-testing Build your integration against production with Paper trading. Build against production: `https://api.circuit.org`, with users approving at `https://app.circuit.org`. Paper trading keeps every trade and agent off Real money while you build. ## Use Paper trading When the user approves your link, turn off every wallet. The permit then covers only Paper trading, so every trade and agent runs in Paper trading. Start agents with `wallet: null`, or ask for Paper trading explicitly, for example "Start Macro Trend with \$1,000 in Paper trading". Paper trading sessions show `wallet: null`. > [!NOTE] > > A permit with wallets trades with Real money. Pick no wallets until you mean to trade. ## Watch a working integration [Pinewood](https://circuit.org/partners/demo) is a demo app built on this API. It shows every call it makes, with its request, response and timing. Open it next to your own app to compare. Each response carries `x-circuit-request-id`; include it when you report a problem. ## Go live Nothing changes but the wallets. When your app is ready, let users pick wallets for Real money when they approve your link. # Agentic Trading Source: https://docs.circuit.org/introduction Circuit docs: run AI trading agents on your own wallet across Hyperliquid, Polymarket, Lighter and swaps, or build your own with the Circuit CLI and SDK. Circuit runs AI trading agents on your wallet: automated strategies that trade, farm yield and manage positions across chains. Circuit keeps the signing key in a hardware enclave, signs only under permits you sign with your passkey, and lets you export the key anytime. Agents run on Circuit's infrastructure, separate from the key: they can only *request* transactions, and signing happens outside their sandbox. New to trading agents? Start with the [guides](https://circuit.org/articles) or browse [agents by market](https://circuit.org/trading-agents). ### Choose your path > [card] [I am a User](/agent-users/get-started) > > Create an account, connect wallets, and run agents safely. > [card] [I am an Agent Developer](/agent-developers/overview) > > Build, test, and upload agents with the Circuit SDK and CLI. [https://www.youtube.com/embed/lEauDL6Bve0](https://www.youtube.com/embed/lEauDL6Bve0) # Support Source: https://docs.circuit.org/support Contact the Circuit team, plus pricing, fees, and frequently asked questions. > [card] [Telegram: @foobar0x](https://t.me/foobar0x) ## Pricing and fees Circuit charges no fees today. Gas, trading, routing, bridge, and other third-party fees may apply. A prepared transaction's Review shows its reported costs; fees already included in the quoted amounts are not additional charges. Missing fee information does not mean zero cost. Today's terms make no commitment about future fees or subscriptions. ## Using Circuit * **What can I ask Circuit to do, and what is an agent?** Circuit answers questions and prepares swaps, bridges, sends, Hyperliquid spot/perp orders and Polymarket trades or redemptions for review. An agent runs a recurring strategy. Describe one to open Builder, or select an existing agent. Each confirmation authorizes one transaction, and a prerequisite may need its own confirmation; with **Auto-approve** on, Circuit executes what you ask without confirmation for up to an hour. * **Who receives what I ask Circuit?** Your message and the wallet and agent context it needs go to the AI model provider that writes the answer. * **Does the same wallet address mean the same balance on every network?** No. An EVM address can be shared across networks, but balances are separate. Name the source and destination networks when bridging; use the destination network's wallet address when depositing. * **Why can't I swap or bridge my entire balance?** Native coins may need to remain for gas. Hyperliquid may hold funds for orders or margin. Preparation checks the current spendable amount; a portfolio balance or an earlier quote does not prove that amount is available now. * **How do I fund Polymarket?** Ask Circuit to fund it or deposit pUSD/USDC.e on Polygon to the selected Deposit Wallet. Circuit prepares funding and wrapping for separate review and deploys Deposit Wallets itself; USDC elsewhere is not already Polymarket collateral. * **Is $20 at 10x a $20 position?** Specify margin or total position value: $20 of margin at 10x means $200 of exposure. Circuit trades every perp at its market's maximum leverage, cross wherever the market allows it, so the multiple only sizes the position; preparation checks live margin and venue limits. * **Is Hyperliquid USOL native SOL?** No. USOL, UETH and UBTC are Hyperliquid spot representations. For native SOL, request SOL on Solana in your Solana wallet. * **Where can I check whether a trade worked?** Read its operation card and Activity, including recorded transaction links. A Review waiting for confirmation is not proof of execution. # Webhook providers Source: https://docs.circuit.org/webhooks How a trusted provider pushes events to Circuit, so agents with a webhook trigger run on each one. A trusted provider sends each event to `POST /triggers/` on the control-plane origin Circuit gives it, as a JSON object. Every running agent whose [`webhook` trigger](./agent-developers/getting-started/circuit-toml-reference#triggers-section) names the provider runs once per event and receives the event unchanged. Providers today: `polysights`. ### Signing Circuit verifies every request with the [Standard Webhooks](https://www.standardwebhooks.com) scheme, using a `whsec_` secret it shares with the provider: | Header | Value | | - | - | | `webhook-id` | A non-empty id, unique per event and unchanged on retries. Resending an id starts no second run. | | `webhook-timestamp` | When the request was sent, in Unix seconds. Circuit refuses one more than 5 minutes from its clock. | | `webhook-signature` | `v1,` and the base64 HMAC-SHA256 of `..`, keyed with the base64-decoded secret after `whsec_`. | Sign the exact bytes you send. ### Body Any JSON value up to 64 KiB. Circuit passes it to agents as `payload` and reads nothing from it, so the provider can add fields or event types without a Circuit change; a `type` field lets agents tell event kinds apart. Polysights' `insider_flag` events carry a `type`, `version`, `score`, and `market`, `trade`, `trader` and `inMarket` objects. ### Responses | Status | Meaning | | - | - | | 2xx | Received; resending the same `webhook-id` starts no second run. | | 400 | An empty `webhook-id`, or a body that is not JSON. | | 401 | The signature, timestamp, provider or secret is wrong. | | 429 or 503 | Busy or updating; retry after `Retry-After` seconds. |