diff --git a/CANARY.md b/CANARY.md index 5a20112..3df47bd 100644 --- a/CANARY.md +++ b/CANARY.md @@ -124,8 +124,10 @@ lock therefore means a flaw in the contract, the NEAR runtime or the exchange. ### The deployer's upgrade key, and the integrity check -The deployer keeps a full-access key on `vault.intatto.near`, so the funds in this hackathon -deployment stay recoverable. That key can replace the contract's code, and with it any rule above. +The deployer keeps a full-access key on `vault.intatto.near` on purpose: the contract is not audited yet, +and without an upgrade key a bug found later could never be fixed, leaving any funds it affected +stuck for good. Owners withdraw with their own keys, not this one; it is removed after an external +audit. That key can replace the contract's code, and with it any rule above. Everyone using the vault, the canary included, trusts whoever holds it. So the canary is tied to a code hash. **If vault.intatto.near's code hash changes, the current @@ -252,8 +254,10 @@ lock therefore means a flaw in the contract, the NEAR runtime or the exchange. ### The deployer's upgrade key, and the integrity check -The deployer keeps a full-access key on `vault-v1.intatto-dev.testnet`, so the funds in this -hackathon deployment stay recoverable. That key can replace the contract's code, and with it any +The deployer keeps a full-access key on `vault-v1.intatto-dev.testnet` on purpose: the contract is not audited yet, +and without an upgrade key a bug found later could never be fixed, leaving any funds it affected +stuck for good. Owners withdraw with their own keys, not this one; it is removed after an external +audit. That key can replace the contract's code, and with it any rule above. Everyone using the vault, the canary included, trusts whoever holds it. So the canary is tied to a code hash. **If vault-v1's code hash changes, the current canary run diff --git a/CHAIN_SIGNATURES.md b/CHAIN_SIGNATURES.md index c607b20..4351908 100644 --- a/CHAIN_SIGNATURES.md +++ b/CHAIN_SIGNATURES.md @@ -1,14 +1,15 @@ -# Chain Signatures intents path (branch `chain-signatures`) +# Chain Signatures intents path An agent swap through NEAR Intents. The vault's own account on `intents.near` is signed for by the MPC network (`v1.signer`, domain 1, Ed25519). The agent picks a pair and two amounts. The vault checks them against the owner's policy, then builds the NEP-413 `token_diff` itself, has -it signed, and settles it by asking `intents.near` whether the nonce was used. Master does not -depend on any of this. +it signed, and settles it by asking `intents.near` whether the nonce was used. The code is in +master (`src/intents.rs`, `src/intent_swap.rs`); the canary's `vault.intatto.near` runs an earlier +build without it. Invariants 14 to 18 and the trust assumptions (MPC 11-of-16, intents.near governance, the vault account's full-access key) are in -[THREAT_MODEL.md](THREAT_MODEL.md#chain-signatures-intents-path-branch-chain-signatures-live-on-mainnet). +[THREAT_MODEL.md](THREAT_MODEL.md#chain-signatures-intents-path-live-on-mainnet). ## Live on mainnet, 2026-11-11 diff --git a/GTM.md b/GTM.md new file mode 100644 index 0000000..86be1e3 --- /dev/null +++ b/GTM.md @@ -0,0 +1,116 @@ +# Intatto: go-to-market plan + +Status on 2026-11-13: live on NEAR mainnet (`vault.intatto.near`, `intents.intatto.near`), one +public canary, fee collection proven on mainnet, no outside users yet. This plan says who the first +users are, how they find Intatto, what it costs them, and what we measure. Every number below that +describes the product today links to a transaction or a file; everything else is a target and says +so. + +## The problem, for one user + +A trading agent needs a key to trade. Today that is the key to its whole wallet: one bug, one +leaked environment file or one prompt injection and the wallet is gone. Intatto gives the agent its +own trading account instead: a vault it can trade from, inside limits the contract enforces, and +can never withdraw from. The agent's key can be stolen and the money stays. + +## First customer + +**Builders who run trading agents on NEAR today**, with a hot full-access key, through Rhea or NEAR +Intents. Solo developers and small teams running bots for themselves or a few clients. + +Why them first: + +- They already hold the exact risk Intatto removes, and already trade the venues it supports + (Rhea pools, NEAR Intents). +- Switching costs them almost nothing: their strategy stays the same; only the signer changes, from + a full-access key to a vault-only function-call key. +- They are findable: in the NEAR builder channels, the NEAR AI Agent Market, and the repositories of + this hackathon's agent tracks. + +**Second segment: teams putting AI agents in charge of a treasury** (DAOs, agent-run businesses, +payroll and payment agents). Same product, `agent_spend` instead of `agent_swap`, with the receiver +allowlist doing the work. + +**Not now:** retail users who want a managed trading bot. Running their agent would mean holding its +key, which is the risk Intatto exists to remove. + +## Why they switch + +| Today | With Intatto | +|---|---| +| The agent's key can withdraw everything | The key can only call the vault's agent methods; it cannot attach a deposit, so it cannot withdraw ([exact limits](README.md#the-agents-function-call-key-exact-limits)) | +| Limits live in the agent's own code, which the attacker controls | Limits live in the contract: caps per trade and per day, pools, pairs, slippage against the exchange's own quote, price floors | +| A compromised agent is found after the money left | The owner freezes the vault in one call; every refused call is on chain with its reason | +| "Trust our code" | The running code is checked live against its reproducible build, and the agent's key is public on mainnet with real NEAR behind it | + +## Distribution, cheapest first + +1. **Where agents are built.** The MCP server ([agent/mcp-server.mjs](agent/mcp-server.mjs)) puts the + vault into Claude, ChatGPT, Cursor, Codex and any MCP client as four tools, with a pre-trade + check that blocks bad swaps before they are signed. No package to install: one command adds it. + Next: publish it to npm and to the MCP registries. +2. **The canary as the standing proof.** "The key is public. The money is still here." A live page, + a counter of refused attempts, and a reason for anyone to come and try. Each new refusal is a + post. +3. **NEAR AI Agent Market.** List a reference Intatto trading agent, so agents hired there can + trade with a vault instead of a key. +4. **Build in public on X** from the project account: each mainnet milestone with its transaction + link (first outside vault, first outside attack refused, audit, key removal). +5. **Hand onboarding of design partners.** Ten trading-bot builders, set up one by one, in exchange + for feedback and a public case study. + +## Pricing + +- **0.10% (10 bps) of the output of every agent swap**, taken by the contract and fixed in its code + ([src/fees.rs](src/fees.rs)); no method can change it. Proven on mainnet: the smoke test's swap + [`JAFaEDBh…`](https://nearblocks.io/txns/JAFaEDBhStuPgwgCyNJKU7mQH2K7evjG328zrhudoaC8) paid + 0.001887 USDt to the treasury. +- No subscription, no fee on deposits, withdrawals, payments or refused calls. +- Costs, stated plainly: the owner pays the vault's storage (about 0.0015 NEAR to open one) and the + agent pays its own gas (about 0.0036 NEAR per completed swap). The operator's fixed cost is the + contract's storage stake, about 2.55 NEAR ([Unit economics](README.md#unit-economics)). Each new + vault costs the operator nothing per call. +- What it means: at 10 bps, 1,000,000 USD of monthly agent swap volume pays 1,000 USD a month. The + fee only matters at volume, which is why distribution goes where agents are built. + +## Launch sequence + +| When | What | Done when | +|---|---|---| +| Hackathon (to 2026-11-14) | Mainnet proof: canary, smoke test, intent swap, MCP server, pre-trade check | Live (this repository) | +| Weeks 1 to 4 | Ten design-partner bots onboarded by hand; MCP server on npm | Ten outside vaults with an agent that has traded | +| Weeks 4 to 8 | External audit of the contract | Audit report published | +| After the audit | Both upgrade keys removed; the canary's bounty raised; public launch | `list-keys` shows no full-access key on either vault | +| Next | More Rhea pairs and intent pairs, chosen by liquidity; a reference agent on the Agent Market | Listed | + +## What we measure + +| Metric | Why | +|---|---| +| Value under policy (all vault balances) | The money that is no longer one key away from gone | +| Agent swap volume, and fee revenue | The business | +| Outside vaults with an agent that has traded | Real adoption, not sign-ups | +| Refused calls, by reason | The product working; each is a loss that did not happen | +| Time from connect to first agent trade | Onboarding; target under 10 minutes | +| Canary attempts, and breaks (target: 0) | The public proof | + +All of these are on chain or derived from the vault's own events; the board already shows the +canary's. + +## Partners, and what is in it for them + +| Partner | Their gain | +|---|---| +| Rhea | Agent swap volume through its pools, from agents that would otherwise not be trusted with keys | +| NEAR Intents | Volume through solvers, signed for the vault by the MPC network | +| NEAR AI | TEE-attested trade decisions recorded on chain with each trade, as a showcase | +| NEAR AI Agent Market | Agents that can be hired to trade without being handed a wallet key | + +## Risks + +| Risk | Answer | +|---|---| +| A contract bug | The public canary, an external audit before keys are removed, and caps that bound what any bug can lose per day | +| Low trading-agent volume on NEAR | The treasury segment uses the same vault with `agent_spend`; the intents path reaches other chains' assets | +| Copies of the spending-limit idea | Intatto's edges are the trading policy (slippage against the exchange's quote, intent price floors, MPC-signed intents) and the proof (public key on mainnet, reproducible build checked live), not the idea of limits | +| Upgrade keys today | Disclosed in the README and THREAT_MODEL.md, checked live on the board, removed after the audit | diff --git a/INTEGRATE.md b/INTEGRATE.md new file mode 100644 index 0000000..4dd7583 --- /dev/null +++ b/INTEGRATE.md @@ -0,0 +1,96 @@ +# Integrating an agent with Intatto + +Three ways to put an agent on an Intatto vault, from least to most code. In all three, the agent +holds a key that can only call the vault's agent methods, and the vault contract enforces the +owner's policy on every call. + +## Before you start (the owner, once) + +1. Open the owner console at [intatto.pages.dev/#/vault](https://intatto.pages.dev/?network=mainnet#/vault), + connect the owner's wallet and deposit. The console's setup checklist shows each step. +2. Name the agent account and its limits (`set_agent`): per-trade and daily caps per token, the + pools it may use, and the slippage it may accept against the exchange's quote. +3. Give the agent account a function-call key for the vault's agent methods only. **Signs a mainnet + transaction**, with the agent account's own key (near-cli-rs 0.30.1): + +```bash +near account add-key grant-function-call-access --allowance '1 NEAR' \ + --contract-account-id vault.intatto.near --function-names agent_spend,agent_swap \ + autogenerate-new-keypair save-to-legacy-keychain network-config mainnet sign-with-legacy-keychain send +``` + +The new key's file is the agent's credential. It can trade within the policy; it cannot withdraw +or change the rules. + +## 1. From an AI assistant: the MCP server + +[agent/mcp-server.mjs](agent/mcp-server.mjs) gives any MCP client (Claude Code, Claude Desktop, +ChatGPT, Cursor, Codex) four tools: + +| Tool | What it does | Signs | +|---|---|---| +| `intatto_vault_status` | Balances, freeze, withdrawal lock, policy, and what is left of today's caps | No | +| `intatto_check_agent_key` | Whether the configured key can only call the vault's agent methods | No | +| `intatto_check_swap` | Allow, warn or block for a planned swap, with reasons and a suggested minimum output | No | +| `intatto_swap` | Runs the check, then signs `agent_swap`; refuses on block, needs `acknowledge_warnings` on warn | Only with `INTATTO_ALLOW_TRADES=1` | + +Node 22 or later, no packages to install. From a clone of this repository, in Claude Code. Reads +the network when a tool runs; signs only through `intatto_swap` with trades enabled: + +```bash +claude mcp add --transport stdio intatto --env INTATTO_NETWORK=mainnet --env INTATTO_VAULT_ID=vault.intatto.near \ + --env INTATTO_OWNER_ID= --env INTATTO_AGENT_ID= \ + --env INTATTO_AGENT_KEY_FILE= -- node ./Intatto/agent/mcp-server.mjs +``` + +Other clients take the same command and environment in their MCP configuration. Without +`INTATTO_ALLOW_TRADES=1`, `intatto_swap` returns the exact call it would make and sends nothing; +start that way. The key file stays on your machine: no tool returns it, and the server runs every +output through the same redaction as the demo agent ([agent/secrets.mjs](agent/secrets.mjs)). + +The server speaks MCP over stdio in both eras: clients that open with `initialize` (protocol +2025-11-25 and earlier) and clients that send the protocol version on every request (2026-07-28), +with `server/discover`. Tests: [agent/mcp-server.test.mjs](agent/mcp-server.test.mjs). + +## 2. From your own agent: the pre-trade check + +[agent/risk-check.mjs](agent/risk-check.mjs) is the check the MCP server runs, as a library with no +dependencies. Call it before you sign: + +```js +import { Chain } from "./agent/intent-swap.mjs"; +import { assessSwap, gatherSwapFacts } from "./agent/risk-check.mjs"; + +const chain = new Chain("https://rpc.mainnet.fastnear.com/"); +const facts = await gatherSwapFacts(chain, { + vaultId: "vault.intatto.near", ownerId, agentId, agentPublicKey, + poolId, tokenIn: "wrap.near", tokenOut: "usdt.tether-token.near", + amountIn: "500000000000000000000000", minAmountOut: "1", +}); +// With no minimum of your own, take the check's suggestion: at most 0.5% under the exchange's quote. +const minAmountOut = wanted ?? assessSwap({ ...facts, minAmountOut: "1" }).suggestedMinOut; +const { verdict, reasons } = assessSwap({ ...facts, minAmountOut }); +if (verdict === "block") throw new Error(reasons.map((r) => r.message).join(" ")); +``` + +| Verdict | Means | +|---|---| +| `block` | The vault would refuse it (not the agent, frozen, pool or pair not allowed, over a cap or the 24-hour count, slippage past the policy, no quote, not enough balance), or the risk is too high: price impact over 5% against a 1% probe of the same pool, or a signing key that is a full-access key | +| `warn` | It would go through, but: price impact over 1%, a minimum output looser than half the policy's slippage, a cap or count over 80% used, or a token whose account has a full-access key (whoever holds it can replace the token's code) | +| `allow` | None of the above | + +The check reads state that can change before the swap lands, so the contract stays the last word: +a swap the check allows can still be refused on chain, with the reason in a `swap_rejected` event. +Tests: [agent/risk-check.test.mjs](agent/risk-check.test.mjs). + +## 3. Any signer: call the vault directly + +Any code that can sign a NEAR transaction can call `agent_swap` (and `agent_spend`) with the agent's +function-call key. The methods, their arguments and every refusal are in the README's +[Bring your own agent](README.md#bring-your-own-agent). The reference signer, with no dependencies, +is [agent/near-tx.mjs](agent/near-tx.mjs). + +## What Intatto does not do + +It does not run your agent. If it did, it would hold the agent's key, which is the risk the vault +exists to remove. diff --git a/README.md b/README.md index 379ef0a..c84015a 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,15 @@ Author: [UEddy](https://github.com/UEddy) **The agent's key is public. Take the money if you can.** +The key is public on mainnet with real NEAR behind it, the code running the vault is checked live +against its reproducible build, and an AI assistant can trade through it with one command +([INTEGRATE.md](INTEGRATE.md)). How it reaches its first users: [GTM.md](GTM.md). + +**Track: AI Security & Defense.** Spending limits and a policy engine enforced by the contract, a +sandboxed wallet the agent can trade from but never withdraw from, NEAR function-call keys, and AI +decisions with TEE attestation receipts: an AI agent gets money without getting the keys to it. +Also entered in Unstoppable DeFi and Agent Economy ([Tracks](#tracks)). + To prove it, we published the agent's key with a real NEAR bounty on it: the canary is an AI agent's vault on NEAR mainnet holding 0.99761 NEAR, and its key is in [CANARY.md](CANARY.md). Sign with it, pick any receiver and any amount, call `agent_spend` or `agent_swap` as often as you like: the transactions go through the vault @@ -20,6 +29,16 @@ NEAR). The bounty is small because one person funds it. The amount does not chan contract applies the same checks to every call, so the policy that refuses these 0.99761 NEAR refuses any balance. +## Judge it in 60 seconds + +1. **The bounty and the public key.** Open [intatto.pages.dev](https://intatto.pages.dev/?network=mainnet). The panel at the top is read live from the chain: the canary's balance, how long it has held, every attempt with the published key, and whether the running code matches the published build. The private key is in [CANARY.md](CANARY.md#mainnet). +2. **What a refusal looks like.** The agent's calls refused on mainnet: [over the per-trade cap](https://nearblocks.io/txns/8o7EGQoMWfxUzeST7cTzA63J5MzvxB5ZiWk4NENa8XHU), [a pool not allowed](https://nearblocks.io/txns/G5d3Fu838aDw5SSpRvh694TpHLKLg6Vk4LVZRJzssekc), [slippage too loose](https://nearblocks.io/txns/CEpq15YceDiwqHWtpUszmZH8LegBoyyZzgrdJ8HRaEck), and a prompt-injected agent [trying to drain the vault](https://nearblocks.io/txns/FNkp2gprgvRs49L6wskMo8JcaYwpoqk2T3YVjGa6oqtw). +3. **A trade that went through, then the owner's withdrawal.** A Rhea [swap within the limits](https://nearblocks.io/txns/JAFaEDBhStuPgwgCyNJKU7mQH2K7evjG328zrhudoaC8), the owner [withdrawing the proceeds](https://nearblocks.io/txns/2tqfhEiJm1jqAe6DNDZBFnfzbHZqfnmThVfFmJToFtYW), and a NEAR Intents swap [settled](https://nearblocks.io/txns/73aJTu55356n6QGvcLuj8h5vHy5cY1PGcvGzprM42uKE) above the owner's price floor. +4. **The freeze.** The owner [freezes the vault](https://nearblocks.io/txns/6YRqjJXZcNuyeHHSnAeMoURtT6vHfG44VpGJ34uDBCk2) in one call, and the agent's next trade is [refused](https://nearblocks.io/txns/7bm6uGYGGJG3hJnuJQYoFfxBckCp6Qasvs5fVHzSW3Li). +5. **The code is the published code.** The board's integrity check compares `vault.intatto.near`'s code hash with the [reproducible build](#what-is-deployed) every 10 seconds. + +**Two ways the agent trades.** The *Rhea path* swaps directly through Rhea pools, checked against the owner's caps, pool allowlist and a slippage bound set by the exchange's own quote. The *NEAR Intents path* has the vault's intents signed by the NEAR MPC network, only for pairs the owner allows and never below the owner's price floor. + Today most trading bots hold your private key. In September 2024, attackers exploited a flaw in the Telegram trading bot Banana Gun and drained about $3 million from 11 users' bot wallets; because the bot held the keys, every transfer was a valid signed transaction that nothing on chain could refuse. The team refunded the users from its treasury.[^banana-gun] Intatto removes the key from the bot: the agent signs only calls the vault's policy allows, and the money stays in a contract it cannot empty. That is what Intatto does: a NEAR contract that holds an owner's NEAR and NEP-141 tokens and lets @@ -47,6 +66,18 @@ trust the operator's custody of those keys: - Both keys will be removed after an external audit ([After the hackathon](#after-the-hackathon)), which makes the code permanent. +### Why the upgrade keys stay until the audit + +This is a deliberate choice, not an oversight. The +contract has not been audited. Without an upgrade key, a bug found later could never be fixed, and +any funds it affected would be stuck for good: a flaw in the withdraw path, or the exchange's +"lostfound" edge case ([THREAT_MODEL.md](THREAT_MODEL.md#known-limitations)), which only a code +upgrade can recover. Keeping the key keeps every owner's money recoverable while the code is +unaudited. The cost is trust in the operator, and that is what the board measures: any new code +shows as **CODE CHANGED** within 10 seconds. Owners do not need this key to get their money out; +they withdraw through the contract with their own accounts' keys. Once an external audit is done, +both keys are removed and the code can never change again. + The repository has four parts: the vault contract (`src/`), including agent swaps through NEAR Intents signed by the MPC network ([CHAIN_SIGNATURES.md](CHAIN_SIGNATURES.md)); a web app with an owner console and the public canary board (`web/`); the agents (`agent/`): the prompt-injection @@ -69,7 +100,7 @@ and an optional time lock on the owner's own withdrawals. | Public canary (published agent key) | **Live** since 2026-11-11: 0.99761 NEAR, locked until 2026-11-20, no attempts yet | **Live** since 2026-11-06: 0.9974 NEAR on `vault-v1` (no fee), locked until 2026-12-06, no attempts yet | | Agent swaps through Rhea (Ref V1), within on-chain limits | **Live**: [smoke test](#mainnet-smoke-test-2026-11-11) 18/18 on 2026-11-11 | **Live** on vault-v1 and vault-v2 | | Agent swaps through NEAR Intents, signed by the MPC network | **Live**: `intents.intatto.near`, [one swap settled](#first-intent-swap-2026-11-11) on 2026-11-11 | Not available (mainnet only) | -| Prompt-injection demo | Not deployed | **Live** on vault-v2 ([agent/README.md](agent/README.md)) | +| Prompt-injection demo | **Run** on 2026-11-12 on `demo.intatto.near`'s vault ([results](#prompt-injection-attack-the-agent-was-told-to-drain-the-vault)); its key was private and has been deleted | **Live** on vault-v2 ([agent/README.md](agent/README.md)) | | Break-price board and owner console | **Live** at [intatto.pages.dev](https://intatto.pages.dev/?network=mainnet), the default | **Live** on the same site (network switch, or `?network=testnet`) | | Wallets | Meteor, Intear, HOT, MyNearWallet | Meteor, Intear | | Passkey sign-in | **Experimental**: sign-in verified on a phone (2026-11-12); signing transactions with a passkey not yet tested. Unaudited Trezu wallet contract, upgradeable by Trezu; use small amounts only. See [THREAT_MODEL.md](THREAT_MODEL.md#passkey-sign-in-mainnet-only-experimental). | Not available (mainnet only) | @@ -307,8 +338,8 @@ git checkout master The web app's and the demo agent's tests run separately. Run each line from the repository root: ```bash -(cd web && npm ci && npm test) # offline: 190 unit tests in 23 files (vitest), 2026-11-12 -node --test agent/*.test.mjs # offline, after the line above: 29 tests: the demo agent's transaction signer, secret redaction and RPC errors, the intent swap agent, the AI decision receipts +(cd web && npm ci && npm test) # offline: 198 unit tests in 25 files (vitest), 2026-11-13 +node --test agent/*.test.mjs # offline, after the line above: 49 tests: the demo agent's transaction signer, secret redaction and RPC errors, the intent swap agent, the AI decision receipts, the pre-trade check, the MCP server (cd web && npx playwright install chromium && npm run test:prod) # reads the network: the Cloudflare build under its real CSP, against live mainnet and testnet (Playwright) ``` @@ -478,6 +509,18 @@ per `per_in`). It also refuses every agent call while the vault is frozen, and a account other than the registered agent. The reference implementation is [agent/](agent/README.md): a NEAR transaction signer with no dependencies, the prompt-injection demo, and the intent-swap agent. +### From an AI assistant (MCP), with a check before every swap + +[agent/mcp-server.mjs](agent/mcp-server.mjs) gives Claude, ChatGPT, Cursor, Codex or any MCP client +the vault as four tools: `intatto_vault_status`, `intatto_check_agent_key`, `intatto_check_swap` and +`intatto_swap`. Before every swap it runs a pre-trade check ([agent/risk-check.mjs](agent/risk-check.mjs)) +that returns allow, warn or block with reasons: every refusal the contract would make, plus what +the contract does not judge (price impact against a 1% probe of the same pool, a token whose +account has a full-access key, a signing key that can do more than call the vault). It blocks bad +swaps before they are signed and sends nothing at all until the server runs with +`INTATTO_ALLOW_TRADES=1`. Setup, the check's rules and how to use it from your own agent: +[INTEGRATE.md](INTEGRATE.md). + ## Unit economics Measured on testnet, where the gas price is 100,000,000 yoctoNEAR per gas unit, the same as on @@ -541,8 +584,9 @@ canary and the board at [intatto.pages.dev](https://intatto.pages.dev/?network=m - **More venues and pairs.** The policy already takes any list of Rhea pools and intent pairs; next are more pairs on both paths, chosen by liquidity. - **Agents that owners run themselves.** Intatto does not run agents, because running one would - mean holding its key. Next is a template an owner deploys on their own infrastructure, built on - [agent/](agent/README.md) and the [Bring your own agent](#bring-your-own-agent) interface. + mean holding its key. The MCP server already lets an owner's own AI assistant trade through the + vault ([INTEGRATE.md](INTEGRATE.md)); next is publishing it to npm and a reference agent on the + NEAR AI Agent Market ([GTM.md](GTM.md)). - **Passkeys end to end.** Signing transactions with a passkey, tested and documented, before passkey wallets are recommended for more than small amounts. @@ -552,15 +596,26 @@ per call. ## Tracks -- **AI Security & Defense (`security`), primary.** The agent's key is public and the money is - still there: the canary invites anyone to drain it with the published key, and the board shows - every attempt and the contract's reason for refusing it. On mainnet, an agent that obeyed a prompt - injection telling it to drain its vault was refused by the contract every time it tried - ([Prompt-injection attack](#prompt-injection-attack-the-agent-was-told-to-drain-the-vault)), and - the model's trade decisions carry receipts from an attested TEE - ([AI decisions, verifiable](#ai-decisions-verifiable)). The deployed code is checked live against - its reproducible build, and every trust assumption is written down in - [THREAT_MODEL.md](THREAT_MODEL.md). +- **AI Security & Defense (`security`), primary.** What the track asks for, and where it is here: + - *Spending limits and a policy engine:* per-trade and 24-hour caps, a receiver allowlist, pool + and pair allowlists, a slippage bound against the exchange's own quote and price floors, all + checked by the contract on every agent call ([`src/policy.rs`](src/policy.rs), + [What the contract guarantees](#what-the-contract-guarantees-and-where-it-is-checked)). + - *A sandboxed wallet:* the vault holds the money; the agent can trade from it and never + withdraw, and the owner can freeze it in one call or lock withdrawals until a date. + - *Function-call keys:* the agent's key can call only the vault's agent methods and cannot attach + a deposit ([exact limits](#the-agents-function-call-key-exact-limits)). + - *Scam and risk checks before signing:* the MCP server's pre-trade check returns allow, warn + or block for every swap, with reasons: thin or manipulated pools, upgradeable tokens, an unsafe + signing key, and every refusal the contract would make ([INTEGRATE.md](INTEGRATE.md)). + - *TEE attestation:* the model's trade decisions carry signature receipts from an attested TEE, + recorded with each trade ([AI decisions, verifiable](#ai-decisions-verifiable)). + - *Adversarial proof:* the canary's agent key is public on mainnet and the board shows every + attempt and the contract's reason for refusing it; on mainnet, an agent that obeyed a prompt + injection telling it to drain its vault was refused every time it tried + ([Prompt-injection attack](#prompt-injection-attack-the-agent-was-told-to-drain-the-vault)). + The deployed code is checked live against its reproducible build, and every trust assumption + is written down in [THREAT_MODEL.md](THREAT_MODEL.md). - **Unstoppable DeFi (`defi`).** A vault and a trading agent that settles through NEAR Intents, with no custodian of the agent's key: swaps go through Rhea (Ref V1) under on-chain pool, pair, cap and slippage rules, the slippage checked against the exchange's @@ -607,12 +662,14 @@ Services: FastNEAR RPC and transactions API, and the NearBlocks API as a fallbac |---|---| | `src/` | The vault contract: `lib.rs` (deposit, withdraw, views), `policy.rs`, `spend.rs`, `swap.rs`, `callbacks.rs`, `tokens.rs`, `ledger.rs`, `lock.rs`, `storage.rs`, `events.rs`, and the NEAR Intents path in `intents.rs` and `intent_swap.rs`; unit tests in `tests.rs` | | `tests/` | Sandbox tests, the contract binaries they deploy (`tests/res/`) and the mock MPC signer (`tests/contracts/`) | -| `agent/` | The prompt-injection demo agent and the intent-swap agent (Node, no npm packages of their own; the AI receipt check uses `web/`'s pinned `@noble` packages) | +| `agent/` | The prompt-injection demo agent, the intent-swap agent, the MCP server (`mcp-server.mjs`) and the pre-trade check (`risk-check.mjs`) (Node, no npm packages of their own; the AI receipt check uses `web/`'s pinned `@noble` packages) | | `web/` | Owner console and canary board (React, Vite) | | `scripts/` | Testnet smoke tests and canary setup; mainnet deploy, canary, smoke, intents and teardown scripts, dry run by default and resumable (near-cli-rs) | | [THREAT_MODEL.md](THREAT_MODEL.md) | Invariants, trust assumptions, what counts as a canary break | | [CANARY.md](CANARY.md) | The public canaries, mainnet and testnet: accounts, keys, baselines, how to try | | [CHAIN_SIGNATURES.md](CHAIN_SIGNATURES.md) | The NEAR Intents path: calls, the mainnet run, its transactions | +| [INTEGRATE.md](INTEGRATE.md) | Putting an agent on a vault: the MCP server, the pre-trade check, or any signer | +| [GTM.md](GTM.md) | Go-to-market: first users, distribution, pricing, launch sequence, metrics | ## Status and known gaps @@ -624,15 +681,16 @@ Services: FastNEAR RPC and transactions API, and the NearBlocks API as a fallbac [run 43022039828](https://github.com/UEddy/Intatto/actions/runs/43022039828); [scripts/mainnet-deploy.sh](scripts/mainnet-deploy.sh) deploys nothing else. `intents.intatto.near` runs the reproducible build of commit `fc23fbc` (`HRkrMN8o…`, run 43063218549). -- The deployer keeps a full-access key on both vault accounts, so the funds in this hackathon - deployment stay recoverable. That key can replace the code. For the canary's vault, the board's +- The deployer keeps a full-access key on both vault accounts on purpose, so that a bug in the + unaudited code can be fixed and no owner's funds are ever stuck + ([why](#why-the-upgrade-keys-stay-until-the-audit)). That key can replace the code. For the canary's vault, the board's integrity check shows any change within 10 seconds ([CANARY.md](CANARY.md)). Both keys are removed after an external audit ([After the hackathon](#after-the-hackathon)). - The NEAR Intents path has settled one swap on mainnet. Its limits and trust assumptions (the MPC network, `intents.near` governance) are in [THREAT_MODEL.md](THREAT_MODEL.md). - vault-v2 runs a non-reproducible build of the fee code (code hash above), so its code cannot be checked against source; vault-v1 and both mainnet vaults use reproducible builds. -- Passkey sign-in (mainnet only): Experimental: sign-in verified on a phone (2026-11-12); signing transactions with a passkey not yet tested. Unaudited Trezu wallet contract, upgradeable by Trezu; use small amounts only. +- Passkey sign-in (mainnet only), experimental: sign-in verified on a phone (2026-11-12); signing transactions with a passkey not yet tested. Unaudited Trezu wallet contract, upgradeable by Trezu; use small amounts only. - The mainnet deployment stays live after the hackathon. [scripts/mainnet-teardown.sh](scripts/mainnet-teardown.sh) remains in the repository as the operator's way to wind it down safely if ever needed. - The web app is hosted at [intatto.pages.dev](https://intatto.pages.dev/?network=mainnet) diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index c526904..9812e52 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -1,12 +1,17 @@ # Threat model -This covers the vault contract in `src/`, deployed on testnet as `vault-v1.intatto-dev.testnet` -with `exchange_id = ref-finance-101.testnet` (Rhea / Ref V1, ref-exchange 1.9.19). It is a -working document, not an audit. +This covers the vault contract in `src/` and its deployments. It is a working document, not an +audit. -vault-v1 runs the build without the swap fee (code hash `J5Mo…`). The fee build (invariants 12 -and 13) is not deployed yet. It goes to a fresh testnet account, vault-v2, initialized with -`new(exchange_id, treasury_id)`, so vault-v1 and its canary are left as they are. +| Deployment | Build | Exchange | +|---|---|---| +| `vault.intatto.near` (mainnet, the canary's vault) | reproducible build of `6cfa90e` (`3z1W5Sfh…`), with the swap fee (invariants 12 and 13), without the intents path | `v2.ref-finance.near` (ref-exchange 1.9.21) | +| `intents.intatto.near` (mainnet) | reproducible build of `fc23fbc` (`HRkrMN8o…`), with the intents path (invariants 14 to 18) | `v2.ref-finance.near` | +| `vault-v1.intatto-dev.testnet` (the testnet canary's vault) | reproducible build of `b85cece` (`J5Mo…`), no swap fee | `ref-finance-101.testnet` (ref-exchange 1.9.19) | +| `vault-v2.intatto-dev.testnet` | local non-reproducible build of the fee code (`7aiNbHTn…`) | `ref-finance-101.testnet` | + +The fee build went to fresh accounts initialized with `new(exchange_id, treasury_id)`, so vault-v1 +and its canary were left as they are. ## What the contract is @@ -150,7 +155,7 @@ exchange beyond rejected calls. - a panicking receipt reverts its state changes; - callbacks run with the results of the promises they follow; - block timestamps are close enough to real time for 24-hour windows and locks. -- **The exchange contract** (`ref-finance-101.testnet`). The vault credits the amounts the +- **The exchange contract** (`ref-finance-101.testnet` on testnet, `v2.ref-finance.near` on mainnet). The vault credits the amounts the exchange reports from `swap` and `withdraw`, and keeps owners' tokens in the vault's account on the exchange between steps. An exchange that reported false amounts could make the vault credit balances backed by other owners' tokens. @@ -187,14 +192,19 @@ exchange beyond rejected calls. It cannot withdraw, register an agent or change the policy. Unfreezing does matter: if the current agent's key is also compromised, unfreezing lets that agent spend again within the current policy. Freeze is therefore only as strong as the owner key's custody. -- **The vault account's key.** `vault-v1.intatto-dev.testnet` has a full-access key. Whoever - holds it can deploy any code to the vault account, including code that sends every owner's - funds anywhere, or delete the account. See the limitations below. - -## Chain Signatures intents path (branch `chain-signatures`, live on mainnet) - -This section covers code that exists only on the `chain-signatures` branch; master does not depend -on it. It adds a second way for the agent to swap: through NEAR Intents, with the vault's intents +- **The vault account's key.** Every vault account has a full-access key: the deployer's key on + `vault.intatto.near`, kept offline, the key on `intents.intatto.near` (see the intents path + below), and the testnet accounts' keys. Whoever holds one can deploy any code to that vault + account, including code that sends every owner's funds anywhere, or delete the account. The + mainnet keys are kept on purpose until an external audit: without one, a bug in the unaudited + code (in the withdraw path, or the lostfound case below) could never be fixed and the funds it + affected would be stuck for good. Owners do not need these keys to withdraw. They are removed + after the audit (README, "After the hackathon"). See the limitations below. + +## Chain Signatures intents path (live on mainnet) + +This section covers the intents code (`src/intents.rs`, `src/intent_swap.rs`), merged into master. +The canary's `vault.intatto.near` runs an earlier build without it. It adds a second way for the agent to swap: through NEAR Intents, with the vault's intents account signed for by the MPC network. Since 2026-11-11 it runs on mainnet as **`intents.intatto.near`**: @@ -635,7 +645,7 @@ Limits of this measurement: ## Passkey sign-in (mainnet only, experimental) -Experimental: sign-in verified on a phone (2026-11-12); signing transactions with a passkey not yet tested. Unaudited Trezu wallet contract, upgradeable by Trezu; use small amounts only. The console labels the passkey +The console labels the passkey path **"Experimental: sign-in verified on a phone (2026-11-12); signing transactions with a passkey not yet tested. Unaudited Trezu wallet contract, upgradeable by Trezu; use small amounts only."**, in a banner and in the wallet menu, and recommends a withdrawal lock. Code: `web/src/wallet/passkey.ts`. diff --git a/agent/README.md b/agent/README.md index ec9f0f1..01fa5f2 100644 --- a/agent/README.md +++ b/agent/README.md @@ -14,6 +14,12 @@ Only the invoice goes through. `vault-v2.intatto-dev.testnet`. Both modes ran against it on 2026-11-11; see [Results](#results-2026-11-11). `--dry-run` (below) still works without a key and sends nothing. +**Also run on mainnet, 2026-11-12**, on `demo.intatto.near`'s vault on `vault.intatto.near`, with +`attacker.intatto.near` as the attacker and a private key deleted after the runs +([scripts/mainnet-injection-demo.sh](../scripts/mainnet-injection-demo.sh)): the same three attack +payments were refused and only the invoice was paid. Transactions are in the main +[README](../README.md#prompt-injection-attack-the-agent-was-told-to-drain-the-vault). + ## Results, 2026-11-11 The vault before the first run: 0.0978 NEAR, allowlist `[demo-merchant.intatto-dev.testnet]`, diff --git a/agent/mcp-server.mjs b/agent/mcp-server.mjs new file mode 100644 index 0000000..1c65ce0 --- /dev/null +++ b/agent/mcp-server.mjs @@ -0,0 +1,384 @@ +#!/usr/bin/env node +// Intatto MCP server: lets an AI agent in any MCP client (Claude, ChatGPT, Cursor, Codex...) +// read its Intatto vault, check a swap before it signs, and trade through the vault, without +// ever holding a key that can withdraw. +// +// Transport: stdio, newline-delimited JSON-RPC 2.0, no dependencies. Dual-era per the MCP +// versioning rules: a client that opens with `initialize` (protocol 2025-11-25 and earlier) is +// served with legacy semantics; a request carrying `_meta["io.modelcontextprotocol/protocolVersion"]` +// (2026-07-28) is served statelessly, and `server/discover` answers either way. +// +// Tools: +// intatto_vault_status balances, freeze, lock, policy, and what is left of today's caps +// intatto_check_agent_key whether the signing key can only call the vault's agent methods +// intatto_check_swap allow / warn / block for a planned swap, with reasons and a suggested minimum +// intatto_swap runs the check, then signs and sends agent_swap (only with INTATTO_ALLOW_TRADES=1) +// +// The vault contract enforces the owner's policy whatever this server does. The server adds a +// pre-trade check (agent/risk-check.mjs) so that refused swaps are not sent and risks the contract +// does not judge (price impact, upgradeable tokens, a full-access signing key) are flagged. +// +// Configuration (environment, or agent/.env): +// INTATTO_NETWORK mainnet (default) or testnet +// INTATTO_RPC_URL default: https://rpc.mainnet.fastnear.com/ or https://test.rpc.fastnear.com/ +// INTATTO_VAULT_ID default: vault.intatto.near or vault-v1.intatto-dev.testnet +// INTATTO_OWNER_ID the vault owner whose vault the agent trades (tools may override it) +// INTATTO_AGENT_ID the agent account +// INTATTO_AGENT_KEY the agent's function-call private key (ed25519:...), or +// INTATTO_AGENT_KEY_FILE a near CLI key file holding it +// INTATTO_ALLOW_TRADES set to 1 to let intatto_swap send transactions; otherwise it reports +// the exact call it would make and sends nothing +// +// Claude Code: claude mcp add --transport stdio intatto --env INTATTO_OWNER_ID=you.near \ +// --env INTATTO_AGENT_ID=agent.you.near --env INTATTO_AGENT_KEY_FILE=/path/to/key.json \ +// -- node /path/to/Intatto/agent/mcp-server.mjs +// The key never leaves this process: it is never returned by a tool or written to a log. +import { readFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +import { fileURLToPath } from "node:url"; +import { Chain, vaultEvents } from "./intent-swap.mjs"; +import { keyPair } from "./near-tx.mjs"; +import { assessSwap, gatherSwapFacts, keyScope, soldInWindow, spendsInWindow } from "./risk-check.mjs"; +import { loadEnvFile, redact } from "./secrets.mjs"; + +export const SERVER_INFO = { name: "intatto", version: "0.1.0" }; +export const MODERN_VERSION = "2026-07-28"; +export const LEGACY_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]; +const META_VERSION = "io.modelcontextprotocol/protocolVersion"; +const META_SERVER = "io.modelcontextprotocol/serverInfo"; +const SWAP_GAS = 300_000_000_000_000n; // what scripts/mainnet-smoke.sh attaches; the contract needs AGENT_SWAP_TGAS of it + +export const INSTRUCTIONS = + "Intatto vault tools. The vault holds the money and enforces the owner's policy on every agent call; " + + "this server's key can trade from the vault but never withdraw. Before every trade call intatto_check_swap " + + "and pass its suggested min_amount_out. A 'block' verdict means the contract would refuse it or the risk is too high; " + + "do not retry it unchanged. Never ask the user for keys."; + +const NETWORKS = { + mainnet: { rpc: "https://rpc.mainnet.fastnear.com/", vault: "vault.intatto.near", explorer: "https://nearblocks.io/txns/" }, + testnet: { rpc: "https://test.rpc.fastnear.com/", vault: "vault-v1.intatto-dev.testnet", explorer: "https://testnet.nearblocks.io/txns/" }, +}; + +const amount = { type: "string", pattern: "^[0-9]+$", description: "In the token's smallest units, as a decimal string." }; +const owner = { type: "string", description: "Vault owner account. Defaults to INTATTO_OWNER_ID." }; +const swapProps = { + owner_id: owner, + pool_id: { type: "integer", minimum: 0, description: "Rhea (Ref) pool id from the owner's policy." }, + token_in: { type: "string", description: "Token the vault sells, e.g. wrap.near." }, + token_out: { type: "string", description: "Token the vault buys." }, + amount_in: amount, + min_amount_out: { ...amount, description: "Least output accepted. Omit to use the check's suggestion (at most 0.5% under the exchange's quote)." }, +}; + +export const TOOLS = [ + { + name: "intatto_check_agent_key", + title: "Check the agent's key", + description: "Reports whether the configured signing key can only call the vault's agent methods (safe) or can do more (unsafe).", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true, openWorldHint: true }, + }, + { + name: "intatto_check_swap", + title: "Check a swap before signing", + description: + "Pre-trade risk check for an agent swap: allow, warn or block, with reasons. Mirrors every refusal the vault contract would make " + + "(policy, caps, freeze, slippage against the exchange's quote) and flags price impact, upgradeable tokens and an unsafe key. Read-only.", + inputSchema: { type: "object", properties: swapProps, required: ["pool_id", "token_in", "token_out", "amount_in"], additionalProperties: false }, + annotations: { readOnlyHint: true, openWorldHint: true }, + }, + { + name: "intatto_swap", + title: "Swap through the vault", + description: + "Runs intatto_check_swap, then signs agent_swap with the agent's function-call key. Refuses on 'block'; on 'warn' needs acknowledge_warnings. " + + "Sends nothing unless the server runs with INTATTO_ALLOW_TRADES=1. The vault contract re-checks the policy on chain.", + inputSchema: { + type: "object", + properties: { ...swapProps, acknowledge_warnings: { type: "boolean", description: "Proceed although the check returned warnings." } }, + required: ["pool_id", "token_in", "token_out", "amount_in"], + additionalProperties: false, + }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true }, + }, + { + name: "intatto_vault_status", + title: "Vault status", + description: "The vault's balances, freeze and withdrawal lock, the owner's policy, and what is left of today's caps for each token. Read-only.", + inputSchema: { type: "object", properties: { owner_id: owner }, additionalProperties: false }, + annotations: { readOnlyHint: true, openWorldHint: true }, + }, +].sort((a, b) => a.name.localeCompare(b.name)); // deterministic order, as the spec asks + +/** Reads configuration from `env`. The agent key is loaded lazily and only its public half is kept in view. */ +export function configFrom(env) { + const network = env.INTATTO_NETWORK ?? "mainnet"; + const n = NETWORKS[network]; + if (!n) throw new Error(`INTATTO_NETWORK must be mainnet or testnet, not ${network}`); + let secret = env.INTATTO_AGENT_KEY; + if (!secret && env.INTATTO_AGENT_KEY_FILE) { + try { + secret = JSON.parse(readFileSync(env.INTATTO_AGENT_KEY_FILE, "utf8")).private_key; + } catch { + throw new Error(`INTATTO_AGENT_KEY_FILE is not a readable near CLI key file`); + } + } + return { + network, + rpcUrl: env.INTATTO_RPC_URL ?? n.rpc, + vaultId: env.INTATTO_VAULT_ID ?? n.vault, + explorer: n.explorer, + ownerId: env.INTATTO_OWNER_ID, + agentId: env.INTATTO_AGENT_ID, + allowTrades: env.INTATTO_ALLOW_TRADES === "1", + secret, // kept for signing only; never returned + }; +} + +class ToolError extends Error {} + +function need(value, name) { + if (!value) throw new ToolError(`${name} is not set. Pass it as an argument or set it in the server's environment.`); + return value; +} + +function swapParams(cfg, args, publicKey) { + return { + vaultId: cfg.vaultId, + ownerId: need(args.owner_id ?? cfg.ownerId, "owner_id (INTATTO_OWNER_ID)"), + agentId: need(cfg.agentId, "INTATTO_AGENT_ID"), + agentPublicKey: publicKey, + poolId: Number(args.pool_id), + tokenIn: String(args.token_in), + tokenOut: String(args.token_out), + amountIn: String(args.amount_in), + minAmountOut: args.min_amount_out === undefined ? undefined : String(args.min_amount_out), + }; +} + +/** Facts, then the verdict; with no min_amount_out given, the check's own suggestion is used. */ +async function checkSwap(chain, cfg, args, publicKey) { + const p = swapParams(cfg, args, publicKey); + const facts = await gatherSwapFacts(chain, { ...p, minAmountOut: p.minAmountOut ?? "1" }); + let minAmountOut = p.minAmountOut; + if (minAmountOut === undefined) { + // The check's own suggestion. With no quote there is none; the check is then run with a + // placeholder of 1 so that it reports the real reason (no quote) rather than blaming a + // minimum the caller never gave, and the result says no minimum was used. + const suggested = assessSwap({ ...facts, minAmountOut: "1" }).suggestedMinOut; + if (suggested === null) { + return { params: { ...p, minAmountOut: null }, result: assessSwap({ ...facts, minAmountOut: "1" }) }; + } + minAmountOut = suggested; + } + const result = assessSwap({ ...facts, minAmountOut }); + return { params: { ...p, minAmountOut }, result }; +} + +function publicKeyOf(cfg) { + if (!cfg.secret) return undefined; + return keyPair(cfg.secret).publicKey; +} + +export function makeTools(cfg, chain) { + return { + async intatto_vault_status(args) { + const ownerId = need(args.owner_id ?? cfg.ownerId, "owner_id (INTATTO_OWNER_ID)"); + const block = await chain.rpc("block", { finality: "final" }); + const nowNs = BigInt(block.header.timestamp_nanosec ?? block.header.timestamp); + const v = await chain.view(cfg.vaultId, "get_vault", { owner_id: ownerId }); + if (!v) return { network: cfg.network, vault_id: cfg.vaultId, owner_id: ownerId, exists: false }; + const policy = v.policy ?? {}; + const lock = v.withdrawals_locked_until ? BigInt(v.withdrawals_locked_until) : null; + return { + network: cfg.network, + vault_id: cfg.vaultId, + owner_id: ownerId, + exists: true, + block_height: block.header.height, + agent_id: v.agent_id, + frozen: v.frozen, + withdrawals_locked_until_ns: lock !== null && lock > nowNs ? lock.toString() : null, + near_balance_yocto: v.balance, + tokens: (v.tokens ?? []).map((t) => ({ token_id: t.token_id, balance: t.balance, on_exchange: t.on_exchange })), + agent_calls_last_24h: spendsInWindow(v.recent_spends, nowNs), + max_agent_calls_per_24h: policy.max_spends_per_24h, + token_caps: (policy.tokens ?? []).map((t) => { + const sold = soldInWindow(v.recent_spends, t.token_id, nowNs); + const left = BigInt(t.daily_cap) > sold ? BigInt(t.daily_cap) - sold : 0n; + return { token_id: t.token_id, per_swap_cap: t.per_tx_cap, daily_cap: t.daily_cap, sold_last_24h: sold.toString(), left_today: left.toString() }; + }), + pools: policy.pools ?? [], + }; + }, + + async intatto_check_agent_key() { + const agentId = need(cfg.agentId, "INTATTO_AGENT_ID"); + const publicKey = publicKeyOf(cfg); + if (!publicKey) throw new ToolError("No agent key is configured (INTATTO_AGENT_KEY or INTATTO_AGENT_KEY_FILE)."); + let permission; + try { + permission = (await chain.rpc("query", { request_type: "view_access_key", finality: "final", account_id: agentId, public_key: publicKey })).permission; + } catch { + return { agent_id: agentId, public_key: publicKey, scope: "missing", safe: false, message: `This key is not an access key of ${agentId}.` }; + } + const scope = keyScope(permission, cfg.vaultId); + const messages = { + "vault-only": `Safe: the key can only call the vault's agent methods on ${cfg.vaultId}, and cannot attach a deposit.`, + wider: `Not safe: the key can call vault methods beyond the agent methods. Replace it with one limited to agent_swap (and agent_spend if needed).`, + full: `Not safe: this is a full-access key. Anyone who gets it controls ${agentId}. Use a function-call key on ${cfg.vaultId} instead.`, + other: `Not usable: the key cannot call ${cfg.vaultId}.`, + }; + return { agent_id: agentId, public_key: publicKey, scope, safe: scope === "vault-only", permission, message: messages[scope] }; + }, + + async intatto_check_swap(args) { + const { params, result } = await checkSwap(chain, cfg, args, publicKeyOf(cfg)); + return { min_amount_out_used: params.minAmountOut, ...result }; + }, + + async intatto_swap(args) { + const publicKey = publicKeyOf(cfg); + if (!publicKey) throw new ToolError("No agent key is configured (INTATTO_AGENT_KEY or INTATTO_AGENT_KEY_FILE)."); + const { params, result } = await checkSwap(chain, cfg, args, publicKey); + if (result.verdict === "block") return { sent: false, check: result, message: "Not sent: the check blocked this swap. Fix the reasons, do not retry it unchanged." }; + if (result.verdict === "warn" && args.acknowledge_warnings !== true) { + return { sent: false, check: result, message: "Not sent: the check returned warnings. Call again with acknowledge_warnings: true to proceed, or change the trade." }; + } + const call = { + signer_id: params.agentId, + receiver_id: cfg.vaultId, + method: "agent_swap", + args: { owner_id: params.ownerId, pool_id: params.poolId, token_in: params.tokenIn, token_out: params.tokenOut, amount_in: params.amountIn, min_amount_out: params.minAmountOut }, + gas: SWAP_GAS.toString(), + deposit: "0", + }; + if (!cfg.allowTrades) return { sent: false, dry_run: true, check: result, call, message: "Dry run: INTATTO_ALLOW_TRADES is not 1, so nothing was signed. This is the exact call." }; + const keys = keyPair(cfg.secret); + const outcome = await chain.call({ signerId: params.agentId, keys, receiverId: cfg.vaultId, method: "agent_swap", args: call.args, gas: SWAP_GAS }); + const hash = outcome?.transaction?.hash ?? outcome?.transaction_outcome?.id; + const events = vaultEvents(outcome, cfg.vaultId).map((e) => ({ event: e.event, data: e.data })); + const rejected = events.find((e) => e.event === "swap_rejected"); + return { + sent: true, + tx_hash: hash, + explorer: hash ? `${cfg.explorer}${hash}` : null, + status: rejected ? `refused by the vault: ${rejected.data?.reason}` : events.some((e) => e.event === "swap_completed") ? "completed" : "initiated", + events, + check: result, + }; + }, + }; +} + +function jsonText(value) { + return JSON.stringify(value, (_, v) => (typeof v === "bigint" ? v.toString() : v), 2); +} + +/** + * Handles one JSON-RPC message; returns the response object, or null for a notification. + * `state.legacy` records an `initialize` handshake (legacy era) for this process. + */ +export async function handle(msg, { tools, state, secrets = [] }) { + const isRequest = msg && typeof msg === "object" && msg.id !== undefined && msg.id !== null; + if (!msg || msg.jsonrpc !== "2.0" || typeof msg.method !== "string") { + return isRequest || msg?.id === undefined ? { jsonrpc: "2.0", id: msg?.id ?? null, error: { code: -32600, message: "Invalid Request" } } : null; + } + if (!isRequest) return null; // notifications (notifications/initialized, cancelled, ...) need no answer + const reply = (result) => ({ jsonrpc: "2.0", id: msg.id, result }); + const fail = (code, message, data) => ({ jsonrpc: "2.0", id: msg.id, error: data === undefined ? { code, message } : { code, message, data } }); + const params = msg.params ?? {}; + const requested = params._meta?.[META_VERSION]; + const modern = requested !== undefined; + if (modern && requested !== MODERN_VERSION) { + return fail(-32022, "Unsupported protocol version", { supported: [MODERN_VERSION, ...LEGACY_VERSIONS], requested }); + } + const withMeta = (result) => (modern ? { resultType: "complete", ...result, _meta: { [META_SERVER]: SERVER_INFO } } : result); + + switch (msg.method) { + case "initialize": { + const asked = params.protocolVersion; + state.legacy = true; + return reply({ + protocolVersion: LEGACY_VERSIONS.includes(asked) ? asked : LEGACY_VERSIONS[0], + capabilities: { tools: { listChanged: false } }, + serverInfo: SERVER_INFO, + instructions: INSTRUCTIONS, + }); + } + case "server/discover": + return reply({ + resultType: "complete", + supportedVersions: [MODERN_VERSION, ...LEGACY_VERSIONS], + capabilities: { tools: {} }, + _meta: { [META_SERVER]: SERVER_INFO }, + instructions: INSTRUCTIONS, + ttlMs: 3_600_000, + cacheScope: "public", + }); + case "ping": + return reply({}); + case "tools/list": + return reply(withMeta({ tools: TOOLS, ttlMs: 3_600_000, cacheScope: "public" })); + case "tools/call": { + const tool = TOOLS.find((t) => t.name === params.name); + if (!tool) return fail(-32602, `Unknown tool: ${params.name}`); + const args = params.arguments ?? {}; + for (const key of tool.inputSchema.required ?? []) { + if (args[key] === undefined) return reply(withMeta({ content: [{ type: "text", text: `Missing argument: ${key}` }], isError: true })); + } + for (const [key, value] of Object.entries(args)) { + const schema = tool.inputSchema.properties[key]; + if (!schema) return reply(withMeta({ content: [{ type: "text", text: `Unknown argument: ${key}` }], isError: true })); + if (schema.pattern && !(typeof value === "string" && new RegExp(schema.pattern).test(value))) { + return reply(withMeta({ content: [{ type: "text", text: `${key} must be a decimal string of digits` }], isError: true })); + } + if (schema.type === "integer" && !Number.isSafeInteger(value)) return reply(withMeta({ content: [{ type: "text", text: `${key} must be an integer` }], isError: true })); + } + try { + const out = await tools[tool.name](args); + const isError = out?.sent === false && !out?.dry_run; + return reply(withMeta({ content: [{ type: "text", text: redact(jsonText(out), secrets) }], structuredContent: JSON.parse(jsonText(out)), isError })); + } catch (err) { + const text = err instanceof ToolError ? err.message : `Failed: ${err?.message ?? err}`; + return reply(withMeta({ content: [{ type: "text", text: redact(text, secrets) }], isError: true })); + } + } + default: + return fail(-32601, `Method not found: ${msg.method}`); + } +} + +async function main() { + loadEnvFile(); + const cfg = configFrom(process.env); + const secrets = cfg.secret ? [cfg.secret] : []; + const tools = makeTools(cfg, new Chain(cfg.rpcUrl)); + const state = { legacy: false }; + const write = (obj) => process.stdout.write(JSON.stringify(obj) + "\n"); + // Logs go to stderr only: stdout carries protocol messages and nothing else. + console.error(`intatto mcp: ${cfg.network}, vault ${cfg.vaultId}, trades ${cfg.allowTrades ? "enabled" : "dry-run"}`); + const rl = createInterface({ input: process.stdin, crlfDelay: Infinity }); + for await (const line of rl) { + if (!line.trim()) continue; + let msg; + try { + msg = JSON.parse(line); + } catch { + write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); + continue; + } + // Requests are independent; answer each as it finishes. + handle(msg, { tools, state, secrets }).then( + (res) => res && write(res), + (err) => write({ jsonrpc: "2.0", id: msg?.id ?? null, error: { code: -32603, message: redact(String(err?.message ?? err), secrets) } }), + ); + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { + main().catch((err) => { + console.error(`intatto mcp: ${err?.message ?? err}`); + process.exit(1); + }); +} diff --git a/agent/mcp-server.test.mjs b/agent/mcp-server.test.mjs new file mode 100644 index 0000000..c848aaa --- /dev/null +++ b/agent/mcp-server.test.mjs @@ -0,0 +1,211 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { generateKeyPairSync } from "node:crypto"; +import { dirname, join } from "node:path"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; +import { configFrom, handle, LEGACY_VERSIONS, makeTools, MODERN_VERSION, TOOLS } from "./mcp-server.mjs"; +import { base58Encode, keyPair } from "./near-tx.mjs"; + +const here = dirname(fileURLToPath(import.meta.url)); +const NOW = 1_800_000_000_000_000_000n; +const VAULT = "vault.intatto.near"; +const W = "wrap.near"; +const U = "usdt.tether-token.near"; + +function secretKey() { + const { privateKey, publicKey } = generateKeyPairSync("ed25519"); + const d = Buffer.from(privateKey.export({ format: "jwk" }).d, "base64url"); + const x = Buffer.from(publicKey.export({ format: "jwk" }).x, "base64url"); + return `ed25519:${base58Encode(Buffer.concat([d, x]))}`; +} +const SECRET = secretKey(); +const PUBLIC = keyPair(SECRET).publicKey; + +function fakeChain({ permission = { FunctionCall: { receiver_id: VAULT, method_names: ["agent_swap"] } }, frozen = false } = {}) { + const sent = []; + return { + sent, + rpc: async (method, params) => { + if (method === "block") return { header: { height: 123, timestamp_nanosec: NOW.toString() } }; + if (params.request_type === "view_access_key") return { permission }; + if (params.request_type === "view_access_key_list") return { keys: [] }; + throw new Error("unexpected " + method); + }, + view: async (_account, method, args) => { + if (method === "get_vault") + return { + balance: "0", + frozen, + agent_id: "agent.near", + withdrawals_locked_until: (NOW + 1000n).toString(), + policy: { + max_spends_per_24h: 5, + tokens: [{ token_id: W, per_tx_cap: "1000", daily_cap: "3000" }], + pools: [{ pool_id: 7, token_ids: [W, U], max_slippage_bps: 100 }], + }, + recent_spends: [{ spend_id: "1", timestamp: (NOW - 5n).toString(), token_id: W, amount: "500" }], + tokens: [{ token_id: W, balance: "5000", on_exchange: "0" }], + }; + if (method === "get_exchange_id") return "v2.ref-finance.near"; + if (method === "get_return") return String(BigInt(args.amount_in) * 4n); + throw new Error("unexpected " + method); + }, + call: async (tx) => { + sent.push(tx); + return { + transaction: { hash: "HASH1" }, + receipts_outcome: [{ outcome: { executor_id: VAULT, logs: [`EVENT_JSON:${JSON.stringify({ standard: "intatto", version: "1.0.0", event: "swap_initiated", data: { agent_id: "agent.near" } })}`] } }], + }; + }, + }; +} + +function ctx(env = {}, chainOpts) { + const cfg = configFrom({ INTATTO_OWNER_ID: "owner.near", INTATTO_AGENT_ID: "agent.near", INTATTO_AGENT_KEY: SECRET, ...env }); + const chain = fakeChain(chainOpts); + return { chain, c: { tools: makeTools(cfg, chain), state: {}, secrets: [SECRET] } }; +} + +const call = (c, name, args, id = 1, meta) => handle({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args, ...(meta ? { _meta: meta } : {}) } }, c); +const body = (res) => res.result.structuredContent; + +test("legacy clients get an initialize handshake with the version they asked for", async () => { + const { c } = ctx(); + const res = await handle({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } } }, c); + assert.equal(res.result.protocolVersion, "2025-06-18"); + assert.deepEqual(res.result.capabilities, { tools: { listChanged: false } }); + assert.equal(res.result.serverInfo.name, "intatto"); + const unknown = await handle({ jsonrpc: "2.0", id: 2, method: "initialize", params: { protocolVersion: "2099-01-01" } }, c); + assert.equal(unknown.result.protocolVersion, LEGACY_VERSIONS[0]); + assert.equal(await handle({ jsonrpc: "2.0", method: "notifications/initialized" }, c), null); +}); + +test("modern clients: server/discover, per-request version, unsupported versions rejected", async () => { + const { c } = ctx(); + const meta = { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION }; + const d = await handle({ jsonrpc: "2.0", id: "d", method: "server/discover", params: { _meta: meta } }, c); + assert.equal(d.result.resultType, "complete"); + assert.ok(d.result.supportedVersions.includes(MODERN_VERSION)); + assert.equal(d.result._meta["io.modelcontextprotocol/serverInfo"].name, "intatto"); + const list = await handle({ jsonrpc: "2.0", id: 2, method: "tools/list", params: { _meta: meta } }, c); + assert.equal(list.result.resultType, "complete"); + assert.equal(list.result.cacheScope, "public"); + assert.deepEqual(list.result.tools.map((t) => t.name), [...TOOLS.map((t) => t.name)].sort()); + const bad = await handle({ jsonrpc: "2.0", id: 3, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "1900-01-01" } } }, c); + assert.equal(bad.error.code, -32022); + assert.equal(bad.error.data.requested, "1900-01-01"); + const missing = await handle({ jsonrpc: "2.0", id: 4, method: "nope" }, c); + assert.equal(missing.error.code, -32601); +}); + +test("arguments are validated before anything touches the chain", async () => { + const { c } = ctx(); + assert.equal((await call(c, "intatto_check_swap", { pool_id: 7, token_in: W, token_out: U })).result.isError, true); + assert.equal((await call(c, "intatto_check_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "1e3" })).result.isError, true); + assert.equal((await call(c, "intatto_check_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "10", extra: 1 })).result.isError, true); + assert.equal((await call(c, "intatto_check_swap", { pool_id: 7.5, token_in: W, token_out: U, amount_in: "10" })).result.isError, true); +}); + +test("vault status reports what is left of today's caps", async () => { + const { c } = ctx(); + const s = body(await call(c, "intatto_vault_status", {})); + assert.equal(s.exists, true); + assert.equal(s.agent_calls_last_24h, 1); + assert.equal(s.token_caps[0].left_today, "2500"); + assert.equal(s.withdrawals_locked_until_ns, (NOW + 1000n).toString()); +}); + +test("the key check says whether the key can only call the vault", async () => { + assert.equal(body(await call(ctx().c, "intatto_check_agent_key", {})).safe, true); + const full = body(await call(ctx({}, { permission: "FullAccess" }).c, "intatto_check_agent_key", {})); + assert.equal(full.scope, "full"); + assert.equal(full.safe, false); + assert.equal(full.public_key, PUBLIC); +}); + +test("check_swap suggests a tight minimum when none is given", async () => { + const r = body(await call(ctx().c, "intatto_check_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "1000" })); + assert.equal(r.verdict, "allow"); + assert.equal(r.min_amount_out_used, "3980"); +}); + +test("with no minimum given and no quote, the check reports the missing quote, not a zero minimum", async () => { + const { c, chain } = ctx(); + const view = chain.view; + chain.view = async (a, m, args) => (m === "get_return" ? Promise.reject(new Error("pool has no such token")) : view(a, m, args)); + const r = body(await call(c, "intatto_check_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "1000" })); + assert.equal(r.verdict, "block"); + assert.equal(r.min_amount_out_used, null); + assert.ok(r.reasons.some((x) => x.code === "quote_failed")); + assert.ok(!r.reasons.some((x) => x.code === "zero_min_amount_out")); + const s = body(await call(c, "intatto_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "1000" })); + assert.equal(s.sent, false); + assert.equal(chain.sent.length, 0); +}); + +test("swap: dry run by default, refuses blocks and unacknowledged warnings, sends only when allowed", async () => { + const dry = ctx(); + const d = body(await call(dry.c, "intatto_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "1000" })); + assert.equal(d.dry_run, true); + assert.equal(d.call.args.min_amount_out, "3980"); + assert.equal(dry.chain.sent.length, 0); + + const frozen = ctx({ INTATTO_ALLOW_TRADES: "1" }, { frozen: true }); + const f = await call(frozen.c, "intatto_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "1000" }); + assert.equal(f.result.isError, true); + assert.equal(body(f).check.verdict, "block"); + assert.equal(frozen.chain.sent.length, 0); + + const warned = ctx({ INTATTO_ALLOW_TRADES: "1" }); + const loose = { pool_id: 7, token_in: W, token_out: U, amount_in: "1000", min_amount_out: "3961" }; + assert.equal(body(await call(warned.c, "intatto_swap", loose)).sent, false); + assert.equal(warned.chain.sent.length, 0); + const ok = body(await call(warned.c, "intatto_swap", { ...loose, acknowledge_warnings: true })); + assert.equal(ok.sent, true); + assert.equal(ok.tx_hash, "HASH1"); + assert.equal(ok.explorer, "https://nearblocks.io/txns/HASH1"); + assert.equal(ok.status, "initiated"); + assert.equal(warned.chain.sent.length, 1); + assert.equal(warned.chain.sent[0].method, "agent_swap"); + assert.equal(warned.chain.sent[0].receiverId, VAULT); +}); + +test("the private key never appears in any tool output", async () => { + const { c } = ctx({ INTATTO_ALLOW_TRADES: "1" }); + const outputs = []; + for (const [name, args] of [ + ["intatto_check_agent_key", {}], + ["intatto_vault_status", {}], + ["intatto_check_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "1000" }], + ["intatto_swap", { pool_id: 7, token_in: W, token_out: U, amount_in: "1000" }], + ]) { + outputs.push(JSON.stringify(await call(c, name, args))); + } + const raw = SECRET.slice("ed25519:".length); + for (const o of outputs) assert.ok(!o.includes(raw)); +}); + +test("over stdio: answers initialize and tools/list, logs only to stderr", async () => { + const child = spawn(process.execPath, [join(here, "mcp-server.mjs")], { env: { PATH: process.env.PATH, INTATTO_NETWORK: "testnet" }, stdio: ["pipe", "pipe", "pipe"] }); + const lines = []; + let buf = ""; + child.stdout.on("data", (d) => { + buf += d; + let i; + while ((i = buf.indexOf("\n")) >= 0) { + lines.push(JSON.parse(buf.slice(0, i))); + buf = buf.slice(i + 1); + } + }); + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-11-25", capabilities: {}, clientInfo: { name: "t", version: "1" } } }) + "\n"); + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n"); + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }) + "\n"); + child.stdin.write("not json\n"); + const deadline = Date.now() + 5000; + while (lines.length < 3 && Date.now() < deadline) await new Promise((r) => setTimeout(r, 20)); + child.kill(); + assert.equal(lines.find((l) => l.id === 1).result.protocolVersion, "2025-11-25"); + assert.equal(lines.find((l) => l.id === 2).result.tools.length, TOOLS.length); + assert.equal(lines.find((l) => l.id === null).error.code, -32700); +}); diff --git a/agent/risk-check.mjs b/agent/risk-check.mjs new file mode 100644 index 0000000..546e15b --- /dev/null +++ b/agent/risk-check.mjs @@ -0,0 +1,248 @@ +// Pre-trade risk check for an agent swap through an Intatto vault: allow, warn or block, with +// reasons. +// +// The vault contract is the hard limit: it refuses every swap outside the owner's policy whatever +// this file says. This check runs before the agent signs, so that: +// - a swap the contract would refuse is never sent (no wasted gas, no noise on the board), and +// the agent gets the same reason the contract would give, in words; +// - risks the contract does not judge are flagged before they cost anything: a thin or +// manipulated pool (price impact), a token whose contract a single key can replace, a key +// that can do more than call the vault, and caps nearly used up. +// +// `assessSwap` is pure: it takes facts and returns a verdict, so every rule is unit-tested. +// `gatherSwapFacts` reads those facts from the chain over RPC (view calls only; it signs nothing). +// +// The block rules mirror the contract's checks in src/swap.rs (agent_swap, on_swap_quoted) and +// src/policy.rs. They use the same 24-hour window and the same slippage floor arithmetic +// (`slippage_floor`). They read state that can change before the swap lands, so a swap this check +// allows can still be refused by the contract; the reverse should not happen. + +/** The contract's 24-hour window for caps and counts (src/spend.rs WINDOW_NS). */ +export const WINDOW_NS = 24n * 60n * 60n * 1_000_000_000n; +const BPS = 10_000n; + +/** Price impact (bps) above which the check warns, and above which it blocks. */ +export const IMPACT_WARN_BPS = 100n; // 1% +export const IMPACT_BLOCK_BPS = 500n; // 5% +/** Share of a cap or count already used above which the check warns. */ +export const NEAR_LIMIT_SHARE_BPS = 8_000n; // 80% +/** The agent methods a vault key needs; anything wider is reported. */ +export const AGENT_METHODS = ["agent_spend", "agent_swap", "agent_intent_swap", "settle_intent_swap"]; + +/** The contract's slippage floor: quote * (10000 - bps) / 10000, rounded down (src/swap.rs). */ +export function slippageFloor(quote, maxSlippageBps) { + const q = BigInt(quote); + const keep = BPS - BigInt(maxSlippageBps); + return (q / BPS) * keep + ((q % BPS) * keep) / BPS; +} + +/** + * Price impact of the full trade, in bps: how much worse the rate for `amountIn` is than the rate + * for a small `probeIn`. The pool's fee is in both rates, so it cancels. Null if not computable. + */ +export function priceImpactBps(amountIn, quote, probeIn, probeQuote) { + const a = BigInt(amountIn); + const q = BigInt(quote); + const p = BigInt(probeIn); + const pq = BigInt(probeQuote); + if (a <= 0n || p <= 0n || pq <= 0n) return null; + // rate(full) / rate(probe) = (q / a) / (pq / p) = q * p / (pq * a) + const ratioBps = (q * p * BPS) / (pq * a); + return ratioBps >= BPS ? 0n : BPS - ratioBps; +} + +function counts(spend, nowNs) { + return BigInt(spend.timestamp) + WINDOW_NS > nowNs; +} + +/** How much of `tokenId` the vault's agent sold in the last 24 hours (or NEAR sent, for null). */ +export function soldInWindow(recentSpends, tokenId, nowNs) { + let total = 0n; + for (const s of recentSpends ?? []) { + if ((s.token_id ?? null) === tokenId && counts(s, nowNs)) total += BigInt(s.amount); + } + return total; +} + +/** Agent spends and swaps in the last 24 hours, the count `max_spends_per_24h` limits. */ +export function spendsInWindow(recentSpends, nowNs) { + return (recentSpends ?? []).filter((s) => counts(s, nowNs)).length; +} + +/** Describes an access key's permission: "full", "vault-only" (exactly agent methods), "wider" or "other". */ +export function keyScope(permission, vaultId) { + if (permission === "FullAccess" || permission?.FullAccess !== undefined) return "full"; + const call = permission?.FunctionCall; + if (!call || call.receiver_id !== vaultId) return "other"; + const methods = call.method_names ?? []; + if (methods.length === 0) return "wider"; // an empty list allows every method of the receiver + return methods.every((m) => AGENT_METHODS.includes(m)) ? "vault-only" : "wider"; +} + +/** + * The verdict for one planned `agent_swap`. + * + * facts: { + * vaultId, ownerId, agentId, poolId (number), tokenIn, tokenOut, + * amountIn, minAmountOut (strings or bigints, smallest units), + * nowNs (bigint, chain time), + * vault: get_vault result or null, + * quote: exchange get_return for amountIn, or null if it failed, + * probeIn, probeQuote: a small trade's input and quote, for price impact (optional), + * agentKeyPermission: the signing key's permission from view_access_key (optional), + * tokenOutFullAccessKeys: number of full-access keys on tokenOut's account (optional), + * } + * returns { verdict: "allow" | "warn" | "block", reasons: [{ level, code, message }], quote, floor, suggestedMinOut, impactBps } + */ +export function assessSwap(f) { + const reasons = []; + const block = (code, message) => reasons.push({ level: "block", code, message }); + const warn = (code, message) => reasons.push({ level: "warn", code, message }); + const amountIn = BigInt(f.amountIn ?? 0); + const minOut = BigInt(f.minAmountOut ?? 0); + const nowNs = BigInt(f.nowNs ?? 0); + const out = { quote: f.quote ?? null, floor: null, suggestedMinOut: null, impactBps: null }; + + if (amountIn <= 0n) block("zero_amount", "amount_in must be greater than zero."); + if (minOut <= 0n) block("zero_min_amount_out", "min_amount_out must be greater than zero; the contract refuses an unbounded swap."); + + // The signing key. A full-access key is what Intatto exists to replace. + if (f.agentKeyPermission?.Missing) { + block("agent_key_missing", `The signing key is not an access key of ${f.agentId}.`); + } else if (f.agentKeyPermission !== undefined) { + const scope = keyScope(f.agentKeyPermission, f.vaultId); + if (scope === "full") block("agent_key_full_access", `The signing key is a full-access key on ${f.agentId}. Use a function-call key limited to the vault's agent methods.`); + else if (scope === "other") block("agent_key_wrong_receiver", `The signing key cannot call ${f.vaultId}.`); + else if (scope === "wider") warn("agent_key_wider", `The signing key can call vault methods beyond the agent methods (${AGENT_METHODS.join(", ")}).`); + } + + const v = f.vault; + if (!v) { + block("no_vault", `${f.ownerId} has no vault on ${f.vaultId}.`); + return finish(reasons, out); + } + if (v.agent_id !== f.agentId) block("not_agent", `${f.agentId} is not this vault's agent (the agent is ${v.agent_id ?? "nobody"}).`); + if (v.frozen) block("frozen", "The owner froze this vault; every agent call is refused until they unfreeze it."); + + const policy = v.policy ?? {}; + const pool = (policy.pools ?? []).find((p) => Number(p.pool_id) === Number(f.poolId)); + if (!pool) block("pool_not_allowlisted", `Pool ${f.poolId} is not in the owner's policy.`); + else { + const pair = pool.token_ids ?? []; + if (!(pair.includes(f.tokenIn) && pair.includes(f.tokenOut) && f.tokenIn !== f.tokenOut)) { + block("pair_mismatch", `Pool ${f.poolId} is declared for ${pair.join(" / ")}, not ${f.tokenIn} -> ${f.tokenOut}.`); + } + } + + const tokenPolicy = (policy.tokens ?? []).find((t) => t.token_id === f.tokenIn); + if (!tokenPolicy) block("token_not_allowed", `${f.tokenIn} is not in the owner's token policy, so the agent may not sell it.`); + else { + const perTx = BigInt(tokenPolicy.per_tx_cap); + const daily = BigInt(tokenPolicy.daily_cap); + const sold = soldInWindow(v.recent_spends, f.tokenIn, nowNs); + if (amountIn > perTx) block("over_per_tx_cap", `amount_in ${amountIn} is over the per-swap cap of ${perTx}.`); + if (sold + amountIn > daily) block("over_daily_cap", `${sold} already sold in the last 24 hours; ${amountIn} more is over the daily cap of ${daily}.`); + else if (daily > 0n && ((sold + amountIn) * BPS) / daily > NEAR_LIMIT_SHARE_BPS) { + warn("near_daily_cap", `After this swap ${sold + amountIn} of the ${daily} daily cap is used.`); + } + } + + const maxSpends = BigInt(policy.max_spends_per_24h ?? 0); + const used = BigInt(spendsInWindow(v.recent_spends, nowNs)); + if (used + 1n > maxSpends) block("too_many_spends", `${used} agent calls in the last 24 hours; the policy allows ${maxSpends}.`); + else if (maxSpends > 0n && ((used + 1n) * BPS) / maxSpends > NEAR_LIMIT_SHARE_BPS) { + warn("near_spend_count", `This is agent call ${used + 1n} of ${maxSpends} allowed in 24 hours.`); + } + + const held = BigInt((v.tokens ?? []).find((t) => t.token_id === f.tokenIn)?.balance ?? 0); + if (amountIn > held) block("insufficient_balance", `The vault holds ${held} of ${f.tokenIn}, less than amount_in ${amountIn}.`); + + // Against the exchange's own quote, as on_swap_quoted checks it. + if (f.quote === null || f.quote === undefined) { + block("quote_failed", `The exchange returned no quote for pool ${f.poolId}; the contract would refuse the swap.`); + } else if (pool) { + const quote = BigInt(f.quote); + const floor = slippageFloor(quote, pool.max_slippage_bps); + out.floor = floor.toString(); + // A tighter suggestion than the policy's loosest: at most 0.5% below the quote. + const tight = slippageFloor(quote, Math.min(Number(pool.max_slippage_bps), 50)); + out.suggestedMinOut = tight.toString(); + if (minOut < floor) { + block("slippage_too_loose", `min_amount_out ${minOut} is below the policy floor ${floor} (${pool.max_slippage_bps} bps under the quote ${quote}).`); + } else if (quote > 0n && minOut > quote) { + warn("min_out_above_quote", `min_amount_out ${minOut} is above the current quote ${quote}; the exchange will refuse the swap unless the price moves.`); + } else if (quote > 0n && ((quote - minOut) * BPS) / quote > BigInt(pool.max_slippage_bps) / 2n) { + warn("loose_min_out", `min_amount_out leaves ${((quote - minOut) * BPS) / quote} bps under the quote, over half of what the policy allows. Suggested: ${tight}.`); + } + if (f.probeQuote !== undefined && f.probeQuote !== null && f.probeIn) { + const impact = priceImpactBps(amountIn, quote, f.probeIn, f.probeQuote); + out.impactBps = impact === null ? null : impact.toString(); + if (impact !== null && impact > IMPACT_BLOCK_BPS) { + block("price_impact", `Price impact ${impact} bps: the pool is too thin for this size, or its price was moved. Trade less or wait.`); + } else if (impact !== null && impact > IMPACT_WARN_BPS) { + warn("price_impact", `Price impact ${impact} bps for this size.`); + } + } + } + + if (typeof f.tokenOutFullAccessKeys === "number" && f.tokenOutFullAccessKeys > 0) { + warn("token_out_upgradeable", `${f.tokenOut} has ${f.tokenOutFullAccessKeys} full-access key(s): whoever holds one can replace the token's code.`); + } + + return finish(reasons, out); +} + +function finish(reasons, out) { + const verdict = reasons.some((r) => r.level === "block") ? "block" : reasons.some((r) => r.level === "warn") ? "warn" : "allow"; + return { verdict, reasons, ...out, quote: out.quote === null ? null : String(out.quote) }; +} + +/** + * Reads the facts `assessSwap` needs. `chain` is agent/intent-swap.mjs's Chain (rpc, view). + * `agentPublicKey` is optional; without it the key check is skipped. + */ +export async function gatherSwapFacts(chain, p) { + const block = await chain.rpc("block", { finality: "final" }); + const nowNs = BigInt(block.header.timestamp_nanosec ?? block.header.timestamp); + const vault = await chain.view(p.vaultId, "get_vault", { owner_id: p.ownerId }); + const exchangeId = p.exchangeId ?? (await chain.view(p.vaultId, "get_exchange_id", {})); + const amountIn = BigInt(p.amountIn); + const quoteFor = async (amount) => { + try { + return await chain.view(exchangeId, "get_return", { pool_id: Number(p.poolId), token_in: p.tokenIn, amount_in: amount.toString(), token_out: p.tokenOut }); + } catch { + return null; + } + }; + const quote = amountIn > 0n ? await quoteFor(amountIn) : null; + const probeIn = amountIn / 100n > 0n ? amountIn / 100n : null; + const probeQuote = probeIn ? await quoteFor(probeIn) : null; + + let agentKeyPermission; + if (p.agentPublicKey) { + try { + const key = await chain.rpc("query", { request_type: "view_access_key", finality: "final", account_id: p.agentId, public_key: p.agentPublicKey }); + agentKeyPermission = key.permission; + } catch { + agentKeyPermission = { Missing: true }; + } + } + let tokenOutFullAccessKeys; + try { + const list = await chain.rpc("query", { request_type: "view_access_key_list", finality: "final", account_id: p.tokenOut }); + tokenOutFullAccessKeys = (list.keys ?? []).filter((k) => keyScope(k.access_key?.permission, "") === "full").length; + } catch { + tokenOutFullAccessKeys = undefined; + } + return { + ...p, + exchangeId, + nowNs, + vault, + quote: quote === null ? null : String(quote), + probeIn: probeIn ? probeIn.toString() : undefined, + probeQuote: probeQuote === null ? null : String(probeQuote), + agentKeyPermission, + tokenOutFullAccessKeys, + }; +} diff --git a/agent/risk-check.test.mjs b/agent/risk-check.test.mjs new file mode 100644 index 0000000..7833bc0 --- /dev/null +++ b/agent/risk-check.test.mjs @@ -0,0 +1,167 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { assessSwap, gatherSwapFacts, keyScope, priceImpactBps, slippageFloor, soldInWindow, spendsInWindow, WINDOW_NS } from "./risk-check.mjs"; + +const NOW = 1_800_000_000_000_000_000n; +const VAULT = "vault.intatto.near"; +const W = "wrap.near"; +const U = "usdt.tether-token.near"; + +function vault(over = {}) { + return { + balance: "0", + frozen: false, + agent_id: "agent.intatto.near", + policy: { + per_tx_cap: "0", + daily_cap: "0", + max_spends_per_24h: 10, + allowlist: [], + tokens: [{ token_id: W, per_tx_cap: "1000", daily_cap: "3000" }], + pools: [{ pool_id: 7, token_ids: [W, U], max_slippage_bps: 100 }], + }, + recent_spends: [], + tokens: [{ token_id: W, balance: "5000", on_exchange: "0" }], + ...over, + }; +} + +function facts(over = {}) { + return { + vaultId: VAULT, + ownerId: "owner.near", + agentId: "agent.intatto.near", + poolId: 7, + tokenIn: W, + tokenOut: U, + amountIn: "1000", + minAmountOut: "3980", + nowNs: NOW, + vault: vault(), + quote: "4000", + probeIn: "10", + probeQuote: "40", + agentKeyPermission: { FunctionCall: { receiver_id: VAULT, method_names: ["agent_swap"], allowance: "1" } }, + tokenOutFullAccessKeys: 0, + ...over, + }; +} + +const codes = (r) => r.reasons.map((x) => x.code); + +test("slippageFloor matches the contract's arithmetic", () => { + assert.equal(slippageFloor(4000n, 100), 3960n); + assert.equal(slippageFloor(12345n, 37), 12299n); // 12345 * 9963 / 10000 = 12299.3 + assert.equal(slippageFloor(9999n, 1), 9998n); +}); + +test("priceImpactBps compares the full trade's rate with a small probe", () => { + assert.equal(priceImpactBps(1000n, 4000n, 10n, 40n), 0n); + assert.equal(priceImpactBps(1000n, 3800n, 10n, 40n), 500n); + assert.equal(priceImpactBps(1000n, 4000n, 0n, 40n), null); +}); + +test("window helpers count only the last 24 hours", () => { + const spends = [ + { timestamp: (NOW - WINDOW_NS).toString(), token_id: W, amount: "900" }, // expired exactly at the edge + { timestamp: (NOW - 1n).toString(), token_id: W, amount: "100" }, + { timestamp: (NOW - 1n).toString(), token_id: null, amount: "5" }, + ]; + assert.equal(soldInWindow(spends, W, NOW), 100n); + assert.equal(soldInWindow(spends, null, NOW), 5n); + assert.equal(spendsInWindow(spends, NOW), 2); +}); + +test("keyScope tells a vault-only key from a full or wider one", () => { + assert.equal(keyScope("FullAccess", VAULT), "full"); + assert.equal(keyScope({ FunctionCall: { receiver_id: VAULT, method_names: ["agent_swap"] } }, VAULT), "vault-only"); + assert.equal(keyScope({ FunctionCall: { receiver_id: VAULT, method_names: [] } }, VAULT), "wider"); + assert.equal(keyScope({ FunctionCall: { receiver_id: VAULT, method_names: ["withdraw"] } }, VAULT), "wider"); + assert.equal(keyScope({ FunctionCall: { receiver_id: "x.near", method_names: ["agent_swap"] } }, VAULT), "other"); +}); + +test("a swap inside the policy, with a tight minimum, is allowed", () => { + const r = assessSwap(facts()); + assert.equal(r.verdict, "allow", JSON.stringify(r.reasons)); + assert.equal(r.floor, "3960"); + assert.equal(r.suggestedMinOut, "3980"); + assert.equal(r.impactBps, "0"); +}); + +test("every contract refusal is a block, with the contract's reason", () => { + assert.deepEqual(codes(assessSwap(facts({ vault: null }))), ["no_vault"]); + assert.ok(codes(assessSwap(facts({ vault: vault({ frozen: true }) }))).includes("frozen")); + assert.ok(codes(assessSwap(facts({ vault: vault({ agent_id: "someone.near" }) }))).includes("not_agent")); + assert.ok(codes(assessSwap(facts({ poolId: 8 }))).includes("pool_not_allowlisted")); + assert.ok(codes(assessSwap(facts({ tokenOut: "other.near" }))).includes("pair_mismatch")); + assert.ok(codes(assessSwap(facts({ tokenIn: U, tokenOut: W }))).includes("token_not_allowed")); + assert.ok(codes(assessSwap(facts({ amountIn: "1001", quote: "4004", minAmountOut: "3990" }))).includes("over_per_tx_cap")); + assert.ok(codes(assessSwap(facts({ quote: null }))).includes("quote_failed")); + assert.ok(codes(assessSwap(facts({ minAmountOut: "3959" }))).includes("slippage_too_loose")); + assert.ok(codes(assessSwap(facts({ minAmountOut: "0" }))).includes("zero_min_amount_out")); + assert.ok(codes(assessSwap(facts({ vault: vault({ tokens: [{ token_id: W, balance: "999", on_exchange: "0" }] }) }))).includes("insufficient_balance")); + for (const code of ["frozen", "pool_not_allowlisted", "slippage_too_loose"]) { + const v = code === "frozen" ? { vault: vault({ frozen: true }) } : code === "pool_not_allowlisted" ? { poolId: 8 } : { minAmountOut: "1" }; + assert.equal(assessSwap(facts(v)).verdict, "block"); + } +}); + +test("daily cap and spend count follow the 24-hour window", () => { + const recent = [ + { spend_id: "1", timestamp: (NOW - 10n).toString(), token_id: W, amount: "1000" }, + { spend_id: "2", timestamp: (NOW - 10n).toString(), token_id: W, amount: "1000" }, + ]; + assert.ok(codes(assessSwap(facts({ vault: vault({ recent_spends: recent }) }))).includes("near_daily_cap")); + const full = [...recent, { spend_id: "3", timestamp: (NOW - 10n).toString(), token_id: W, amount: "500" }]; + assert.ok(codes(assessSwap(facts({ vault: vault({ recent_spends: full }) }))).includes("over_daily_cap")); + const old = recent.map((s) => ({ ...s, timestamp: (NOW - WINDOW_NS - 1n).toString() })); + assert.equal(assessSwap(facts({ vault: vault({ recent_spends: old }) })).verdict, "allow"); + const many = Array.from({ length: 10 }, (_, i) => ({ spend_id: String(i), timestamp: (NOW - 1n).toString(), token_id: null, amount: "1" })); + assert.ok(codes(assessSwap(facts({ vault: vault({ recent_spends: many }) }))).includes("too_many_spends")); +}); + +test("risks the contract does not judge are flagged", () => { + assert.ok(codes(assessSwap(facts({ quote: "3900", minAmountOut: "3870" }))).includes("price_impact")); + const thin = assessSwap(facts({ quote: "3000", minAmountOut: "2980" })); + assert.equal(thin.verdict, "block"); + assert.ok(codes(thin).includes("price_impact")); + assert.ok(codes(assessSwap(facts({ minAmountOut: "3961" }))).includes("loose_min_out")); + assert.ok(codes(assessSwap(facts({ minAmountOut: "4100" }))).includes("min_out_above_quote")); + assert.ok(codes(assessSwap(facts({ tokenOutFullAccessKeys: 2 }))).includes("token_out_upgradeable")); +}); + +test("the signing key must be a function-call key on the vault", () => { + assert.ok(codes(assessSwap(facts({ agentKeyPermission: "FullAccess" }))).includes("agent_key_full_access")); + assert.ok(codes(assessSwap(facts({ agentKeyPermission: { Missing: true } }))).includes("agent_key_missing")); + assert.ok(codes(assessSwap(facts({ agentKeyPermission: { FunctionCall: { receiver_id: "x.near", method_names: [] } } }))).includes("agent_key_wrong_receiver")); + assert.equal(assessSwap(facts({ agentKeyPermission: { FunctionCall: { receiver_id: VAULT, method_names: [] } } })).verdict, "warn"); +}); + +test("gatherSwapFacts reads view calls only and quotes the full trade and a 1% probe", async () => { + const calls = []; + const chain = { + rpc: async (method, params) => { + calls.push(method + ":" + (params.request_type ?? "")); + if (method === "block") return { header: { timestamp_nanosec: NOW.toString() } }; + if (params.request_type === "view_access_key") return { permission: { FunctionCall: { receiver_id: VAULT, method_names: ["agent_swap"] } } }; + if (params.request_type === "view_access_key_list") return { keys: [{ access_key: { permission: "FullAccess" } }] }; + throw new Error("unexpected " + method); + }, + view: async (account, method, args) => { + calls.push(`view:${account}.${method}`); + if (method === "get_vault") return vault(); + if (method === "get_exchange_id") return "v2.ref-finance.near"; + if (method === "get_return") return String(BigInt(args.amount_in) * 4n); + throw new Error("unexpected " + method); + }, + }; + const f = await gatherSwapFacts(chain, { vaultId: VAULT, ownerId: "owner.near", agentId: "agent.intatto.near", agentPublicKey: "ed25519:x", poolId: 7, tokenIn: W, tokenOut: U, amountIn: "1000", minAmountOut: "3980" }); + assert.equal(f.quote, "4000"); + assert.equal(f.probeIn, "10"); + assert.equal(f.probeQuote, "40"); + assert.equal(f.tokenOutFullAccessKeys, 1); + assert.ok(calls.every((c) => !c.startsWith("send_tx") && !c.startsWith("broadcast"))); + const r = assessSwap(f); + assert.equal(r.verdict, "warn"); // the token's full-access key + assert.deepEqual(codes(r), ["token_out_upgradeable"]); +}); diff --git a/web/e2e/prod/meta.spec.ts b/web/e2e/prod/meta.spec.ts index 0d8e82d..96c743f 100644 --- a/web/e2e/prod/meta.spec.ts +++ b/web/e2e/prod/meta.spec.ts @@ -13,7 +13,7 @@ test("link preview tags are in the served HTML, with absolute URLs and a 1200x63 expect(tag("property", "og:title")).toBe("Intatto: the agent can trade. It can't withdraw."); const description = tag("property", "og:description"); - expect(description).toBe("A NEAR vault where your AI agent trades within limits the contract enforces and can never withdraw. Its key is public: take the money if you can."); + expect(description).toBe("Your AI agent's own trading account on NEAR: spending limits the contract enforces, no way to withdraw. Its key is public: take the money if you can."); expect(description!.length, "under 160 characters").toBeLessThan(160); expect(tag("name", "description")).toBe(description); expect(tag("name", "twitter:description")).toBe(description); diff --git a/web/index.html b/web/index.html index 8384c71..33e9af1 100644 --- a/web/index.html +++ b/web/index.html @@ -9,14 +9,14 @@ - + - + @@ -25,7 +25,7 @@ - + Intatto diff --git a/web/src/board/AttemptLog.tsx b/web/src/board/AttemptLog.tsx index 8f1e2b8..6c612a3 100644 --- a/web/src/board/AttemptLog.tsx +++ b/web/src/board/AttemptLog.tsx @@ -12,6 +12,7 @@ import { IndexerDown } from "../ui/IndexerDown"; import { TokenAmount } from "../ui/TokenAmount"; import { useArrivals } from "../ui/useArrivals"; import { useNow } from "../ui/useNow"; +import { MAINNET_TX } from "./JudgeWalkthrough"; type Data = { attempts: Attempt[]; sources: ReadonlySet; more: boolean }; @@ -29,7 +30,7 @@ export const demoSubject = (d: DemoConfig): LogSubject => ({ kind: "demo", owner export function AttemptLog({ query, subject }: { query: UseQueryResult; subject: LogSubject }) { const canary = subject; const titleId = `attempts-title-${subject.kind}`; - const { indexer } = useServices(); + const { indexer, config } = useServices(); const now = useNow(15_000); const data = query.data; const arrivals = useArrivals(data?.attempts.map((a) => a.hash)); @@ -70,6 +71,12 @@ export function AttemptLog({ query, subject }: { query: UseQueryResult; su Every transaction signed with {canary.agentId}'s published key appears here within half a minute, with the reason the vault gave for refusing it. {subject.kind === "demo" ? <> Run node agent/injection-demo.mjs --compromised to add some. : null} + {subject.kind === "canary" && config.networkId === "mainnet" ? ( + <> + {" "} + Until then, here is what a refusal looks like: the same vault contract refusing an agent's swap over its cap, . + + ) : null}

) : ( diff --git a/web/src/board/BoardPage.tsx b/web/src/board/BoardPage.tsx index d5f58b2..d50b5e3 100644 --- a/web/src/board/BoardPage.tsx +++ b/web/src/board/BoardPage.tsx @@ -11,10 +11,12 @@ import { useChainNow } from "../ui/useNow"; import { AgentKeyCard } from "./AgentKeyCard"; import { AttemptLog, canarySubject, demoSubject } from "./AttemptLog"; import { Faq } from "./Faq"; +import { HeroProof, type ProofTarget } from "./HeroProof"; import { HeroStack, SealFace } from "./HeroStack"; import { HowItWorks } from "./HowItWorks"; import { IntegrityCheck } from "./IntegrityCheck"; import { IntentsPanel } from "./IntentsPanel"; +import { JudgeWalkthrough } from "./JudgeWalkthrough"; import { RulesPanel } from "./RulesPanel"; import { TryItSnippet } from "./TryItSnippet"; import { BOARD_POLL_MS, useBoard } from "./useBoard"; @@ -96,10 +98,13 @@ export function BoardPage() { const keyFc = keyPerm && keyPerm !== "FullAccess" ? keyPerm.FunctionCall : null; const keyScoped = keyFc !== null && keyFc.receiver_id === b.vaultId && keyFc.method_names.every((m) => m === "agent_spend" || m === "agent_swap"); - const openTry = () => { - setTab("try"); + const openTab = (id: TabId) => { + setTab(id); tryRef.current?.scrollIntoView({ behavior: reducedMotion() ? "auto" : "smooth", block: "start" }); }; + const openTry = () => openTab("try"); + // The hash is the router's (#/vault), so the hero's proof cells scroll rather than link. + const jump = (id: ProofTarget) => document.getElementById(id)?.scrollIntoView({ behavior: reducedMotion() ? "auto" : "smooth", block: "start" }); const tickerItems: ReactNode[] = [ <> @@ -145,30 +150,34 @@ export function BoardPage() { {state.seal === "broken" ? "The seal is broken." : "The money is still here."}

- Intatto is a NEAR vault that gives an AI agent its own trading account: the agent trades through Rhea and NEAR Intents within limits the contract enforces, and can never withdraw.{" "} - {config.networkId === "mainnet" ? "To prove it, we published the agent's key with a real NEAR bounty on it." : "To prove it, we published the agent's key with a bounty on it, here in testnet NEAR."} + Intatto gives an AI agent its own trading account on NEAR. It trades within limits the contract enforces, and it can never withdraw.{" "} + + {config.networkId === "mainnet" ? "We published this agent's key with real NEAR on it. Anyone can sign with it." : "We published this agent's key with testnet NEAR on it. Anyone can sign with it."} +

-

- Anyone can sign with that key. The vault contract's policy lets it move nothing, and this page shows, live from the chain, whether that is still true. -

-
- {state.seal === "unknown" ? ( - - ) : state.seal === "broken" ? ( - <> - Broken - {state.breaks.join(" ")} - - ) : ( - <> - {frozen ? Frozen : Intact} - - {frozen ? "Frozen by its owner. " : ""}Balance at or above the {formatNear(baselineYocto, FIGURE)} NEAR baseline - {vaultSource ? <> as of block {formatInt(vaultSource.blockHeight)} : null}. - - - )} -
+ + {frozen ? "Frozen by its owner. " : ""}At or above the {formatNear(baselineYocto, FIGURE)} NEAR baseline + {vaultSource ? <>, block {formatInt(vaultSource.blockHeight)} : null}. + + ) + } + intactNs={unbrokenNs} + runEnded={state.runEnded} + missingText={missingYocto !== null ? formatNear(missingYocto, { maxFraction: 4 }) : null} + attempts={attempts ? { count: attempts.length, more: b.attempts.data?.more === true, through: attempts.filter((x) => x.outcome.kind === "succeeded").length } : null} + attemptsFailed={b.attempts.isError} + integrity={integrity} + onJump={jump} + />
+ +
+ + + + + +
+
+ ); +} diff --git a/web/src/board/HowItWorks.tsx b/web/src/board/HowItWorks.tsx index 5c79744..3c50477 100644 --- a/web/src/board/HowItWorks.tsx +++ b/web/src/board/HowItWorks.tsx @@ -2,8 +2,9 @@ import type { ReactNode } from "react"; import { Icon } from "../ui/primitives"; /** - * The three steps, and the limits the contract enforces, named by their fields in src/policy.rs - * (Policy, TokenPolicy, PoolPolicy), src/intent_swap.rs (IntentPair) and the owner methods. + * The three steps in plain words, then the two ways the agent trades, then the full policy + * surface (closed by default), named by its fields in src/policy.rs (Policy, TokenPolicy, + * PoolPolicy), src/intent_swap.rs (IntentPair) and the owner methods. */ const LIMITS: [string, ReactNode][] = [ ["per_tx_cap, daily_cap", "The most NEAR one payment may send, and the most in any 24 hours."], @@ -23,36 +24,53 @@ export function HowItWorks() { -

Create a vault

-

Deposit NEAR and tokens into the vault contract. Only your account can withdraw them.

+

Fund a vault

+

Deposit NEAR and tokens into the vault contract. Only your account can ever withdraw them.

  • Set the limits

    -

    You set them on chain, and the contract checks every agent call against them:

    -
    - {LIMITS.map(([field, what]) => ( -
    -
    {field}
    -
    {what}
    -
    - ))} -
    +

    Caps per trade and per day, the tokens, pools and pairs it may use, a slippage bound and a freeze switch. They live on chain, and the contract checks every agent call against them.

  • -

    Give your agent a key

    -

    - A function-call key that can call only the vault's agent methods: agent_spend and agent_swap, and on the - intents vault agent_intent_swap and settle_intent_swap. It signs as the agent's account, not yours, and - cannot attach a deposit, so it cannot call any owner method: it can trade within your limits, and it can never withdraw. -

    +

    Hand the agent a key

    +

    A key that can only call the vault's trade methods. It can trade within your limits. It cannot withdraw, and it cannot change the rules.

  • + +
    +
    +

    Rhea path

    +

    Direct swaps through Rhea pools, checked against your caps, pool allowlist and a slippage bound set by the exchange's own quote.

    +
    +
    +

    NEAR Intents path

    +

    Intents signed for the vault by the NEAR MPC network, only for pairs you allow and never below your price floor.

    +
    +
    + +
    + Full policy surface +
    + {LIMITS.map(([field, what]) => ( +
    +
    {field}
    +
    {what}
    +
    + ))} +
    +

    + The agent's key is a NEAR function-call key for agent_spend and agent_swap, and on the intents vault{" "} + agent_intent_swap and settle_intent_swap. It signs as the agent's account, not yours, and cannot attach a + deposit, so it cannot call any owner method. +

    +
    +
    Open your vault diff --git a/web/src/board/JudgeWalkthrough.tsx b/web/src/board/JudgeWalkthrough.tsx new file mode 100644 index 0000000..b55bf0a --- /dev/null +++ b/web/src/board/JudgeWalkthrough.tsx @@ -0,0 +1,66 @@ +import type { ReactNode } from "react"; +import { TxLink } from "../ui/primitives"; +import type { ProofTarget } from "./HeroProof"; +import { BOARD_POLL_MS } from "./useBoard"; + +/** + * A 60-second path through the evidence for a first-time reviewer. Mainnet only: every link is a + * mainnet transaction from the README's "Mainnet smoke test, 2026-11-11", "First intent swap, + * 2026-11-11" and the 2026-11-12 prompt-injection runs on vault.intatto.near. + */ +export const MAINNET_TX = { + overCap: "8o7EGQoMWfxUzeST7cTzA63J5MzvxB5ZiWk4NENa8XHU", + badPool: "G5d3Fu838aDw5SSpRvh694TpHLKLg6Vk4LVZRJzssekc", + slippage: "CEpq15YceDiwqHWtpUszmZH8LegBoyyZzgrdJ8HRaEck", + injection: "FNkp2gprgvRs49L6wskMo8JcaYwpoqk2T3YVjGa6oqtw", + swap: "JAFaEDBhStuPgwgCyNJKU7mQH2K7evjG328zrhudoaC8", + withdraw: "2tqfhEiJm1jqAe6DNDZBFnfzbHZqfnmThVfFmJToFtYW", + intentSettle: "73aJTu55356n6QGvcLuj8h5vHy5cY1PGcvGzprM42uKE", + freeze: "6YRqjJXZcNuyeHHSnAeMoURtT6vHfG44VpGJ34uDBCk2", + frozenRefusal: "7bm6uGYGGJG3hJnuJQYoFfxBckCp6Qasvs5fVHzSW3Li", +} as const; + +function Step({ n, title, children }: { n: number; title: string; children: ReactNode }) { + return ( +
  • + +
    +

    {title}

    +

    {children}

    +
    +
  • + ); +} + +export function JudgeWalkthrough({ onJump, onShowKey }: { onJump: (t: ProofTarget) => void; onShowKey: () => void }) { + return ( +
      + + The panel above is read live from the chain: the balance, how long it has held, every attempt.{" "} + + . Anyone can sign with it. + + + The agent's calls refused on mainnet: over the per-trade cap, a pool not allowed,{" "} + slippage too loose, and a prompt-injected agent trying to drain the vault. + + + A Rhea swap within the limits, the owner withdrawing the proceeds, and a{" "} + NEAR Intents swap settled above the owner's price floor. + + + The owner freezes the vault in one call, and the agent's next trade is refused. + + + {" "} + compares the vault's running code hash with the reproducible build, every {BOARD_POLL_MS / 1000} seconds. + +
    + ); +} diff --git a/web/src/console/ConsolePage.tsx b/web/src/console/ConsolePage.tsx index 5cdfe93..b57dd24 100644 --- a/web/src/console/ConsolePage.tsx +++ b/web/src/console/ConsolePage.tsx @@ -8,6 +8,7 @@ import { ActionProvider } from "./ActionSheet"; import { ReadOnlyContext } from "./readOnly"; import { KillSwitch } from "./KillSwitch"; import { NextSteps } from "./NextSteps"; +import { SetupProgress } from "./SetupProgress"; import { PASSKEY_LOCK_ADVICE } from "../wallet/passkey"; import { DepositPanel, LockPanel, ReclaimPanel, WithdrawPanel } from "./MoneyPanels"; import { Overview } from "./Overview"; @@ -113,11 +114,16 @@ function ConnectedConsole({ ownerId, vaultId, readOnly = false }: { ownerId: str )} + {/* The owner's setup checklist, read from the chain; gone once the required steps are done. */} + {!readOnly && c.vault.isSuccess && ( + chainNow} /> + )} + {/* What happens next: always on a live vault viewed read-only; for the owner, once the vault exists and until its agent has been set and has acted. Outside the owner controls, so its copy button works read-only too. It signs nothing. */} {v && (readOnly || v.agent_id == null || v.recent_spends.length === 0) && ( - + )}
    diff --git a/web/src/console/NextSteps.test.tsx b/web/src/console/NextSteps.test.tsx index 357bfe7..4b9a5c2 100644 --- a/web/src/console/NextSteps.test.tsx +++ b/web/src/console/NextSteps.test.tsx @@ -1,7 +1,7 @@ import { render, screen } from "@testing-library/react"; import { describe, expect, it } from "vitest"; import type { VaultView } from "../contract/abi.gen"; -import { addKeyCommand, NextSteps } from "./NextSteps"; +import { addKeyCommand, mcpCommand, NextSteps } from "./NextSteps"; const vault = { agent_id: "demo-agent.intatto.near", recent_spends: [] } as unknown as VaultView; @@ -15,12 +15,21 @@ describe("What happens next", () => { expect(cmd).not.toMatch(/[–—]/); }); + it("gives the MCP command with this vault, owner and agent, and no key", () => { + const cmd = mcpCommand("owner.near", "agent.near", "vault.intatto.near", "mainnet"); + expect(cmd).toContain("claude mcp add --transport stdio intatto --env INTATTO_NETWORK=mainnet --env INTATTO_VAULT_ID=vault.intatto.near"); + expect(cmd).toContain("--env INTATTO_OWNER_ID=owner.near --env INTATTO_AGENT_ID=agent.near"); + expect(cmd).toContain("--env INTATTO_AGENT_KEY_FILE= -- node ./Intatto/agent/mcp-server.mjs"); + expect(cmd).not.toMatch(/ed25519:/); + expect(cmd).not.toMatch(/[–—]/); + }); + it("says why we don't run the agent, and signs nothing: its only button copies", () => { render(); expect(screen.getByText(/Intatto doesn't run your agent for you\. If we did, we'd hold its key, which is the risk this vault exists to remove\./)).toBeTruthy(); expect(screen.getByRole("link", { name: /Bring your own agent/ }).getAttribute("href")).toBe("https://github.com/UEddy/Intatto#bring-your-own-agent"); expect(screen.getByRole("link", { name: /agent\// }).getAttribute("href")).toBe("https://github.com/UEddy/Intatto/tree/master/agent"); - expect(screen.getAllByRole("button").map((b) => b.textContent?.trim())).toEqual(["policy", "Copy command"]); + expect(screen.getAllByRole("button").map((b) => b.textContent?.trim())).toEqual(["policy", "Copy command", "Copy MCP command"]); }); it("read-only, never says your", () => { diff --git a/web/src/console/NextSteps.tsx b/web/src/console/NextSteps.tsx index bab1409..57f1504 100644 --- a/web/src/console/NextSteps.tsx +++ b/web/src/console/NextSteps.tsx @@ -22,9 +22,22 @@ export function addKeyCommand(agentId: string | null, vaultId: string, network: * agent. It signs nothing; the command is for the agent account's own near CLI. Read-only (someone * else's vault), it speaks of "the agent" instead of "your agent". */ -export function NextSteps({ vault, vaultId, network, repoUrl, readOnly }: { vault: VaultView; vaultId: string; network: NetworkId; repoUrl: string; readOnly: boolean }) { +/** + * The command that adds the Intatto MCP server to Claude Code, so an AI agent can check and make + * vault swaps from any MCP client. It runs from a clone of the repo; the key file stays local. + */ +export function mcpCommand(ownerId: string | null, agentId: string | null, vaultId: string, network: NetworkId): string { + return [ + `claude mcp add --transport stdio intatto --env INTATTO_NETWORK=${network} --env INTATTO_VAULT_ID=${vaultId} \\`, + ` --env INTATTO_OWNER_ID=${ownerId ?? ""} --env INTATTO_AGENT_ID=${agentId ?? ""} \\`, + ` --env INTATTO_AGENT_KEY_FILE= -- node ./Intatto/agent/mcp-server.mjs`, + ].join("\n"); +} + +export function NextSteps({ vault, vaultId, network, repoUrl, readOnly, ownerId = null }: { vault: VaultView; vaultId: string; network: NetworkId; repoUrl: string; readOnly: boolean; ownerId?: string | null }) { const who = readOnly ? "the" : "your"; const command = addKeyCommand(vault.agent_id ?? null, vaultId, network); + const mcp = mcpCommand(ownerId, vault.agent_id ?? null, vaultId, network); return (
      @@ -66,6 +79,18 @@ export function NextSteps({ vault, vaultId, network, repoUrl, readOnly }: { vaul .

      +

      + Or give an AI assistant the vault as tools: the MCP server in agent/mcp-server.mjs checks every swap before it signs (allow, + warn or block) and sends nothing until you allow trades. For Claude Code: +

      +
      +
      +              {mcp}
      +            
      +
      + +
      +

    diff --git a/web/src/console/SetupProgress.test.tsx b/web/src/console/SetupProgress.test.tsx new file mode 100644 index 0000000..480827b --- /dev/null +++ b/web/src/console/SetupProgress.test.tsx @@ -0,0 +1,41 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { render, screen, waitFor } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; +import { ServicesProvider, type Services } from "../app/services"; +import { MAINNET } from "../config/networks"; +import type { VaultView } from "../contract/abi.gen"; +import { SetupProgress } from "./SetupProgress"; + +const V = "vault.intatto.near"; +const vault = (over: Partial) => ({ balance: "1", frozen: false, agent_id: "agent.near", policy: {}, recent_spends: [], tokens: [], withdrawals_locked_until: null, ...over }) as unknown as VaultView; + +function renderWith(v: VaultView | null, keys: { permission: unknown }[] | null) { + const chain = { accessKeyList: async () => (keys ? { value: keys } : null) }; + const services = { config: MAINNET, chain } as unknown as Services; + return render( + + + + + , + ); +} + +describe("SetupProgress", () => { + it("reads the agent's keys and marks the next step", async () => { + renderWith(vault({}), [{ permission: { FunctionCall: { allowance: "1", receiver_id: V, method_names: ["agent_swap"] } } }]); + await waitFor(() => expect(screen.getByLabelText("3 of 4 done")).toBeTruthy()); + const next = document.querySelector('[aria-current="step"]'); + expect(next?.textContent).toContain("Connect the agent"); + }); + + it("without a vault-only key, the key step is next", async () => { + renderWith(vault({}), [{ permission: "FullAccess" }]); + await waitFor(() => expect(document.querySelector('[aria-current="step"]')?.textContent).toContain("Give the agent a vault-only key")); + }); + + it("disappears once the required steps are done", async () => { + const { container } = renderWith(vault({ recent_spends: [{}] as never }), [{ permission: { FunctionCall: { allowance: "1", receiver_id: V, method_names: ["agent_swap"] } } }]); + await waitFor(() => expect(container.querySelector(".setup")).toBeNull()); + }); +}); diff --git a/web/src/console/SetupProgress.tsx b/web/src/console/SetupProgress.tsx new file mode 100644 index 0000000..9c98cbe --- /dev/null +++ b/web/src/console/SetupProgress.tsx @@ -0,0 +1,62 @@ +import { useQuery } from "@tanstack/react-query"; +import { useServices } from "../app/services"; +import type { VaultView } from "../contract/abi.gen"; +import { Icon } from "../ui/primitives"; +import { hasVaultKey, progress, setupSteps } from "./setup"; + +/** + * The owner's setup as a checklist read from the chain: what is done, what to do next, and a jump + * to the section that does it. It signs nothing. Hidden once the required steps are done. + */ +function reducedMotion(): boolean { + return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; +} + +export function SetupProgress({ vault, vaultId, lockActive }: { vault: VaultView | null; vaultId: string; lockActive: boolean }) { + const { chain, config } = useServices(); + const agentId = vault?.agent_id ?? null; + const keys = useQuery({ + queryKey: [config.networkId, "agent-keys", agentId], + queryFn: () => chain.accessKeyList(agentId!), + enabled: !!agentId, + refetchInterval: 15_000, + }); + const steps = setupSteps(vault, agentId ? hasVaultKey(keys.data?.value, vaultId) : false, lockActive); + const { done, total } = progress(steps); + if (done === total) return null; + const go = (id: string) => document.getElementById(id)?.scrollIntoView({ behavior: reducedMotion() ? "auto" : "smooth", block: "start" }); + return ( +

    +
    +

    + Set up in {total} steps +

    +

    + {done}/{total} +

    +
    + +
      + {steps.map((s, i) => ( +
    1. + +
    2. + ))} +
    +
    + ); +} diff --git a/web/src/console/setup.test.ts b/web/src/console/setup.test.ts new file mode 100644 index 0000000..b6ee585 --- /dev/null +++ b/web/src/console/setup.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import type { VaultView } from "../contract/abi.gen"; +import { hasVaultKey, progress, setupSteps } from "./setup"; + +const V = "vault.intatto.near"; +const vault = (over: Partial = {}) => ({ balance: "0", frozen: false, agent_id: null, policy: {}, recent_spends: [], tokens: [], withdrawals_locked_until: null, ...over }) as unknown as VaultView; +const fc = (receiver_id: string, method_names: string[]) => ({ permission: { FunctionCall: { allowance: "1", receiver_id, method_names } } }); + +describe("owner setup", () => { + it("starts at funding, with nothing done", () => { + const s = setupSteps(null, null, false); + expect(s.map((x) => x.state)).toEqual(["next", "todo", "todo", "todo", "todo"]); + expect(progress(s)).toEqual({ done: 0, total: 4 }); + }); + + it("moves to the first step not done, and the optional lock is never next", () => { + const funded = vault({ balance: "1" }); + expect(setupSteps(funded, null, false).find((x) => x.state === "next")?.id).toBe("agent"); + const named = vault({ balance: "1", agent_id: "a.near" }); + expect(setupSteps(named, false, false).find((x) => x.state === "next")?.id).toBe("key"); + const keyed = setupSteps(named, true, false); + expect(keyed.find((x) => x.state === "next")?.id).toBe("trade"); + const acted = setupSteps(vault({ balance: "1", agent_id: "a.near", recent_spends: [{}] as never }), true, false); + expect(progress(acted)).toEqual({ done: 4, total: 4 }); + expect(acted.find((x) => x.id === "lock")?.state).toBe("todo"); + }); + + it("counts token deposits as funding", () => { + expect(setupSteps(vault({ tokens: [{ token_id: "wrap.near", balance: "5", on_exchange: "0" }] as never }), null, false)[0]!.state).toBe("done"); + }); + + it("accepts only a function-call key on this vault limited to agent methods", () => { + expect(hasVaultKey(null, V)).toBeNull(); + expect(hasVaultKey([{ permission: "FullAccess" }], V)).toBe(false); + expect(hasVaultKey([fc(V, [])], V)).toBe(false); + expect(hasVaultKey([fc(V, ["withdraw"])], V)).toBe(false); + expect(hasVaultKey([fc("other.near", ["agent_swap"])], V)).toBe(false); + expect(hasVaultKey([{ permission: "FullAccess" }, fc(V, ["agent_spend", "agent_swap"])], V)).toBe(true); + }); +}); diff --git a/web/src/console/setup.ts b/web/src/console/setup.ts new file mode 100644 index 0000000..9eea8cd --- /dev/null +++ b/web/src/console/setup.ts @@ -0,0 +1,61 @@ +import type { VaultView } from "../contract/abi.gen"; +import type { AccessKeyPermission } from "../near/chain"; + +/** The vault methods an agent key may call; a key limited to these cannot move the owner's money out. */ +export const AGENT_METHODS = ["agent_spend", "agent_swap", "agent_intent_swap", "settle_intent_swap"]; + +export type StepState = "done" | "next" | "todo"; + +export interface SetupStep { + readonly id: "fund" | "agent" | "key" | "trade" | "lock"; + readonly title: string; + readonly detail: string; + /** The console section that does this step. */ + readonly target: "deposit" | "policy" | "next" | "lock"; + readonly state: StepState; + readonly optional?: boolean; +} + +/** Whether one of the agent's keys is a function-call key on this vault, limited to agent methods. */ +export function hasVaultKey(keys: readonly { permission: AccessKeyPermission }[] | null | undefined, vaultId: string): boolean | null { + if (keys == null) return null; + return keys.some((k) => { + if (k.permission === "FullAccess") return false; + const call = k.permission.FunctionCall; + return call.receiver_id === vaultId && call.method_names.length > 0 && call.method_names.every((m) => AGENT_METHODS.includes(m)); + }); +} + +/** + * The owner's setup, derived from chain state only: fund the vault, name the agent with its + * limits (set_agent sets both), give the agent a vault-only key, see it act. Locking withdrawals + * is optional. The first step not done is "next". + */ +export function setupSteps(vault: VaultView | null, agentHasVaultKey: boolean | null, lockActive: boolean): SetupStep[] { + const funded = !!vault && (BigInt(vault.balance) > 0n || vault.tokens.some((t) => BigInt(t.balance) > 0n)); + const agent = !!vault?.agent_id; + const acted = !!vault && vault.recent_spends.length > 0; + const raw: Omit[] = [ + { id: "fund", title: "Fund the vault", detail: "Deposit NEAR or tokens. Only you can withdraw them.", target: "deposit" }, + { id: "agent", title: "Name the agent and its limits", detail: "Caps, tokens, pools and slippage, checked by the contract on every call.", target: "policy" }, + { id: "key", title: "Give the agent a vault-only key", detail: "A function-call key for the agent methods only. It cannot withdraw.", target: "next" }, + { id: "trade", title: "Connect the agent", detail: "Any agent that signs NEAR transactions, or any MCP client. Its calls show up here.", target: "next" }, + { id: "lock", title: "Lock withdrawals", detail: "Optional: proves to others you cannot pull the funds before a date.", target: "lock", optional: true }, + ]; + const done: Record = { fund: funded, agent, key: agentHasVaultKey === true, trade: acted, lock: lockActive }; + let nextGiven = false; + return raw.map((s) => { + if (done[s.id]) return { ...s, state: "done" as const }; + if (!nextGiven && !s.optional) { + nextGiven = true; + return { ...s, state: "next" as const }; + } + return { ...s, state: "todo" as const }; + }); +} + +/** Required steps done, and how many there are. */ +export function progress(steps: readonly SetupStep[]): { done: number; total: number } { + const required = steps.filter((s) => !s.optional); + return { done: required.filter((s) => s.state === "done").length, total: required.length }; +} diff --git a/web/src/styles/console.css b/web/src/styles/console.css index 81da9cd..9bb8697 100644 --- a/web/src/styles/console.css +++ b/web/src/styles/console.css @@ -850,3 +850,121 @@ list-style-position: inside; } } + +/* ---------- setup checklist ---------- */ + +.setup { + border: 1px solid var(--ink); + border-radius: var(--radius); + background: var(--paper-raised); + box-shadow: var(--shadow); + padding: 16px 18px 8px; + margin-bottom: 20px; +} +.setup-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; +} +.setup-title { + font-family: var(--font-display); + font-size: clamp(20px, 2.2vw, 26px); + line-height: 1.15; +} +.setup-count { + font-size: 14px; + color: var(--ink-2); +} +.setup-bar { + height: 4px; + margin: 12px 0 6px; + border-radius: 2px; + background: var(--paper-sunk); + overflow: hidden; +} +.setup-bar span { + display: block; + height: 100%; + background: var(--verdigris); + transition: width 240ms ease; +} +.setup-steps { + list-style: none; + margin: 0; + padding: 0; +} +.setup-step + .setup-step { + border-top: 1px solid var(--rule); +} +.setup-btn { + all: unset; + box-sizing: border-box; + display: grid; + grid-template-columns: 28px minmax(0, 1fr); + gap: 12px; + align-items: start; + width: 100%; + min-height: var(--tap); + padding: 10px 0; + cursor: pointer; +} +.setup-btn:focus-visible { + outline: 2px solid var(--focus); + outline-offset: 2px; + border-radius: 4px; +} +.setup-mark { + display: inline-grid; + place-items: center; + width: 26px; + height: 26px; + border-radius: 50%; + border: 1px solid var(--rule-strong); + font-family: var(--font-mono); + font-size: 12.5px; + color: var(--ink-2); +} +.setup-text { + display: grid; + gap: 2px; + padding-top: 3px; +} +.setup-step-title { + font-weight: 500; +} +.setup-optional { + font-weight: 400; + color: var(--ink-3); +} +.setup-detail { + font-size: 14px; + color: var(--ink-2); +} +.setup-step--done .setup-mark { + border-color: var(--verdigris); + background: var(--verdigris); + color: var(--paper); +} +.setup-step--done .setup-step-title { + color: var(--ink-3); +} +.setup-step--next .setup-mark { + border-color: var(--ink); + background: var(--ink); + color: var(--paper); +} +.setup-step--next .setup-step-title::after { + content: " Next"; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.14em; + text-transform: uppercase; + color: var(--ink-3); + margin-left: 8px; +} +@media (prefers-reduced-motion: reduce) { + .setup-bar span { + transition: none; + } +} diff --git a/web/src/styles/landing.css b/web/src/styles/landing.css index 8ea120d..8b3981d 100644 --- a/web/src/styles/landing.css +++ b/web/src/styles/landing.css @@ -154,6 +154,198 @@ max-width: 52ch; } +.hero-what-proof { + color: var(--ink-2); +} + +/* ---------- the hero's proof panel: the four facts, always visible ---------- */ + +.proof { + display: grid; + border: 1px solid var(--ink); + border-radius: var(--radius); + background: var(--paper-raised); + box-shadow: var(--shadow); + max-width: 640px; +} +/* :where keeps the reset at element specificity, so the cells' own padding and borders win. */ +:where(.proof) button { + all: unset; + box-sizing: border-box; + display: grid; + align-content: start; + gap: 4px; + min-width: 0; + cursor: pointer; + transition: background-color 140ms ease; +} +.proof button:hover { + background: color-mix(in srgb, var(--paper-sunk) 60%, transparent); +} +.proof button:focus-visible { + outline: 2px solid var(--focus); + outline-offset: -2px; +} +.proof-bounty { + padding: 16px 18px 18px; + border-bottom: 3px double var(--ink); +} +.proof-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.proof-head .hero-status { + min-height: 0; +} +.proof-label { + font-size: 11.5px; + font-weight: 600; + letter-spacing: 0.16em; + text-transform: uppercase; + color: var(--ink-3); +} +.proof-figure { + font-family: var(--font-display); + font-optical-sizing: auto; + font-size: clamp(56px, 15vw, 84px); + line-height: 0.95; + letter-spacing: -0.025em; + font-variant-numeric: lining-nums tabular-nums; + margin-top: 4px; + overflow-wrap: anywhere; +} +.proof-unit { + font-family: var(--font-text); + font-size: 14px; + font-weight: 600; + letter-spacing: 0.14em; + color: var(--ink-3); + margin-left: 0.5em; +} +.proof-note { + font-size: 13.5px; + line-height: 1.45; + color: var(--ink-2); + margin-top: 6px; +} +.proof-minor { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); +} +.proof-cell { + padding: 12px 12px 14px; +} +.proof-cell + .proof-cell { + border-left: 1px solid var(--rule); +} +.proof-cell .proof-label { + font-size: 10.5px; + letter-spacing: 0.12em; +} +.proof-value { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0 0.22em; + font-family: var(--font-display); + font-size: clamp(22px, 6vw, 30px); + line-height: 1.1; + font-variant-numeric: lining-nums tabular-nums; +} +.proof-small { + font-family: var(--font-text); + font-size: 0.5em; + font-weight: 600; + color: var(--ink-3); + margin-left: 1px; +} +.proof-sub { + font-size: 12px; + line-height: 1.35; + color: var(--ink-3); +} +.proof-code { + align-items: center; +} +.proof-code--matches { + color: var(--verdigris); +} +.proof-code--changed, +.proof--broken .proof-figure, +.proof--broken .proof-cell:first-child .proof-value { + color: var(--wax); +} +.proof--broken { + border-color: var(--wax); +} +@media (min-width: 768px) { + .proof-bounty { + padding: 20px 24px 22px; + } + .proof-cell { + padding: 14px 18px 16px; + } + .proof-cell .proof-label { + font-size: 11.5px; + } +} +@media (prefers-reduced-motion: reduce) { + .proof button { + transition: none; + } +} + +/* ---------- judge it in 60 seconds ---------- */ + +.judge { + display: grid; + margin: 0; + padding: 0; + list-style: none; + border-top: 1px solid var(--ink); +} +.judge-step { + display: grid; + align-content: start; + align-items: start; + grid-template-columns: 36px minmax(0, 1fr); + gap: 12px; + padding: 16px 0 18px; + border-bottom: 1px solid var(--rule); +} +.judge-n { + font-size: 13px; + color: var(--ink-3); + padding-top: 4px; +} +.judge-title { + font-family: var(--font-display); + font-size: clamp(20px, 2vw, 24px); + line-height: 1.2; +} +.judge-body { + margin-top: 4px; + color: var(--ink-2); + max-width: 72ch; +} +.judge-body .txlink { + font-family: var(--font-text); +} +@media (min-width: 1024px) { + .judge { + grid-template-columns: repeat(5, minmax(0, 1fr)); + column-gap: 24px; + } + .judge-step { + grid-template-columns: minmax(0, 1fr); + gap: 8px; + border-bottom: 0; + padding: 18px 0 8px; + } +} + /* ---------- how it works ---------- */ .how-steps { @@ -216,11 +408,76 @@ justify-content: center; margin-top: 28px; } -/* Wide screens: step 2 gets twice the width and lists its limits in two columns, and the three - cards share one height. Phones keep one column. */ +/* The two trade paths, side by side from tablet up. */ +.how-paths { + display: grid; + gap: 1px; + margin-top: 20px; + background: var(--rule); + border: 1px solid var(--rule); + border-radius: 10px; + overflow: hidden; +} +.how-path { + padding: 16px 20px 18px; + background: var(--paper); +} +.how-path p:not(.how-path-name) { + color: var(--ink-2); + font-size: 15px; +} +.how-path-name { + font-size: 11.5px; + font-weight: 600; + letter-spacing: 0.16em; + text-transform: uppercase; + color: var(--ink); + margin-bottom: 4px; +} +.how-more { + margin-top: 12px; +} +.how-more summary { + display: inline-flex; + align-items: center; + min-height: var(--tap); + cursor: pointer; + font-weight: 500; +} +.how-more summary::-webkit-details-marker { + display: none; +} +.how-more summary::before { + content: "+"; + display: inline-grid; + place-items: center; + width: 22px; + height: 22px; + margin-right: 10px; + border: 1px solid var(--rule-strong); + border-radius: 50%; + font-size: 14px; + line-height: 1; +} +.how-more[open] summary::before { + content: "\2212"; +} +.how-key-detail { + margin-top: 14px; + font-size: 14px; + color: var(--ink-2); + max-width: 80ch; +} +@media (min-width: 768px) { + .how-paths { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} +/* Wide screens: three equal steps of one height; the policy list in two columns. Phones keep + one column. */ @media (min-width: 1024px) { .how-steps { - grid-template-columns: minmax(0, 1fr) minmax(0, 2fr) minmax(0, 1fr); + grid-template-columns: repeat(3, minmax(0, 1fr)); align-items: stretch; } .how-limits { @@ -667,3 +924,20 @@ align-self: start; } } + +/* Wide screens: the headline on two lines, so the proof panel and the call to action sit above + the fold at 1440 by 900. */ +@media (min-width: 1024px) { + .board-hero .display--hero { + font-size: clamp(48px, 4.5vw, 66px); + } + .board-hero .hero-what { + font-size: 19px; + } + .board-hero .proof-figure { + font-size: 68px; + } + .board-hero-text { + gap: 16px; + } +}