From 6c7944450c5baff8cfc2900508a64870a0e0516c Mon Sep 17 00:00:00 2001 From: Lexirieru Date: Thu, 12 Nov 2026 20:25:33 +0700 Subject: [PATCH 1/7] feat(engine): crosschain_quote, a NEAR Intents dry quote for stablecoin payments (#273) NEAR Intents has no testnet and HelloNear wallets are testnet, so this is a preview only: 1Click POST /v0/quote with dry: true (no deposit address, no transaction, no key). Asset ids from GET /v0/tokens, amounts in BigInt, refundTo is the Mind's own wallet address. Tests: test/crosschain.test.ts 5/5 (fake 1Click); one live dry quote by hand: 10 USDC on NEAR -> 9.99558 USDC on Base. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q5ZrzK8une3S2YyhDG746e --- engine/package.json | 2 +- engine/src/crosschain.ts | 131 +++++++++++++++++++++++++++++++++ engine/src/tools.ts | 3 +- engine/test/crosschain.test.ts | 111 ++++++++++++++++++++++++++++ 4 files changed, 245 insertions(+), 2 deletions(-) create mode 100644 engine/src/crosschain.ts create mode 100644 engine/test/crosschain.test.ts diff --git a/engine/package.json b/engine/package.json index d22a1493..45eba642 100644 --- a/engine/package.json +++ b/engine/package.json @@ -9,7 +9,7 @@ "dev": "node --env-file=.env --import tsx src/server.ts", "test": "node --env-file=.env --import tsx --test test/*.test.ts", "typecheck": "tsc --noEmit", - "test:unit": "node --import tsx --test test/skills.test.ts test/templates.test.ts test/graph.test.ts test/secrets.test.ts test/verify.test.ts test/tools.test.ts test/builder.test.ts test/wallet-tools.test.ts test/email.test.ts test/composio.test.ts test/calendar.test.ts test/apps.test.ts test/titles.test.ts test/mail-tools.test.ts test/mind.test.ts test/attacks.test.ts test/auto-approve-rules.test.ts test/zoom.test.ts test/counted.test.ts" + "test:unit": "node --import tsx --test test/skills.test.ts test/templates.test.ts test/graph.test.ts test/secrets.test.ts test/verify.test.ts test/tools.test.ts test/builder.test.ts test/wallet-tools.test.ts test/email.test.ts test/composio.test.ts test/calendar.test.ts test/apps.test.ts test/titles.test.ts test/mail-tools.test.ts test/mind.test.ts test/attacks.test.ts test/auto-approve-rules.test.ts test/zoom.test.ts test/counted.test.ts test/crosschain.test.ts" }, "dependencies": { "@ai-sdk/openai-compatible": "3.0.82", diff --git a/engine/src/crosschain.ts b/engine/src/crosschain.ts new file mode 100644 index 00000000..544ebf27 --- /dev/null +++ b/engine/src/crosschain.ts @@ -0,0 +1,131 @@ +// Cross-chain quote (NEAR Intents, 1Click API): what a stablecoin payment from NEAR to another chain would deliver, as a +// preview only. NEAR Intents has no testnet (docs.near-intents.org FAQ, read 12 Nov; HACKATHON.md Q-007 says use +// `dry: true` quotes), and every HelloNear wallet is on testnet, so this tool never gets a deposit address and nothing +// can be sent with it. `dry: true` needs no API key (checked live 12 Nov: 201, 10 USDC on NEAR to Base quoted in ~1 s). +import { createTool } from '@mastra/core/tools' +import { z } from 'zod' +import { walletCall } from './wallet.ts' + +// Read per call, not at import, so tests can point it at a fake. +const oneClick = () => process.env.ONECLICK_URL ?? 'https://1click.chaindefuser.com' + +export const STABLECOINS = ['USDC', 'USDT'] as const + +// Names people use for a chain, to 1Click's `blockchain` ids (GET /v0/tokens, 12 Nov). An id itself also works. +const CHAIN_NAMES: Record = { + ethereum: 'eth', arbitrum: 'arb', solana: 'sol', polygon: 'pol', bnb: 'bsc', 'bnb chain': 'bsc', binance: 'bsc', optimism: 'op', + avalanche: 'avax', tron: 'tron', ton: 'ton', base: 'base', near: 'near', stellar: 'stellar', aptos: 'aptos', sui: 'sui', gnosis: 'gnosis', + scroll: 'scroll', monad: 'monad', 'x layer': 'xlayer', xlayer: 'xlayer', hyperliquid: 'hypercore', +} +export const chainId = (name: string) => { const n = name.trim().toLowerCase(); return CHAIN_NAMES[n] ?? n } + +export type Token = { assetId: string; decimals: number; blockchain: string; symbol: string } + +// The token list changes rarely; one fetch per 10 minutes is enough. +let cached: { at: number; tokens: Token[] } | undefined +export const resetTokenCache = () => { cached = undefined } +async function tokens(): Promise { + if (cached && Date.now() - cached.at < 10 * 60_000) return cached.tokens + const res = await fetch(`${oneClick()}/v0/tokens`, { redirect: 'error', signal: AbortSignal.timeout(15_000) }) + if (!res.ok) throw new Error(`NEAR Intents: token list HTTP ${res.status}`) + const list = (await res.json()) as Token[] + cached = { at: Date.now(), tokens: list } + return list +} + +// One token per chain and symbol. Hyperliquid lists USDC twice (hip1 and erc20); the first listed is used. +export function findToken(list: Token[], symbol: string, chain: string): Token | undefined { + return list.find((t) => t.symbol === symbol && t.blockchain === chain) +} +export const chainsFor = (list: Token[], symbol: string) => [...new Set(list.filter((t) => t.symbol === symbol && t.blockchain !== 'near').map((t) => t.blockchain))].sort() + +// Decimal text and smallest units, in BigInt so no float ever touches an amount. +export function toUnits(amount: string, decimals: number): bigint { + const [w, f = ''] = amount.split('.') + if (f.length > decimals) throw new Error(`at most ${decimals} decimals`) + return BigInt(w) * 10n ** BigInt(decimals) + BigInt(f.padEnd(decimals, '0') || '0') +} +export function fromUnits(units: bigint, decimals: number): string { + const neg = units < 0n + const v = neg ? -units : units + const base = 10n ** BigInt(decimals) + const frac = (v % base).toString().padStart(decimals, '0').replace(/0+$/, '') + return `${neg ? '-' : ''}${v / base}${frac ? `.${frac}` : ''}` +} +// What the route keeps, in the token's own unit: sent minus received, both scaled to the larger decimals. +export function costOf(amountIn: bigint, dIn: number, amountOut: bigint, dOut: number): string { + const d = Math.max(dIn, dOut) + return fromUnits(amountIn * 10n ** BigInt(d - dIn) - amountOut * 10n ** BigInt(d - dOut), d) +} + +export const NOT_SENT = 'Preview only: nothing was sent. NEAR Intents runs on NEAR mainnet only and this Mind\'s wallet is on testnet, so it cannot send this payment yet.' + +type QuoteAnswer = { + quote?: { amountIn: string; amountOut: string; minAmountOut?: string; timeEstimate?: number } + correlationId?: string + timestamp?: string + message?: string +} + +export const crosschainQuote = createTool({ + id: 'crosschain_quote', + description: 'Preview a stablecoin payment from NEAR to another chain through NEAR Intents: how much the recipient would get, the cost and the time. A quote only: it sends nothing and asks no approval, and this Mind cannot send cross-chain yet (NEAR Intents is mainnet only, the wallet is testnet). The recipient address must be one the owner typed in this conversation.', + inputSchema: z.object({ + token: z.enum(STABLECOINS).describe('the stablecoin on NEAR to send'), + amount: z.string().regex(/^\d{1,9}(\.\d{1,6})?$/, 'a decimal amount, e.g. "10" or "2.5"').describe('how much of it to send'), + toChain: z.string().min(2).max(20).describe('the chain to deliver on, e.g. "base", "arbitrum", "solana", "ethereum", "polygon", "tron"'), + recipient: z.string().min(20).max(100).describe('the recipient\'s address on that chain, exactly as the owner gave it'), + toToken: z.enum(STABLECOINS).optional().describe('the stablecoin to deliver; the same as token when left out'), + }), + outputSchema: z.object({ + status: z.literal('quote_only'), + from: z.object({ chain: z.literal('near'), token: z.string(), amount: z.string() }), + to: z.object({ chain: z.string(), token: z.string(), recipient: z.string(), amount: z.string(), minAmount: z.string() }), + cost: z.string().describe('sent minus received, in the token'), + seconds: z.number().describe('NEAR Intents\' estimate of the time it takes'), + quoteId: z.string(), + quotedAt: z.string(), + note: z.string(), + }), + execute: async ({ token, amount, toChain, recipient, toToken }, context) => { + const out = toToken ?? token + const chain = chainId(toChain) + if (chain === 'near') throw new Error('this is for other chains; a payment on NEAR uses send_payment') + const list = await tokens() + const from = findToken(list, token, 'near') + const to = findToken(list, out, chain) + if (!from) throw new Error(`NEAR Intents lists no ${token} on NEAR`) + if (!to) throw new Error(`NEAR Intents lists no ${out} on "${toChain}". ${out} goes to: ${chainsFor(list, out).join(', ')}`) + const amountIn = toUnits(amount, from.decimals) + if (amountIn <= 0n) throw new Error('the amount must be more than 0') + // Refunds would go back to this Mind's own wallet. A dry quote moves nothing, but 1Click requires the field. + const { address } = await walletCall<{ address: string }>(context, 'GET', '/internal/v1/wallet/balance') + const res = await fetch(`${oneClick()}/v0/quote`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + dry: true, swapType: 'EXACT_INPUT', slippageTolerance: 100, + originAsset: from.assetId, destinationAsset: to.assetId, amount: amountIn.toString(), + depositType: 'ORIGIN_CHAIN', recipient, recipientType: 'DESTINATION_CHAIN', refundTo: address, refundType: 'ORIGIN_CHAIN', + deadline: new Date(Date.now() + 10 * 60_000).toISOString(), + }), + redirect: 'error', + signal: AbortSignal.timeout(20_000), + }) + const body = (await res.json().catch(() => ({}))) as QuoteAnswer + // 1Click's own words for a refusal ("recipient is not valid", an amount below the minimum) are safe to pass on. + if (!res.ok || !body.quote) throw new Error(`NEAR Intents: ${body.message ?? `HTTP ${res.status}`}`) + const q = body.quote + const got = BigInt(q.amountOut) + return { + status: 'quote_only' as const, + from: { chain: 'near' as const, token, amount: fromUnits(amountIn, from.decimals) }, + to: { chain, token: out, recipient, amount: fromUnits(got, to.decimals), minAmount: fromUnits(BigInt(q.minAmountOut ?? q.amountOut), to.decimals) }, + cost: costOf(amountIn, from.decimals, got, to.decimals), + seconds: q.timeEstimate ?? 0, + quoteId: body.correlationId ?? '', + quotedAt: body.timestamp ?? new Date().toISOString(), + note: NOT_SENT, + } + }, +}) diff --git a/engine/src/tools.ts b/engine/src/tools.ts index 830fe1d1..02623ea6 100644 --- a/engine/src/tools.ts +++ b/engine/src/tools.ts @@ -12,6 +12,7 @@ import type { Mind } from './mind.ts' import { addressOf, composioTool, gmail, toListed, toRead } from './composio.ts' import { appTools } from './apps.ts' import { zoomTools } from './zoom.ts' +import { crosschainQuote } from './crosschain.ts' import { ISO_WITH_OFFSET, MAX_ATTENDEES, MAX_RANGE_DAYS, checkAttendees, composioTiming, createSampleEvent, createSampleMeeting, listSampleCalendar, listedEvents, withLocalTimes, type CalendarEvent, meetLinkOf, rangeOf, withMeetLink, @@ -792,7 +793,7 @@ const nearCheckTransfer = createTool({ }) export const toolRegistry = { - get_time: getTime, add_numbers: addNumbers, split_amount: splitAmountTool, http_request: httpRequest, near_view_account: nearViewAccount, near_check_transfer: nearCheckTransfer, + get_time: getTime, add_numbers: addNumbers, split_amount: splitAmountTool, http_request: httpRequest, near_view_account: nearViewAccount, near_check_transfer: nearCheckTransfer, crosschain_quote: crosschainQuote, buy_data: buyData, get_quotes: getQuotes, sell_offer: sellOffer, buy_from_mind: buyFromMind, send_payment: sendPayment, get_balance: getBalance, list_payments: listPayments, gmail_list_emails: gmailListEmails, gmail_read_email: gmailReadEmail, gmail_create_draft: gmailCreateDraft, gmail_organize: gmailOrganize, googlecalendar_list_events: calendarListEvents, googlecalendar_create_event: calendarCreateEvent, diff --git a/engine/test/crosschain.test.ts b/engine/test/crosschain.test.ts new file mode 100644 index 00000000..d00c9652 --- /dev/null +++ b/engine/test/crosschain.test.ts @@ -0,0 +1,111 @@ +// Cross-chain quote (NEAR Intents 1Click, dry run) against a fake 1Click and a fake backend. No network, LLM or database. +// Run: node --import tsx --test test/crosschain.test.ts +import { after, before, test } from 'node:test' +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import type { AddressInfo } from 'node:net' +import { toolRegistry } from '../src/tools.ts' +import { WALLET_KEY, walletContext } from '../src/wallet.ts' +import { chainId, costOf, fromUnits, resetTokenCache, toUnits } from '../src/crosschain.ts' + +const USDC_NEAR = 'nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1' +const USDC_BASE = 'nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near' +const USDC_BSC = 'nep141:bnb-0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d.omdep.near' +// From GET /v0/tokens on 12 Nov (USDC on BNB Chain has 18 decimals). +const TOKENS = [ + { assetId: USDC_NEAR, decimals: 6, blockchain: 'near', symbol: 'USDC' }, + { assetId: USDC_BASE, decimals: 6, blockchain: 'base', symbol: 'USDC' }, + { assetId: USDC_BSC, decimals: 18, blockchain: 'bsc', symbol: 'USDC' }, + { assetId: 'nep141:usdt.tether-token.near', decimals: 6, blockchain: 'near', symbol: 'USDT' }, +] +const BASE_ADDR = '0x8ba1f109551bD432803012645Ac136ddd64DBA72' +const BAD_ADDR = '0x' + 'f'.repeat(40) + +const quotes: any[] = [] +const oneClick = createServer(async (req, res) => { + let raw = '' + for await (const c of req) raw += c + const send = (status: number, json: unknown) => res.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(json)) + if (req.url === '/v0/tokens') return send(200, TOKENS) + if (req.url !== '/v0/quote') return send(404, {}) + const body = JSON.parse(raw) + quotes.push(body) + if (body.recipient === BAD_ADDR) return send(400, { message: 'recipient is not valid' }) + // The shape of a live dry answer (12 Nov): 10 USDC on NEAR -> 9.99558 on Base. + const out = body.destinationAsset === USDC_BSC ? '9995580000000000000' : '9995580' + const min = body.destinationAsset === USDC_BSC ? '9895624000000000000' : '9895624' + send(201, { quote: { amountIn: body.amount, amountInFormatted: '10.0', amountOut: out, minAmountOut: min, timeEstimate: 22 }, correlationId: 'q-1', timestamp: '2026-11-12T12:54:15.113Z' }) +}) +const backend = createServer((req, res) => { + if (req.url === '/internal/v1/wallet/balance') return res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ address: 'a'.repeat(64), balanceNear: '1' })) + res.writeHead(404).end('{}') +}) + +before(async () => { + await new Promise((r) => oneClick.listen(0, '127.0.0.1', r)) + await new Promise((r) => backend.listen(0, '127.0.0.1', r)) + process.env.ONECLICK_URL = `http://127.0.0.1:${(oneClick.address() as AddressInfo).port}` + process.env.BACKEND_URL = `http://127.0.0.1:${(backend.address() as AddressInfo).port}` + process.env.ENGINE_API_KEY ??= 'engine-key-for-tests' + resetTokenCache() +}) +after(async () => { + await new Promise((r) => oneClick.close(() => r())) + await new Promise((r) => backend.close(() => r())) +}) + +const ctx = (token?: string) => ({ requestContext: { get: (k: string) => (k === WALLET_KEY ? walletContext(token) : undefined) } }) +const run = (input: unknown, token: string | undefined = 'wt_test.abc') => toolRegistry.crosschain_quote.execute!(input as any, ctx(token) as any) as Promise + +test('amounts are converted with BigInt, never floats', () => { + assert.equal(toUnits('10', 6), 10_000_000n) + assert.equal(toUnits('2.5', 18), 2_500_000_000_000_000_000n) + assert.throws(() => toUnits('0.0000001', 6), /at most 6 decimals/) + assert.equal(fromUnits(9_995_580n, 6), '9.99558') + assert.equal(fromUnits(10_000_000n, 6), '10') + assert.equal(costOf(10_000_000n, 6, 9_995_580_000_000_000_000n, 18), '0.00442') + assert.equal(chainId('Arbitrum'), 'arb') + assert.equal(chainId('BNB Chain'), 'bsc') + assert.equal(chainId('base'), 'base') +}) + +test('a dry quote: USDC on NEAR to Base, refunds to the Mind\'s own wallet, nothing to deposit', async () => { + const out = await run({ token: 'USDC', amount: '10', toChain: 'Base', recipient: BASE_ADDR }) + const sent = quotes.at(-1) + assert.equal(sent.dry, true, 'never a live quote') + assert.equal(sent.swapType, 'EXACT_INPUT') + assert.equal(sent.originAsset, USDC_NEAR) + assert.equal(sent.destinationAsset, USDC_BASE) + assert.equal(sent.amount, '10000000') + assert.equal(sent.recipient, BASE_ADDR) + assert.equal(sent.refundTo, 'a'.repeat(64)) + assert.deepEqual(out, { + status: 'quote_only', + from: { chain: 'near', token: 'USDC', amount: '10' }, + to: { chain: 'base', token: 'USDC', recipient: BASE_ADDR, amount: '9.99558', minAmount: '9.895624' }, + cost: '0.00442', seconds: 22, quoteId: 'q-1', quotedAt: '2026-11-12T12:54:15.113Z', + note: out.note, + }) + assert.match(out.note, /nothing was sent/) + assert.equal(JSON.stringify(out).includes('depositAddress'), false) +}) + +test('different decimals on each side (USDC on BNB Chain has 18)', async () => { + const out = await run({ token: 'USDC', amount: '10', toChain: 'bnb', recipient: BASE_ADDR }) + assert.equal(quotes.at(-1).destinationAsset, USDC_BSC) + assert.equal(out.to.amount, '9.99558') + assert.equal(out.cost, '0.00442') +}) + +test('refusals: an unknown chain lists where it can go, NEAR itself, a bad address, no wallet', async () => { + const before = quotes.length + await assert.rejects(run({ token: 'USDC', amount: '10', toChain: 'dogecoin', recipient: BASE_ADDR }), /no USDC on "dogecoin"\. USDC goes to: base, bsc/) + await assert.rejects(run({ token: 'USDC', amount: '10', toChain: 'near', recipient: BASE_ADDR }), /send_payment/) + await assert.rejects(run({ token: 'USDC', amount: '0', toChain: 'base', recipient: BASE_ADDR }), /more than 0/) + await assert.rejects(run({ token: 'USDC', amount: '10', toChain: 'base', recipient: BASE_ADDR }, ''), /no wallet yet/) + assert.equal(quotes.length, before, 'none of those asked for a quote') +}) + +test('1Click\'s own refusal comes back in its words', async () => { + await assert.rejects(run({ token: 'USDC', amount: '10', toChain: 'base', recipient: BAD_ADDR }), /NEAR Intents: recipient is not valid/) +}) From b7e854b468a7ca85a63a4584781ea378de28c5f0 Mon Sep 17 00:00:00 2001 From: Lexirieru Date: Thu, 12 Nov 2026 20:25:33 +0700 Subject: [PATCH 2/7] feat(engine): payments skill quotes cross-chain stablecoin payments (#273) The Payments Mind template already carries the payments skill, so no owner adds anything. Its blurb names the quote: with "(cannot send them yet)" a try-out Mind with ~20 skills refused from the skill list without calling the tool (Chrome, 12 Nov). Tests: test:unit 177/177; skills-crosschain (live, a 14-skill Mind, fake 1Click) 9/9 over 3 runs; bun run test 315/317 (autopilot timing and one calendar-local-times run; both pass alone, 7/7 and 3/3); Chrome e2e on a local stack with the real 1Click: Base USDC and Solana USDT quotes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q5ZrzK8une3S2YyhDG746e --- engine/skills/payments/SKILL.md | 7 +- engine/test/skills-crosschain.test.ts | 106 ++++++++++++++++++++++++++ engine/test/skills.test.ts | 2 +- 3 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 engine/test/skills-crosschain.test.ts diff --git a/engine/skills/payments/SKILL.md b/engine/skills/payments/SKILL.md index 49e706a9..bf317604 100644 --- a/engine/skills/payments/SKILL.md +++ b/engine/skills/payments/SKILL.md @@ -1,13 +1,13 @@ --- name: payments -description: Use when the owner asks to pay a bill, an invoice or a subscription, to send testnet NEAR to someone, or about this Mind's wallet balance and past payments. +description: Use when the owner asks to pay a bill, an invoice or a subscription, to send testnet NEAR to someone, to pay USDC or USDT on another chain, or about this Mind's wallet balance and past payments. metadata: hellonear: - tools: [send_payment, get_balance, list_payments, get_time, near_view_account] + tools: [send_payment, get_balance, list_payments, get_time, near_view_account, crosschain_quote] connections: [near-wallet] status: available title: Payments - blurb: sends testnet NEAR and pays bills after the owner approves + blurb: sends testnet NEAR and pays bills after the owner approves; quotes USDC or USDT payments to other chains (Base, Solana…) through NEAR Intents references: [near-recipients.md] --- @@ -22,3 +22,4 @@ metadata: 7. After a `sent` payment, report the amount, the recipient and the `txHash` in one sentence. A `pending` payment waits for the owner in the OutLayer dashboard; say so. 8. Use `get_balance` for any question about this Mind's own balance and `list_payments` for past payments. Never guess either. 9. If a tool says this Mind has no wallet yet, tell the owner to create one on the Mind's wallet screen. +10. To pay USDC or USDT on another chain (Base, Arbitrum, Solana, Ethereum…), call `crosschain_quote` with the address the owner typed. It is a preview: show what the recipient would get, the cost and the time, and say plainly that nothing was sent and this Mind can't send cross-chain yet. Never call `send_payment` for it. diff --git a/engine/test/skills-crosschain.test.ts b/engine/test/skills-crosschain.test.ts new file mode 100644 index 00000000..139c94e7 --- /dev/null +++ b/engine/test/skills-crosschain.test.ts @@ -0,0 +1,106 @@ +// Prompt tests for the cross-chain quote (NEAR Intents 1Click, dry run) in the payments skill, against real NEAR AI +// Cloud and the local Postgres. A fake backend stands in for the wallet routes and a fake 1Click answers like the live +// API did on 12 Nov, so no test depends on market makers. Run: node --env-file=.env --import tsx --test test/skills-crosschain.test.ts +import { after, before, test } from 'node:test' +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import type { AddressInfo } from 'node:net' +import { randomUUID } from 'node:crypto' +import { server } from '../src/server.ts' +import { resetTokenCache } from '../src/crosschain.ts' + +let base = '' +const key = process.env.ENGINE_API_KEY! +const TOKEN = `wt_${randomUUID()}` +const BASE_ADDR = '0x8ba1f109551bD432803012645Ac136ddd64DBA72' +const SOL_ADDR = '7EcDhSYGxXyscszYEp35KHN8vvw3svAuLKTzXwCFLtV' + +type Ev = Record +async function chat(message: string, threadId = randomUUID()): Promise { + const res = await fetch(`${base}/v1/minds/penny/chat`, { + method: 'POST', headers: { 'content-type': 'application/json', 'x-engine-key': key }, + body: JSON.stringify({ userId: `usr_cc_${randomUUID().slice(0, 8)}`, threadId, walletToken: TOKEN, message, mind }), + }) + assert.equal(res.status, 200, await res.clone().text()) + return (await res.text()).split('\n').filter((l) => l.startsWith('data: ')).map((l) => JSON.parse(l.slice(6))) +} +// The Payments Mind template's skills plus calendar and mail ones: with only `payments` equipped the model always +// called the tool, but a try-out Mind with ~20 skills answered from the skill list alone (Chrome, 12 Nov). +const SKILLS = ['payments', 'daily-planner', 'recipient-guard', 'split-bill', 'treasury-report', 'spending-audit', 'best-price', 'freeze-advisor', 'calendar-conflicts', 'email-triage', 'phishing-detector', 'subscriptions', 'invoice', 'near-account'] +const mind = { templateId: 'payments-mind', name: 'Penny', soul: { identity: 'You handle the owner\'s payments carefully.', invariants: ['Never invent facts.'], priors: [] }, skills: SKILLS.map((skillId) => ({ skillId })) } +const reply = (evs: Ev[]) => evs.filter((e) => e.type === 'run.finished').map((e) => e.text ?? '').join('\n') +const calls = (evs: Ev[], tool: string) => evs.filter((e) => e.type === 'tool.called' && e.tool === tool) + +const TOKENS = [ + { assetId: 'nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1', decimals: 6, blockchain: 'near', symbol: 'USDC' }, + { assetId: 'nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near', decimals: 6, blockchain: 'base', symbol: 'USDC' }, + { assetId: 'nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near', decimals: 6, blockchain: 'sol', symbol: 'USDC' }, + { assetId: 'nep141:usdt.tether-token.near', decimals: 6, blockchain: 'near', symbol: 'USDT' }, + { assetId: 'nep141:sol-c800a4bd850783ccb82c2b2c7e84175443606352.omft.near', decimals: 6, blockchain: 'sol', symbol: 'USDT' }, +] +const quotes: any[] = [] +const oneClick = createServer(async (req, res) => { + let raw = '' + for await (const c of req) raw += c + const send = (status: number, json: unknown) => res.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(json)) + if (req.url === '/v0/tokens') return send(200, TOKENS) + const body = JSON.parse(raw) + quotes.push(body) + const out = (BigInt(body.amount) * 99956n) / 100000n + send(201, { quote: { amountIn: body.amount, amountOut: out.toString(), minAmountOut: ((out * 99n) / 100n).toString(), timeEstimate: 22 }, correlationId: randomUUID(), timestamp: new Date().toISOString() }) +}) +let sends = 0 +const backend = createServer(async (req, res) => { + for await (const _ of req) void _ + const send = (json: unknown) => res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(json)) + if (req.headers['x-wallet-token'] !== TOKEN) return res.writeHead(401).end('{}') + if (req.url === '/internal/v1/wallet/balance') return send({ address: 'a'.repeat(64), balanceNear: '0.42' }) + if (req.url?.startsWith('/internal/v1/wallet/payments')) return send({ payments: [] }) + if (req.url === '/internal/v1/wallet/send_payment') { sends++; return send({ paymentId: 'p1', status: 'sent', txHash: 'FakeTx1' }) } + res.writeHead(404).end('{}') +}) + +before(async () => { + await new Promise((r) => oneClick.listen(0, '127.0.0.1', r)) + await new Promise((r) => backend.listen(0, '127.0.0.1', r)) + process.env.ONECLICK_URL = `http://127.0.0.1:${(oneClick.address() as AddressInfo).port}` + process.env.BACKEND_URL = `http://127.0.0.1:${(backend.address() as AddressInfo).port}` + resetTokenCache() + await new Promise((r) => server.listen(0, r)) + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}` +}) +after(async () => { + await new Promise((r) => oneClick.close(() => r())) + await new Promise((r) => backend.close(() => r())) + await new Promise((r) => server.close(() => r())) +}) + +test('"send 10 USDC to ": a dry quote with the owner\'s address, no payment card, says nothing was sent', async () => { + const evs = await chat(`Send 10 USDC to ${BASE_ADDR} on Base.`) + const q = calls(evs, 'crosschain_quote') + assert.equal(q.length, 1, JSON.stringify(evs.filter((e) => e.type === 'tool.called').map((e) => [e.tool, e.args]))) + assert.deepEqual({ ...q[0].args, toChain: String(q[0].args.toChain).toLowerCase() }, { token: 'USDC', amount: '10', toChain: 'base', recipient: BASE_ADDR }) + assert.equal(quotes.at(-1).dry, true) + assert.ok(!evs.some((e) => e.type === 'tool.approval_required'), 'no approval card for a quote') + assert.equal(sends, 0) + const text = reply(evs) + assert.match(text, /9\.99/, text) + assert.match(text, /(not|nothing).{0,40}(sent|send)|can'?t send|cannot send|preview|quote/i, text) +}) + +test('USDT on Solana: the token and chain follow the owner\'s words', async () => { + const evs = await chat(`I want to pay 25 USDT to ${SOL_ADDR} on Solana. How much would they get?`) + const q = calls(evs, 'crosschain_quote') + assert.equal(q.length, 1, JSON.stringify(evs.filter((e) => e.type === 'tool.called').map((e) => [e.tool, e.args]))) + assert.equal(q[0].args.token, 'USDT') + assert.equal(q[0].args.amount, '25') + assert.match(String(q[0].args.toChain), /^sol(ana)?$/i) + assert.equal(q[0].args.recipient, SOL_ADDR) + assert.equal(sends, 0) +}) + +test('a NEAR testnet payment still goes through send_payment with its approval card', async () => { + const evs = await chat('Pay 0.01 NEAR to alice.testnet.') + assert.equal(calls(evs, 'crosschain_quote').length, 0) + assert.ok(evs.some((e) => e.type === 'tool.approval_required' && e.tool === 'send_payment'), JSON.stringify(evs.filter((e) => e.type === 'tool.called').map((e) => e.tool))) +}) diff --git a/engine/test/skills.test.ts b/engine/test/skills.test.ts index 9a5e8010..9ea5c355 100644 --- a/engine/test/skills.test.ts +++ b/engine/test/skills.test.ts @@ -9,7 +9,7 @@ test('every SKILL.md in engine/skills parses and only uses registered tools', () assert.deepEqual(skillCatalog.get('daily-planner')?.tools, ['get_time', 'add_numbers', 'googlecalendar_list_events', 'googlecalendar_create_event', 'googlecalendar_create_meeting', 'googlecalendar_block_time', 'googlecalendar_find_free_time', 'googlecalendar_move_event']) assert.deepEqual(skillCatalog.get('daily-planner')?.connections, ['googlecalendar', 'googlemeet']) assert.equal(skillCatalog.get('payments')?.status, 'available') - assert.deepEqual(skillCatalog.get('payments')?.tools, ['send_payment', 'get_balance', 'list_payments', 'get_time', 'near_view_account']) + assert.deepEqual(skillCatalog.get('payments')?.tools, ['send_payment', 'get_balance', 'list_payments', 'get_time', 'near_view_account', 'crosschain_quote']) assert.equal(skillCatalog.get('email-triage')?.status, 'available') assert.deepEqual(skillCatalog.get('email-triage')?.tools, ['gmail_list_emails', 'gmail_read_email', 'gmail_create_draft', 'gmail_organize', 'get_time']) assert.equal(skillCatalog.get('daily-planner')?.skill.name, 'daily-planner') From d69fdda314aab633564fde745d27d0c6409bc893 Mon Sep 17 00:00:00 2001 From: Lexirieru Date: Thu, 12 Nov 2026 20:25:33 +0700 Subject: [PATCH 3/7] docs: cross-chain quote (#273) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q5ZrzK8une3S2YyhDG746e --- docs/api-contract.md | 4 +++- engine/.env.example | 2 ++ engine/CLAUDE.md | 1 + 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index f10a23b5..dd8a3f9e 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -98,6 +98,8 @@ Several sellers (#176, Best Price Buyer) **[tested, fake OutLayer and RPC; not l - Intended config once the demo wallet lists both accounts (decided 11 Nov): `SHOP_SELLERS="lin1er.testnet:1.0,testing7.testnet:0.8"`. Not set anywhere yet. - Engine: `get_quotes` `{ item }` → `{ item, title, quotes, cheapestOnYourList }` (`?quotes=1`); `buy_data` takes an optional `seller` (`?seller=`). +**Cross-chain quote (#273), engine tool `crosschain_quote`, payments skill:** `{ token: "USDC" | "USDT", amount, toChain, recipient, toToken? }` → `{ status: "quote_only", from: { chain: "near", token, amount }, to: { chain, token, recipient, amount, minAmount }, cost, seconds, quoteId, quotedAt, note }`. A NEAR Intents 1Click `POST /v0/quote` with `dry: true` (no deposit address, no transaction, no key); the engine reads the Mind's wallet address from `GET /internal/v1/wallet/balance` for `refundTo` only, so no backend change. No approval: nothing moves. NEAR Intents is mainnet only and the wallets are testnet, so this is a preview and the Mind says so **[tested: unit with a fake 1Click; live prompt tests with a fake 1Click 9/9 on 12 Nov; one live dry quote against 1Click by hand]**. + **Mind as Seller (#181)** **[tested, fake OutLayer and RPC; not live yet]**. Same 402 pattern, paid to the selling Mind's own wallet. Both routes take `X-Engine-Key` and the calling Mind's run `X-Wallet-Token`. - `PUT /internal/v1/offers/{item}`: the selling Mind publishes or replaces one offer. `item` = `[a-z0-9][a-z0-9-]{0,39}`. Body (strict) `{ title (≤ 200), priceNear (> 0, ≤ 1), content (≤ 20,000) }` → `200 { sellerMindId, item, title, priceNear, payTo }`, `payTo` = this Mind's own wallet address. `403 demo_not_allowed` for a try-out or playground Mind (the shared demo wallet is nobody's own). - `GET /internal/v1/minds/{sellerMindId}/offers/{item}[?tx=]`: the buying Mind. Without `tx`: **`402`** `{ status: "payment_required", sellerMindId, item, title, priceNear, payTo }`. With `tx`: `200 { status: "paid", sellerMindId, item, title, content, receipt: { txHash, paymentId, amountNear, payTo } }` only if the buyer's own `wallet_payments` row has that hash as `sent` to `payTo` for at least the price within the last hour, NEAR RPC `tx` shows success with signer = the buyer's wallet and receiver = the seller's, and the hash was never redeemed (`offer_purchases`). Otherwise `402` with the offer and `error` = `payment_not_found` \| `payment_does_not_match` \| `payment_not_on_chain`, or `409 payment_already_used`. `404 no_offer` (unknown Mind, no such item, or a try-out seller), `400 own_offer`, `400 invalid_tx_hash`. @@ -213,7 +215,7 @@ Canvas (React Flow shape; `position` and extra fields are kept for the editor): ``` Rules (the engine answers `400` with `issues` otherwise) **[tested]**: -- Node types: `trigger` (exactly one; optional `inputs` and `schedule`), `agent` (the Mind itself, `{ prompt }`), `tool` (`{ tool, args }`, `tool` = a tool key such as `near_view_account`, `add_numbers`, `get_time`), `http` (the `http_request` tool), `condition` (`left` is one reference, `op` is `eq | ne | lt | lte | gt | gte`, `right` a literal).. An If compares one value, never a list: every tool that returns a list of results also returns `count` (#264: `googlecalendar_list_events` `events`, `googlecalendar_find_free_time` `slots`, `gmail_list_emails` / `outlook_list_emails` `emails`, `mail_list` `messages`, `list_payments` `payments`, `get_quotes` `quotes`, `googlesheets_find_spreadsheets` `spreadsheets`, `googlesheets_read_range` `values`, `googledrive_find_files` `files`, `slack_list_channels` `channels`, `notion_search` `results`, `notion_query_database` `rows`, `zoom_list_meetings` `meetings`), so "Number of events > 0" is `{{steps..count}}` `gt` `0`; `{{steps..events.length}}` is refused with `400 invalid_workflow`. An agent step's reply is `{{steps..text}}`, compared as exact text (`"Yes"` is not `eq` `"yes"`) **[tested: `engine/test/workflows.test.ts` (count on the sample calendar takes the then way, `events.length` refused), 11 Nov; agent `text` saved and run once by hand]**. At most 20 nodes. +- Node types: `trigger` (exactly one; optional `inputs` and `schedule`), `agent` (the Mind itself, `{ prompt }`), `tool` (`{ tool, args }`, `tool` = a tool key such as `near_view_account`, `add_numbers`, `get_time`), `http` (the `http_request` tool), `condition` (`left` is one reference, `op` is `eq | ne | lt | lte | gt | gte`, `right` a literal). An If compares one value, never a list: every tool that returns a list of results also returns `count` (#264: `googlecalendar_list_events` `events`, `googlecalendar_find_free_time` `slots`, `gmail_list_emails` / `outlook_list_emails` `emails`, `mail_list` `messages`, `list_payments` `payments`, `get_quotes` `quotes`, `googlesheets_find_spreadsheets` `spreadsheets`, `googlesheets_read_range` `values`, `googledrive_find_files` `files`, `slack_list_channels` `channels`, `notion_search` `results`, `notion_query_database` `rows`, `zoom_list_meetings` `meetings`), so "Number of events > 0" is `{{steps..count}}` `gt` `0`; `{{steps..events.length}}` is refused with `400 invalid_workflow`. An agent step's reply is `{{steps..text}}`, compared as exact text (`"Yes"` is not `eq` `"yes"`) **[tested: `engine/test/workflows.test.ts` (count on the sample calendar takes the then way, `events.length` refused), 11 Nov; agent `text` saved and run once by hand]**. At most 20 nodes. - Shape (#164): a tree from the trigger. Nodes are agent/tool/http steps, conditions (If) and `{ type: "end" }`. An If's `then` / `else` edges start its yes / no ways, and its edge **without** `sourceHandle` starts what comes after both ways. A way whose last step has no next step (or an empty way) carries on after its If; a way that reaches an End stops that path. Ifs may sit anywhere: in the main line, inside a way, inside a way of a way. No joins or loops (every node has one way in), End has no next step, and steps after an If whose ways both end are refused. Inside any way, `{{steps.…}}` may name steps earlier on the same path back to the trigger, never another way's. Runs stream `node.*` for every step at any depth, and the run history lists every step that ran, in order **[tested: unit, local engine runs of three paths, an engine restart, a scheduled fire in `test/autopilot.test.ts`, 10 Nov]**. - Older shape, still accepted as is: trigger → a chain of agent/tool/http nodes → optionally one condition whose `then` edge (required) and `else` edge each lead to a chain of agent/tool/http nodes (#153; no condition inside a way, one next step per node). No cycles, no unreachable nodes. Two **one-step** ways may not need the same input with different values (e.g. two single agent ways); a way of two or more steps has its own mappings, so that limit does not apply to it. Inside a way, `{{steps.…}}` may name earlier steps of the main chain or of the same way, never the other way. - Runs: steps inside a way stream `node.started` / `node.finished` with their own canvas node ids, like any step. The run history (`GET …/runs`) keeps a multi-step way's **final output only**, under its last node (Mastra does not keep the steps inside a nested workflow in the run snapshot) **[tested: unit, local engine run, a scheduled fire in `test/autopilot.test.ts`, 10 Nov]**. diff --git a/engine/.env.example b/engine/.env.example index 5c1a0119..947d0fb8 100644 --- a/engine/.env.example +++ b/engine/.env.example @@ -20,5 +20,7 @@ BACKEND_URL= COMPOSIO_API_KEY= # Optional, default https://backend.composio.dev/api/v3.1 (tests point it at a fake) COMPOSIO_URL= +# Optional, default https://1click.chaindefuser.com: NEAR Intents 1Click API for crosschain_quote (#273, dry quotes only, no key; tests point it at a fake) +ONECLICK_URL= # Optional, default 12000: token budget for the messages of each model call; the oldest are trimmed first (#123) CONTEXT_TOKEN_LIMIT= diff --git a/engine/CLAUDE.md b/engine/CLAUDE.md index 7341d4c5..0571cfe9 100644 --- a/engine/CLAUDE.md +++ b/engine/CLAUDE.md @@ -35,6 +35,7 @@ AI engine: a Mastra server that runs each Mind (soul, skills, tools, memory, sch - **Wallet skills (skills only, no new tools; prompt tests in `test/skills-wallet.test.ts` with a fake wallet backend):** `recipient-guard` (#182: `near_view_account`, `list_payments`, grants `send_payment` itself; a lookalike of an account paid before, e.g. `b0b.testnet` vs `bob.testnet`, gets a question and no card; the TEE policy stays the real wall), `freeze-advisor` (#185: reads only, points to "Freeze wallet"; no freeze tool exists, by design), `split-bill` (#177) and `revenue-split` (#190: split kept in working memory) send one `send_payment` per person, each with its own approval, `treasury-report` (#189) and `spending-audit` (#184) only read `get_balance` / `list_payments`. Refused payments are visible: the backend stores every attempt and `list_payments` returns `policy_denied` / `wallet_frozen` rows with their `message`. Incoming transfers are not listed by any tool (only the balance shows them), and Autopilot runs get no wallet token, so a scheduled daily or weekly report cannot read the wallet yet; no Builder template was added. - **Best price buyer (#176, `get_quotes`, skill `best-price`):** `get_quotes` reads the shop's `?quotes=1` (every seller, cheapest first, `onYourList` from the wallet's own policy) and adds `cheapestOnYourList`; `buy_data` takes an optional `seller` id. The skill shows the comparison and buys only the cheapest seller with `onYourList: true`. Sellers come from the backend's `SHOP_SELLERS` (intended `lin1er.testnet:1.0,testing7.testnet:0.8`, not set yet). Never call it NEAR Intents. - **Price watch (#179, skill `price-watch`):** `get_quotes`, then `add_numbers` (limit minus price) decides; buys through the same `buy_data` + `send_payment` approval only at or under the owner's limit. Autopilot runs drop `send_payment`, so there it only checks and reports. No Builder canvas template exists in the repo yet, so none was added. +- **Cross-chain quote (#273, `crosschain_quote` in `src/crosschain.ts`, skill `payments`):** a stablecoin payment from NEAR to another chain through NEAR Intents, as a **preview only**. NEAR Intents has no testnet and none is planned (docs.near-intents.org FAQ; HACKATHON.md Q-007 suggests `dry: true` quotes), and every wallet here is testnet. So the tool only calls 1Click `POST /v0/quote` with `dry: true` (`ONECLICK_URL`, default `https://1click.chaindefuser.com`, no key: without one 1Click adds its unauthenticated fee to the quote, Q-006). It never gets a deposit address, and nothing can be sent with it. `EXACT_INPUT`, 1% slippage, `ORIGIN_CHAIN` deposit and refund, `DESTINATION_CHAIN` recipient, deadline 10 min. `refundTo` is the Mind's own wallet address (from the backend's balance route; 1Click requires it even dry), so no wallet means "no wallet yet". Asset ids come from `GET /v0/tokens` (cached 10 min; read live 12 Nov: 230 tokens, USDC on 16 chains incl. BNB Chain with 18 decimals, USDT on 13), never typed by hand; chain names map to 1Click's `blockchain` ids (`chainId`). Amounts are converted with BigInt (`toUnits`/`fromUnits`), and `cost` is sent minus received in the token, scaled to the larger decimals. 1Click's refusal text ("recipient is not valid") is passed on. No approval: nothing moves. The playbook line says to use the owner's typed address, show amount, cost and time, say nothing was sent, and never call `send_payment` for it. Graph node `tool:crosschain_quote`. Live dry quote, 12 Nov: 10 USDC on NEAR → 9.99558 on Base, ~22 s estimate, answered in ~1 s. Tests: `test/crosschain.test.ts` (unit, fake 1Click), `test/skills-crosschain.test.ts` (live prompts with a fake 1Click: Base, Solana USDT, a NEAR payment still gets `send_payment`; 9/9 in 3 runs). Real sending needs a mainnet wallet and a policy that allows 1Click deposit addresses; not built (mainnet needs Axel's approval). - **Invoice & get paid (#180, `near_check_transfer`, skill `invoice`):** `list_payments` only lists what the Mind sent and `get_balance` does not say who paid, so "paid" needs `near_check_transfer` (RPC `tx` by hash + sender: success, receiver, NEAR moved). The tool itself sets `toThisMindsWallet` (receiver vs the wallet's own address from `/internal/v1/wallet/balance`) and `coversAmount` (vs the required `amountNear`, in yocto; it was optional and the model once left it out): in a live test (11 Nov) the model read two equal 64-character addresses as different and called a real payment unpaid. It reads `NEAR_RPC_URL` per call. The invoice goes out with `mail_send` (approval), so the `email-address` skill must be on too. The skill has no `send_payment`. - **Mind as seller (#181, `sell_offer`, `buy_from_mind`, skill `mind-seller`):** `sell_offer` (approval) publishes through `PUT /internal/v1/offers/{item}`, paid into the Mind's own wallet; `buy_from_mind` is the 402 pattern against `GET /internal/v1/minds/{sellerMindId}/offers/{item}`. The buyer's wallet must list the seller's address or the policy refuses the payment before signing. Try-out Minds can neither sell nor be bought from. - **Email tools (#13, #43, `src/email.ts`):** `gmail_list_emails`, `gmail_read_email`, `gmail_create_draft` (no send tool; drafts only), and `gmail_organize` (#106 step 2: archive or label up to 20 emails in one approval; archive removes `INBOX`, nothing is ever deleted; `GMAIL_CREATE_LABEL` finds or makes the label, then `GMAIL_ADD_LABEL_TO_EMAIL` per email, failures listed; with `demo` it changes nothing and its `note` makes the Mind say so). A run with `demo: true` (judge try-out user) reads `SAMPLE_INBOX`, fictional and fixed, with times relative to now; results carry `source: "sample_inbox"`. Without `demo` they read the run user's own Gmail through Composio (`src/composio.ts`, REST v3.1): one tool-router session per user id (cached 30 min, reopened once on 404), then `execute` of `GMAIL_FETCH_EMAILS` / `GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID` / `GMAIL_CREATE_EMAIL_DRAFT`. The Composio user id is the backend user id (`USER_KEY` in `RequestContext`), so a session only reaches that user's Gmail. No connection (`400 ToolRouterV2_NoActiveConnection`), no user or no `COMPOSIO_API_KEY` → "Gmail is not connected". Never log the session response (it carries MCP connection headers). Owners must never get the sample. The sample keeps one email that tries to instruct the Mind: the `email-triage` playbook must flag it. App tools are named `_` so the Mind Graph maps them to `app:`. `email-triage` is `available`; no catalog skill is `blocked` right now, so tests add a temporary one. From cf73add08c688755de12e710a7fc67cfc993cf44 Mon Sep 17 00:00:00 2001 From: Lexirieru Date: Thu, 12 Nov 2026 20:40:49 +0700 Subject: [PATCH 4/7] feat(engine): prove a cross-chain quote is NEAR Intents' (#273) 1Click signs every quote, dry ones too. The result now carries proof: { signedBy1Click, signature, quoteHash, publicKey }, checked with the official verifyQuoteSignature from @defuse-protocol/one-click-sdk-typescript 0.1.26 (pinned). The playbook has the Mind say so in plain words after the result, or that the signature could not be checked. Tests: test:unit 178/178 (a recorded real signed quote verifies, a changed amountOut does not); skills-crosschain live 9/9 over 3 runs (the signed answer is called signed, the unsigned one never verified); Chrome e2e on a local stack against the real 1Click: proof question in English and Indonesian answered with the hash, key and signature. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q5ZrzK8une3S2YyhDG746e --- engine/bun.lock | 77 +++++++++++++++++++- engine/package.json | 1 + engine/skills/payments/SKILL.md | 2 +- engine/src/crosschain.ts | 21 +++++- engine/test/crosschain.test.ts | 21 +++++- engine/test/fixtures/oneclick-dry-quote.json | 1 + engine/test/skills-crosschain.test.ts | 11 +++ 7 files changed, 129 insertions(+), 5 deletions(-) create mode 100644 engine/test/fixtures/oneclick-dry-quote.json diff --git a/engine/bun.lock b/engine/bun.lock index 19857b33..2c9c51be 100644 --- a/engine/bun.lock +++ b/engine/bun.lock @@ -6,6 +6,7 @@ "name": "@hellonear/engine", "dependencies": { "@ai-sdk/openai-compatible": "3.0.82", + "@defuse-protocol/one-click-sdk-typescript": "0.1.26", "@mastra/core": "1.81.0", "@mastra/memory": "1.40.0", "@mastra/pg": "1.34.0", @@ -51,6 +52,8 @@ "@chat-adapter/catalog": ["@chat-adapter/catalog@4.44.0", "", {}, "sha512-UtpW5mMgIjYBRDIgxJKh+tfnlFe0GjLsFG5MPPUDA5b/PggSOAt00TFr0xF6UIXXh1SaK3V1u3FiXyM2sdnaJQ=="], + "@defuse-protocol/one-click-sdk-typescript": ["@defuse-protocol/one-click-sdk-typescript@0.1.26", "", { "dependencies": { "@noble/hashes": "^1.3.3", "@scure/base": "^1.0.0 || ^2.0.0", "axios": "^1.6.8", "form-data": "^4.0.0", "json-stable-stringify": "1.3.0", "tweetnacl": "^1.0.0" } }, "sha512-vYoBgEbppergtYd/H1IaJW9Jm5mPrX+jAwuuhMvDFstirJB53KFe2HnGLTg0KNyg6qztbOeDK0sA/oEAee+EAw=="], + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], "@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="], @@ -147,6 +150,8 @@ "@posthog/types": ["@posthog/types@1.419.0", "", {}, "sha512-XX7zRYt/vK8AzaD6V+oDquAzacZf5exJv971dja9En8Qf6g84Qvc3rpT0w6hDYYLWrjaSSkdjFfvvoXI0ouJDg=="], + "@scure/base": ["@scure/base@2.4.0", "", {}, "sha512-thZ1TuJwFwBblOhgsjDKvvGirBxNp+wSvY/DR6tJBJOTDhdAAcHJ8Vbr2eFnqaxeca4+t0i9KBf+uHYGWwZORg=="], + "@sec-ant/readable-stream": ["@sec-ant/readable-stream@0.4.1", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="], "@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="], @@ -217,12 +222,18 @@ "aes-js": ["aes-js@4.0.0-beta.5", "", {}, "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q=="], + "agent-base": ["agent-base@6.0.2", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="], + "asn1.js": ["asn1.js@5.4.1", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0", "safer-buffer": "^2.1.0" } }, "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA=="], "asn1js": ["asn1js@3.1.0", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.2.0", "tslib": "^2.8.1" } }, "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA=="], "async-mutex": ["async-mutex@0.5.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA=="], + "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], + + "axios": ["axios@1.21.1", "", { "dependencies": { "follow-redirects": "^1.16.2", "form-data": "^4.0.6", "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } }, "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ=="], + "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], @@ -235,20 +246,32 @@ "buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="], + "call-bind": ["call-bind@1.0.9", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "get-intrinsic": "^1.3.0", "set-function-length": "^1.2.2" } }, "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ=="], + + "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], + + "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="], + "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], "character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="], "chat": ["chat@4.44.0", "", { "dependencies": { "@chat-adapter/catalog": "4.44.0", "@workflow/serde": "4.1.0-beta.2", "mdast-util-to-string": "^4.0.0", "remark-gfm": "^4.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "remend": "^1.2.1", "unified": "^11.0.5" }, "peerDependencies": { "ai": "^6.0.182 || ^7.0.0", "workflow": "^5.0.0-beta.35", "zod": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["ai", "workflow"] }, "sha512-DGVc9yV1ifOJFpe8Pz6BAoOBVT7/iI/7kkMuB+ZUrpyQ1iw1ElibxyvYBx7tEo1qPl6w510+Acvt1XSVPSgKjA=="], + "combined-stream": ["combined-stream@1.0.8", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="], + "croner": ["croner@10.0.1", "", {}, "sha512-ixNtAJndqh173VQ4KodSdJEI6nuioBWI0V1ITNKhZZsO0pEMoDxz539T4FTTbSZ/xIOSuDnzxLVRqBVSvPNE2g=="], "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], - "debug": ["debug@3.2.7", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="], + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="], + "define-data-property": ["define-data-property@1.1.4", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="], + + "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], + "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], "devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="], @@ -257,10 +280,20 @@ "dotenv": ["dotenv@17.4.2", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="], + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + "ed2curve": ["ed2curve@0.3.0", "", { "dependencies": { "tweetnacl": "1.x.x" } }, "sha512-8w2fmmq3hv9rCrcI7g9hms2pMunQr1JINfcjwR9tAyZqhtyaMN991lF/ZfHfr5tzZQ8c7y7aBgZbjfbd0fjFwQ=="], "elliptic": ["elliptic@6.6.1", "", { "dependencies": { "bn.js": "^4.11.9", "brorand": "^1.1.0", "hash.js": "^1.0.0", "hmac-drbg": "^1.0.1", "inherits": "^2.0.4", "minimalistic-assert": "^1.0.1", "minimalistic-crypto-utils": "^1.0.1" } }, "sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g=="], + "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], + + "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], + + "es-object-atoms": ["es-object-atoms@1.1.2", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="], + + "es-set-tostringtag": ["es-set-tostringtag@2.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="], + "esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": "bin/esbuild" }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], "escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], @@ -279,12 +312,32 @@ "figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="], + "follow-redirects": ["follow-redirects@1.16.3", "", { "peerDependencies": { "debug": "*" }, "optionalPeers": ["debug"] }, "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A=="], + + "form-data": ["form-data@4.0.6", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.4", "mime-types": "^2.1.35" } }, "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ=="], + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], + + "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], + + "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], + "get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="], + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], + + "has-property-descriptors": ["has-property-descriptors@1.0.2", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="], + + "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], + + "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="], + "hash.js": ["hash.js@1.1.7", "", { "dependencies": { "inherits": "^2.0.3", "minimalistic-assert": "^1.0.1" } }, "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA=="], + "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], + "hmac-drbg": ["hmac-drbg@1.0.1", "", { "dependencies": { "hash.js": "^1.0.3", "minimalistic-assert": "^1.0.0", "minimalistic-crypto-utils": "^1.0.1" } }, "sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg=="], "hono": ["hono@4.13.16", "", {}, "sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A=="], @@ -293,6 +346,8 @@ "hpke": ["hpke@1.1.7", "", {}, "sha512-wQGOBpFBFlP2h7euuLuey8yJGUtJ+c8D/ohPxtTQqpICItFtHDpbXk2B29xfUpIFPn0miS9TJVObFGAeEZzDJA=="], + "https-proxy-agent": ["https-proxy-agent@5.0.1", "", { "dependencies": { "agent-base": "6", "debug": "4" } }, "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA=="], + "human-signals": ["human-signals@8.0.1", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="], "iconv-lite": ["iconv-lite@0.4.24", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3" } }, "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA=="], @@ -311,6 +366,8 @@ "is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="], + "isarray": ["isarray@2.0.5", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="], + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], "jose": ["jose@6.2.13", "", {}, "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ=="], @@ -323,6 +380,10 @@ "json-schema-to-zod": ["json-schema-to-zod@2.8.1", "", { "bin": "dist/cjs/cli.js" }, "sha512-fRr1mHgZ7hboLKBUdR428gd9dIHUFGivUqOeiDcSmyXkNZCtB1uGaZLvsjZ4GaN5pwBIs+TGIOf6s+Rp5/R/zA=="], + "json-stable-stringify": ["json-stable-stringify@1.3.0", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.4", "isarray": "^2.0.5", "jsonify": "^0.0.1", "object-keys": "^1.1.1" } }, "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg=="], + + "jsonify": ["jsonify@0.0.1", "", {}, "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg=="], + "lodash.merge": ["lodash.merge@4.6.2", "", {}, "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="], "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], @@ -331,6 +392,8 @@ "markdown-table": ["markdown-table@3.0.4", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="], + "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], + "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.4", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-z4B5c6jrnJ1ltOQemhWYPBSAo6y42Z8Gt2yEgfgNTMcLSU59B8bfj8Z8AnAlJrBGLnqkdAUZ7jdDEqQw3KuipQ=="], "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], @@ -411,6 +474,10 @@ "micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + "mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], + + "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], + "minimalistic-assert": ["minimalistic-assert@1.0.1", "", {}, "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="], "minimalistic-crypto-utils": ["minimalistic-crypto-utils@1.0.1", "", {}, "sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg=="], @@ -423,6 +490,8 @@ "npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="], + "object-keys": ["object-keys@1.1.1", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="], + "ohttp-ts": ["ohttp-ts@0.6.1", "", { "dependencies": { "bhttp-ts": "0.6.1", "quicvarint": "0.2.1" }, "peerDependencies": { "hpke": "^1" } }, "sha512-amrwcueJWKMWV2nHLLZM3S4Z88z2pB0RzEqoml0XoI5arFGNHtoxMRDLsrpNbym4xIA06jE5qJMFmLsxIoambA=="], "openai": ["openai@7.39.0", "", { "peerDependencies": { "@aws-sdk/credential-provider-node": ">=3.972.0 <4", "@smithy/hash-node": ">=4.3.0 <5", "@smithy/signature-v4": ">=5.4.0 <6", "undici": ">=5 <9", "ws": "^8.21.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["@aws-sdk/credential-provider-node", "@smithy/hash-node", "@smithy/signature-v4"] }, "sha512-iEA9ndbrj32vhYZwJg2v9BQVuztGUOb2SBQU16ZcWNkQHWEBjtarxjqR9c6d5PbWMG0Eyfhk66OZ0iJ8XpFjyw=="], @@ -469,6 +538,8 @@ "probe-image-size": ["probe-image-size@7.5.0", "", { "dependencies": { "lodash.merge": "^4.6.2", "needle": "^2.5.2" } }, "sha512-ietdx4XPgmnzHRZOq1/KtcnsBkL4bRsBe+Szj5Tuq1/KPqDG42OspG1IhJb7vz6Z9pSzhp0J6UPnw6hujJTWoQ=="], + "proxy-from-env": ["proxy-from-env@2.1.0", "", {}, "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA=="], + "pvtsutils": ["pvtsutils@1.3.6", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="], "pvutils": ["pvutils@1.2.0", "", {}, "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg=="], @@ -493,6 +564,8 @@ "sax": ["sax@1.6.1", "", {}, "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q=="], + "set-function-length": ["set-function-length@1.2.2", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="], + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], @@ -593,7 +666,7 @@ "ethers/ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], - "micromark/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + "needle/debug": ["debug@3.2.7", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="], "npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], diff --git a/engine/package.json b/engine/package.json index 45eba642..f756e589 100644 --- a/engine/package.json +++ b/engine/package.json @@ -13,6 +13,7 @@ }, "dependencies": { "@ai-sdk/openai-compatible": "3.0.82", + "@defuse-protocol/one-click-sdk-typescript": "0.1.26", "@mastra/core": "1.81.0", "@mastra/memory": "1.40.0", "@mastra/pg": "1.34.0", diff --git a/engine/skills/payments/SKILL.md b/engine/skills/payments/SKILL.md index bf317604..4363b574 100644 --- a/engine/skills/payments/SKILL.md +++ b/engine/skills/payments/SKILL.md @@ -22,4 +22,4 @@ metadata: 7. After a `sent` payment, report the amount, the recipient and the `txHash` in one sentence. A `pending` payment waits for the owner in the OutLayer dashboard; say so. 8. Use `get_balance` for any question about this Mind's own balance and `list_payments` for past payments. Never guess either. 9. If a tool says this Mind has no wallet yet, tell the owner to create one on the Mind's wallet screen. -10. To pay USDC or USDT on another chain (Base, Arbitrum, Solana, Ethereum…), call `crosschain_quote` with the address the owner typed. It is a preview: show what the recipient would get, the cost and the time, and say plainly that nothing was sent and this Mind can't send cross-chain yet. Never call `send_payment` for it. +10. To pay USDC or USDT on another chain (Base, Arbitrum, Solana, Ethereum…), call `crosschain_quote` with the address the owner typed. It is a preview: show what the recipient would get, the cost and the time, and say plainly that nothing was sent and this Mind can't send cross-chain yet. Only after the result: if `proof.signedBy1Click` is true, say in plain words that NEAR Intents signed these numbers and the signature checked out (give `quoteHash` if asked for proof); if false, say the signature could not be checked. Never name tool fields. Never call `send_payment` for it. diff --git a/engine/src/crosschain.ts b/engine/src/crosschain.ts index 544ebf27..a534821b 100644 --- a/engine/src/crosschain.ts +++ b/engine/src/crosschain.ts @@ -3,6 +3,7 @@ // `dry: true` quotes), and every HelloNear wallet is on testnet, so this tool never gets a deposit address and nothing // can be sent with it. `dry: true` needs no API key (checked live 12 Nov: 201, 10 USDC on NEAR to Base quoted in ~1 s). import { createTool } from '@mastra/core/tools' +import { quoteHash, verifyQuoteSignature, type OneClickQuoteResponse } from '@defuse-protocol/one-click-sdk-typescript' import { z } from 'zod' import { walletCall } from './wallet.ts' @@ -64,12 +65,25 @@ type QuoteAnswer = { quote?: { amountIn: string; amountOut: string; minAmountOut?: string; timeEstimate?: number } correlationId?: string timestamp?: string + signature?: string message?: string } +// 1Click signs every quote, dry ones too (docs.near-intents.org "Verify Quote Signatures", read 12 Nov): ed25519 by its +// manager key over a base58 SHA-256 of the request and quote fields. The SDK's own verifyQuoteSignature checks it with +// the key it ships (`ed25519:reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc` in 0.1.26); a live quote passed and the same +// quote with amountOut changed failed (12 Nov). It is the proof shown to the owner that the numbers are NEAR Intents'. +export const ONE_CLICK_KEY = 'ed25519:reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc' +export function proofOf(answer: QuoteAnswer) { + const response = answer as unknown as OneClickQuoteResponse + let hash = '' + try { hash = quoteHash(response) } catch { /* fields missing: not verified */ } + return { signedBy1Click: !!answer.signature && verifyQuoteSignature(response), signature: answer.signature ?? '', quoteHash: hash, publicKey: ONE_CLICK_KEY } +} + export const crosschainQuote = createTool({ id: 'crosschain_quote', - description: 'Preview a stablecoin payment from NEAR to another chain through NEAR Intents: how much the recipient would get, the cost and the time. A quote only: it sends nothing and asks no approval, and this Mind cannot send cross-chain yet (NEAR Intents is mainnet only, the wallet is testnet). The recipient address must be one the owner typed in this conversation.', + description: 'Preview a stablecoin payment from NEAR to another chain through NEAR Intents: how much the recipient would get, the cost and the time, with proof.signedBy1Click saying whether NEAR Intents\' signature over those numbers checked out. A quote only: it sends nothing and asks no approval, and this Mind cannot send cross-chain yet (NEAR Intents is mainnet only, the wallet is testnet). The recipient address must be one the owner typed in this conversation.', inputSchema: z.object({ token: z.enum(STABLECOINS).describe('the stablecoin on NEAR to send'), amount: z.string().regex(/^\d{1,9}(\.\d{1,6})?$/, 'a decimal amount, e.g. "10" or "2.5"').describe('how much of it to send'), @@ -85,6 +99,10 @@ export const crosschainQuote = createTool({ seconds: z.number().describe('NEAR Intents\' estimate of the time it takes'), quoteId: z.string(), quotedAt: z.string(), + proof: z.object({ + signedBy1Click: z.boolean().describe('true when NEAR Intents\' signature over these numbers checked out'), + signature: z.string(), quoteHash: z.string(), publicKey: z.string(), + }), note: z.string(), }), execute: async ({ token, amount, toChain, recipient, toToken }, context) => { @@ -125,6 +143,7 @@ export const crosschainQuote = createTool({ seconds: q.timeEstimate ?? 0, quoteId: body.correlationId ?? '', quotedAt: body.timestamp ?? new Date().toISOString(), + proof: proofOf(body), note: NOT_SENT, } }, diff --git a/engine/test/crosschain.test.ts b/engine/test/crosschain.test.ts index d00c9652..10a8683e 100644 --- a/engine/test/crosschain.test.ts +++ b/engine/test/crosschain.test.ts @@ -6,7 +6,8 @@ import { createServer } from 'node:http' import type { AddressInfo } from 'node:net' import { toolRegistry } from '../src/tools.ts' import { WALLET_KEY, walletContext } from '../src/wallet.ts' -import { chainId, costOf, fromUnits, resetTokenCache, toUnits } from '../src/crosschain.ts' +import { readFileSync } from 'node:fs' +import { chainId, costOf, fromUnits, proofOf, resetTokenCache, toUnits } from '../src/crosschain.ts' const USDC_NEAR = 'nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1' const USDC_BASE = 'nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near' @@ -84,6 +85,7 @@ test('a dry quote: USDC on NEAR to Base, refunds to the Mind\'s own wallet, noth from: { chain: 'near', token: 'USDC', amount: '10' }, to: { chain: 'base', token: 'USDC', recipient: BASE_ADDR, amount: '9.99558', minAmount: '9.895624' }, cost: '0.00442', seconds: 22, quoteId: 'q-1', quotedAt: '2026-11-12T12:54:15.113Z', + proof: out.proof, note: out.note, }) assert.match(out.note, /nothing was sent/) @@ -109,3 +111,20 @@ test('refusals: an unknown chain lists where it can go, NEAR itself, a bad addre test('1Click\'s own refusal comes back in its words', async () => { await assert.rejects(run({ token: 'USDC', amount: '10', toChain: 'base', recipient: BAD_ADDR }), /NEAR Intents: recipient is not valid/) }) + +// A real dry quote recorded from 1Click on 12 Nov (test/fixtures/oneclick-dry-quote.json): its signature checks out with +// the SDK's key; any changed number does not. The fake above signs nothing, so its quotes are never called verified. +test('the proof: a real 1Click signature verifies, a changed number or a fake answer does not', async () => { + const real = JSON.parse(readFileSync(new URL('./fixtures/oneclick-dry-quote.json', import.meta.url), 'utf8')) + const proof = proofOf(real) + assert.equal(proof.signedBy1Click, true) + assert.equal(proof.signature, real.signature) + assert.match(proof.quoteHash, /^[1-9A-HJ-NP-Za-km-z]{40,50}$/) + assert.equal(proof.publicKey, 'ed25519:reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc') + const changed = structuredClone(real) + changed.quote.amountOut = String(BigInt(real.quote.amountOut) + 1n) + assert.equal(proofOf(changed).signedBy1Click, false) + assert.equal(proofOf({ ...real, signature: undefined }).signedBy1Click, false) + const out = await run({ token: 'USDC', amount: '10', toChain: 'base', recipient: BASE_ADDR }) + assert.equal(out.proof.signedBy1Click, false, 'the fake 1Click has no signature') +}) diff --git a/engine/test/fixtures/oneclick-dry-quote.json b/engine/test/fixtures/oneclick-dry-quote.json new file mode 100644 index 00000000..e25600bd --- /dev/null +++ b/engine/test/fixtures/oneclick-dry-quote.json @@ -0,0 +1 @@ +{"quote":{"amountIn":"10000000","amountInFormatted":"10.0","amountInUsd":"9.995160000000","minAmountIn":"10000000","amountOut":"9995580","amountOutFormatted":"9.99558","amountOutUsd":"9.990742139280","minAmountOut":"9895624","timeEstimate":22,"refundFee":"4228","withdrawFee":"2400"},"quoteRequest":{"dry":true,"depositMode":"SIMPLE","swapType":"EXACT_INPUT","slippageTolerance":100,"originAsset":"nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1","depositType":"ORIGIN_CHAIN","destinationAsset":"nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near","amount":"10000000","refundTo":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","refundType":"ORIGIN_CHAIN","recipient":"0x8ba1f109551bD432803012645Ac136ddd64DBA72","recipientType":"DESTINATION_CHAIN","deadline":"2026-11-12T14:30:00.000Z","confidentiality":"public","quoteWaitingTimeMs":0,"insured":false,"appFees":[{"recipient":"5880ad2b362620fadf759cbceb1cd5737ce8c6ed7fb8e9942881e6731f9247dd","fee":1}]},"signature":"ed25519:4weTL73oHsdmeReubyNYeazL8jANrqrfpymcD1okgRrRx1Jno8tYmv8sVvHhNQ9k2sCf8H99C3yvCmPCmotADHE6","timestamp":"2026-11-12T13:28:44.478Z","correlationId":"2197314d-9325-414a-8e72-975abc0b8ce0"} \ No newline at end of file diff --git a/engine/test/skills-crosschain.test.ts b/engine/test/skills-crosschain.test.ts index 139c94e7..a98c7a02 100644 --- a/engine/test/skills-crosschain.test.ts +++ b/engine/test/skills-crosschain.test.ts @@ -7,6 +7,7 @@ import { createServer } from 'node:http' import type { AddressInfo } from 'node:net' import { randomUUID } from 'node:crypto' import { server } from '../src/server.ts' +import { readFileSync } from 'node:fs' import { resetTokenCache } from '../src/crosschain.ts' let base = '' @@ -38,6 +39,7 @@ const TOKENS = [ { assetId: 'nep141:usdt.tether-token.near', decimals: 6, blockchain: 'near', symbol: 'USDT' }, { assetId: 'nep141:sol-c800a4bd850783ccb82c2b2c7e84175443606352.omft.near', decimals: 6, blockchain: 'sol', symbol: 'USDT' }, ] +const SIGNED = JSON.parse(readFileSync(new URL('./fixtures/oneclick-dry-quote.json', import.meta.url), 'utf8')) const quotes: any[] = [] const oneClick = createServer(async (req, res) => { let raw = '' @@ -46,6 +48,9 @@ const oneClick = createServer(async (req, res) => { if (req.url === '/v0/tokens') return send(200, TOKENS) const body = JSON.parse(raw) quotes.push(body) + // 10 USDC to Base answers with a real signed quote recorded from 1Click (12 Nov), so its signature checks out; + // every other quote is unsigned, so the Mind must not call it verified. + if (body.amount === '10000000' && body.destinationAsset.startsWith('nep141:base-')) return send(201, SIGNED) const out = (BigInt(body.amount) * 99956n) / 100000n send(201, { quote: { amountIn: body.amount, amountOut: out.toString(), minAmountOut: ((out * 99n) / 100n).toString(), timeEstimate: 22 }, correlationId: randomUUID(), timestamp: new Date().toISOString() }) }) @@ -86,6 +91,9 @@ test('"send 10 USDC to ": a dry quote with the owner\'s address, n const text = reply(evs) assert.match(text, /9\.99/, text) assert.match(text, /(not|nothing).{0,40}(sent|send)|can'?t send|cannot send|preview|quote/i, text) + const done = evs.find((e) => e.type === 'tool.result' && e.tool === 'crosschain_quote') + assert.equal(done?.result?.proof?.signedBy1Click, true) + assert.match(text, /sign/i, `says it is signed: ${text}`) }) test('USDT on Solana: the token and chain follow the owner\'s words', async () => { @@ -97,6 +105,9 @@ test('USDT on Solana: the token and chain follow the owner\'s words', async () = assert.match(String(q[0].args.toChain), /^sol(ana)?$/i) assert.equal(q[0].args.recipient, SOL_ADDR) assert.equal(sends, 0) + // Unsigned answer: never claimed as verified. + const text = reply(evs) + assert.doesNotMatch(text, /signature (checked out|is valid|verified)|signed by NEAR Intents and (the signature )?(checked|verified)/i, text) }) test('a NEAR testnet payment still goes through send_payment with its approval card', async () => { From e0e7872d0775c6c978a1da1c455f916c8e995929 Mon Sep 17 00:00:00 2001 From: Lexirieru Date: Thu, 12 Nov 2026 20:40:49 +0700 Subject: [PATCH 5/7] docs: the cross-chain quote's signature proof (#273) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q5ZrzK8une3S2YyhDG746e --- docs/api-contract.md | 2 +- engine/CLAUDE.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index dd8a3f9e..1c7bbf42 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -98,7 +98,7 @@ Several sellers (#176, Best Price Buyer) **[tested, fake OutLayer and RPC; not l - Intended config once the demo wallet lists both accounts (decided 11 Nov): `SHOP_SELLERS="lin1er.testnet:1.0,testing7.testnet:0.8"`. Not set anywhere yet. - Engine: `get_quotes` `{ item }` → `{ item, title, quotes, cheapestOnYourList }` (`?quotes=1`); `buy_data` takes an optional `seller` (`?seller=`). -**Cross-chain quote (#273), engine tool `crosschain_quote`, payments skill:** `{ token: "USDC" | "USDT", amount, toChain, recipient, toToken? }` → `{ status: "quote_only", from: { chain: "near", token, amount }, to: { chain, token, recipient, amount, minAmount }, cost, seconds, quoteId, quotedAt, note }`. A NEAR Intents 1Click `POST /v0/quote` with `dry: true` (no deposit address, no transaction, no key); the engine reads the Mind's wallet address from `GET /internal/v1/wallet/balance` for `refundTo` only, so no backend change. No approval: nothing moves. NEAR Intents is mainnet only and the wallets are testnet, so this is a preview and the Mind says so **[tested: unit with a fake 1Click; live prompt tests with a fake 1Click 9/9 on 12 Nov; one live dry quote against 1Click by hand]**. +**Cross-chain quote (#273), engine tool `crosschain_quote`, payments skill:** `{ token: "USDC" | "USDT", amount, toChain, recipient, toToken? }` → `{ status: "quote_only", from: { chain: "near", token, amount }, to: { chain, token, recipient, amount, minAmount }, cost, seconds, quoteId, quotedAt, proof: { signedBy1Click, signature, quoteHash, publicKey }, note }`. `proof.signedBy1Click` is 1Click's ed25519 signature over the quote, checked with the official SDK (`verifyQuoteSignature`, 0.1.26); the FE can show it as "Signed by NEAR Intents" with the hash, key and signature behind it. A NEAR Intents 1Click `POST /v0/quote` with `dry: true` (no deposit address, no transaction, no key); the engine reads the Mind's wallet address from `GET /internal/v1/wallet/balance` for `refundTo` only, so no backend change. No approval: nothing moves. NEAR Intents is mainnet only and the wallets are testnet, so this is a preview and the Mind says so **[tested: unit with a fake 1Click and a recorded signed quote; live prompt tests 9/9 on 12 Nov; Chrome e2e on a local stack against the real 1Click, signature verified]**. **Mind as Seller (#181)** **[tested, fake OutLayer and RPC; not live yet]**. Same 402 pattern, paid to the selling Mind's own wallet. Both routes take `X-Engine-Key` and the calling Mind's run `X-Wallet-Token`. - `PUT /internal/v1/offers/{item}`: the selling Mind publishes or replaces one offer. `item` = `[a-z0-9][a-z0-9-]{0,39}`. Body (strict) `{ title (≤ 200), priceNear (> 0, ≤ 1), content (≤ 20,000) }` → `200 { sellerMindId, item, title, priceNear, payTo }`, `payTo` = this Mind's own wallet address. `403 demo_not_allowed` for a try-out or playground Mind (the shared demo wallet is nobody's own). diff --git a/engine/CLAUDE.md b/engine/CLAUDE.md index 0571cfe9..4b6ece93 100644 --- a/engine/CLAUDE.md +++ b/engine/CLAUDE.md @@ -35,7 +35,7 @@ AI engine: a Mastra server that runs each Mind (soul, skills, tools, memory, sch - **Wallet skills (skills only, no new tools; prompt tests in `test/skills-wallet.test.ts` with a fake wallet backend):** `recipient-guard` (#182: `near_view_account`, `list_payments`, grants `send_payment` itself; a lookalike of an account paid before, e.g. `b0b.testnet` vs `bob.testnet`, gets a question and no card; the TEE policy stays the real wall), `freeze-advisor` (#185: reads only, points to "Freeze wallet"; no freeze tool exists, by design), `split-bill` (#177) and `revenue-split` (#190: split kept in working memory) send one `send_payment` per person, each with its own approval, `treasury-report` (#189) and `spending-audit` (#184) only read `get_balance` / `list_payments`. Refused payments are visible: the backend stores every attempt and `list_payments` returns `policy_denied` / `wallet_frozen` rows with their `message`. Incoming transfers are not listed by any tool (only the balance shows them), and Autopilot runs get no wallet token, so a scheduled daily or weekly report cannot read the wallet yet; no Builder template was added. - **Best price buyer (#176, `get_quotes`, skill `best-price`):** `get_quotes` reads the shop's `?quotes=1` (every seller, cheapest first, `onYourList` from the wallet's own policy) and adds `cheapestOnYourList`; `buy_data` takes an optional `seller` id. The skill shows the comparison and buys only the cheapest seller with `onYourList: true`. Sellers come from the backend's `SHOP_SELLERS` (intended `lin1er.testnet:1.0,testing7.testnet:0.8`, not set yet). Never call it NEAR Intents. - **Price watch (#179, skill `price-watch`):** `get_quotes`, then `add_numbers` (limit minus price) decides; buys through the same `buy_data` + `send_payment` approval only at or under the owner's limit. Autopilot runs drop `send_payment`, so there it only checks and reports. No Builder canvas template exists in the repo yet, so none was added. -- **Cross-chain quote (#273, `crosschain_quote` in `src/crosschain.ts`, skill `payments`):** a stablecoin payment from NEAR to another chain through NEAR Intents, as a **preview only**. NEAR Intents has no testnet and none is planned (docs.near-intents.org FAQ; HACKATHON.md Q-007 suggests `dry: true` quotes), and every wallet here is testnet. So the tool only calls 1Click `POST /v0/quote` with `dry: true` (`ONECLICK_URL`, default `https://1click.chaindefuser.com`, no key: without one 1Click adds its unauthenticated fee to the quote, Q-006). It never gets a deposit address, and nothing can be sent with it. `EXACT_INPUT`, 1% slippage, `ORIGIN_CHAIN` deposit and refund, `DESTINATION_CHAIN` recipient, deadline 10 min. `refundTo` is the Mind's own wallet address (from the backend's balance route; 1Click requires it even dry), so no wallet means "no wallet yet". Asset ids come from `GET /v0/tokens` (cached 10 min; read live 12 Nov: 230 tokens, USDC on 16 chains incl. BNB Chain with 18 decimals, USDT on 13), never typed by hand; chain names map to 1Click's `blockchain` ids (`chainId`). Amounts are converted with BigInt (`toUnits`/`fromUnits`), and `cost` is sent minus received in the token, scaled to the larger decimals. 1Click's refusal text ("recipient is not valid") is passed on. No approval: nothing moves. The playbook line says to use the owner's typed address, show amount, cost and time, say nothing was sent, and never call `send_payment` for it. Graph node `tool:crosschain_quote`. Live dry quote, 12 Nov: 10 USDC on NEAR → 9.99558 on Base, ~22 s estimate, answered in ~1 s. Tests: `test/crosschain.test.ts` (unit, fake 1Click), `test/skills-crosschain.test.ts` (live prompts with a fake 1Click: Base, Solana USDT, a NEAR payment still gets `send_payment`; 9/9 in 3 runs). Real sending needs a mainnet wallet and a policy that allows 1Click deposit addresses; not built (mainnet needs Axel's approval). +- **Cross-chain quote (#273, `crosschain_quote` in `src/crosschain.ts`, skill `payments`):** a stablecoin payment from NEAR to another chain through NEAR Intents, as a **preview only**. NEAR Intents has no testnet and none is planned (docs.near-intents.org FAQ; HACKATHON.md Q-007 suggests `dry: true` quotes), and every wallet here is testnet. So the tool only calls 1Click `POST /v0/quote` with `dry: true` (`ONECLICK_URL`, default `https://1click.chaindefuser.com`, no key: without one 1Click adds its unauthenticated fee to the quote, Q-006). It never gets a deposit address, and nothing can be sent with it. `EXACT_INPUT`, 1% slippage, `ORIGIN_CHAIN` deposit and refund, `DESTINATION_CHAIN` recipient, deadline 10 min. `refundTo` is the Mind's own wallet address (from the backend's balance route; 1Click requires it even dry), so no wallet means "no wallet yet". Asset ids come from `GET /v0/tokens` (cached 10 min; read live 12 Nov: 230 tokens, USDC on 16 chains incl. BNB Chain with 18 decimals, USDT on 13), never typed by hand; chain names map to 1Click's `blockchain` ids (`chainId`). Amounts are converted with BigInt (`toUnits`/`fromUnits`), and `cost` is sent minus received in the token, scaled to the larger decimals. 1Click's refusal text ("recipient is not valid") is passed on. No approval: nothing moves. The playbook line says to use the owner's typed address, show amount, cost and time, say nothing was sent, and never call `send_payment` for it. **Proof (12 Nov):** 1Click signs every quote, dry ones too (docs "Verify Quote Signatures"): ed25519 by its manager key over a base58 SHA-256 of the request and quote fields. The result carries `proof: { signedBy1Click, signature, quoteHash, publicKey }`, checked with the official `verifyQuoteSignature` / `quoteHash` from `@defuse-protocol/one-click-sdk-typescript` **0.1.26, pinned** (it ships the key `ed25519:reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc`). A live quote verified and the same quote with `amountOut` changed did not; `test/fixtures/oneclick-dry-quote.json` is a real signed dry quote for the tests. A quote that does not verify is still returned with `signedBy1Click: false`, and the playbook says the signature could not be checked. Dry quotes are not on chain, so the signature is the only proof (no explorer link). The playbook asks for plain words and no field names; the model still named `signedBy1Click` once in Chrome. Graph node `tool:crosschain_quote`. Live dry quote, 12 Nov: 10 USDC on NEAR → 9.99558 on Base, ~22 s estimate, answered in ~1 s. Tests: `test/crosschain.test.ts` (unit, fake 1Click plus the recorded signed quote), `test/skills-crosschain.test.ts` (live prompts, a 14-skill Payments Mind, fake 1Click: Base answered with the signed fixture, so the reply must say it is signed; Solana USDT unsigned, never called verified; a NEAR payment still gets `send_payment`; 9/9 in 3 runs). With only `payments` equipped the model always called the tool, but a try-out Mind with ~20 skills answered from the blurb alone while it read "(cannot send them yet)"; the blurb now names the quote. Chrome e2e on a local stack with the real 1Click (12 Nov): Base USDC and Solana USDT quotes, and a proof question in English and Indonesian answered with the hash, key and signature. Real sending needs a mainnet wallet and a policy that allows 1Click deposit addresses; not built (mainnet needs Axel's approval). - **Invoice & get paid (#180, `near_check_transfer`, skill `invoice`):** `list_payments` only lists what the Mind sent and `get_balance` does not say who paid, so "paid" needs `near_check_transfer` (RPC `tx` by hash + sender: success, receiver, NEAR moved). The tool itself sets `toThisMindsWallet` (receiver vs the wallet's own address from `/internal/v1/wallet/balance`) and `coversAmount` (vs the required `amountNear`, in yocto; it was optional and the model once left it out): in a live test (11 Nov) the model read two equal 64-character addresses as different and called a real payment unpaid. It reads `NEAR_RPC_URL` per call. The invoice goes out with `mail_send` (approval), so the `email-address` skill must be on too. The skill has no `send_payment`. - **Mind as seller (#181, `sell_offer`, `buy_from_mind`, skill `mind-seller`):** `sell_offer` (approval) publishes through `PUT /internal/v1/offers/{item}`, paid into the Mind's own wallet; `buy_from_mind` is the 402 pattern against `GET /internal/v1/minds/{sellerMindId}/offers/{item}`. The buyer's wallet must list the seller's address or the policy refuses the payment before signing. Try-out Minds can neither sell nor be bought from. - **Email tools (#13, #43, `src/email.ts`):** `gmail_list_emails`, `gmail_read_email`, `gmail_create_draft` (no send tool; drafts only), and `gmail_organize` (#106 step 2: archive or label up to 20 emails in one approval; archive removes `INBOX`, nothing is ever deleted; `GMAIL_CREATE_LABEL` finds or makes the label, then `GMAIL_ADD_LABEL_TO_EMAIL` per email, failures listed; with `demo` it changes nothing and its `note` makes the Mind say so). A run with `demo: true` (judge try-out user) reads `SAMPLE_INBOX`, fictional and fixed, with times relative to now; results carry `source: "sample_inbox"`. Without `demo` they read the run user's own Gmail through Composio (`src/composio.ts`, REST v3.1): one tool-router session per user id (cached 30 min, reopened once on 404), then `execute` of `GMAIL_FETCH_EMAILS` / `GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID` / `GMAIL_CREATE_EMAIL_DRAFT`. The Composio user id is the backend user id (`USER_KEY` in `RequestContext`), so a session only reaches that user's Gmail. No connection (`400 ToolRouterV2_NoActiveConnection`), no user or no `COMPOSIO_API_KEY` → "Gmail is not connected". Never log the session response (it carries MCP connection headers). Owners must never get the sample. The sample keeps one email that tries to instruct the Mind: the `email-triage` playbook must flag it. App tools are named `_` so the Mind Graph maps them to `app:`. `email-triage` is `available`; no catalog skill is `blocked` right now, so tests add a temporary one. From 874e426ee15a87f91dae6e56696f2564116d1b77 Mon Sep 17 00:00:00 2001 From: Lexirieru Date: Thu, 12 Nov 2026 21:02:02 +0700 Subject: [PATCH 6/7] fix(engine): the Mind states a quote's proof unasked, never retypes it (#273) Asked to list the hash and signature, the model dropped characters (a three-character gap in the 88-character signature; the hash missing or wrong in 3 of 6 runs), so a shown proof would not verify. It now says NEAR Intents signed the numbers and the signature checked out, and leaves the exact values to the app, which shows them from the tool result. Tests: skills-crosschain live 9/9 over 3 runs (fails on any proof-like string that is not exactly the tool's); Chrome e2e: a plain request got the proof without being asked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q5ZrzK8une3S2YyhDG746e --- engine/CLAUDE.md | 2 +- engine/skills/payments/SKILL.md | 2 +- engine/test/skills-crosschain.test.ts | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/engine/CLAUDE.md b/engine/CLAUDE.md index 4b6ece93..79633101 100644 --- a/engine/CLAUDE.md +++ b/engine/CLAUDE.md @@ -35,7 +35,7 @@ AI engine: a Mastra server that runs each Mind (soul, skills, tools, memory, sch - **Wallet skills (skills only, no new tools; prompt tests in `test/skills-wallet.test.ts` with a fake wallet backend):** `recipient-guard` (#182: `near_view_account`, `list_payments`, grants `send_payment` itself; a lookalike of an account paid before, e.g. `b0b.testnet` vs `bob.testnet`, gets a question and no card; the TEE policy stays the real wall), `freeze-advisor` (#185: reads only, points to "Freeze wallet"; no freeze tool exists, by design), `split-bill` (#177) and `revenue-split` (#190: split kept in working memory) send one `send_payment` per person, each with its own approval, `treasury-report` (#189) and `spending-audit` (#184) only read `get_balance` / `list_payments`. Refused payments are visible: the backend stores every attempt and `list_payments` returns `policy_denied` / `wallet_frozen` rows with their `message`. Incoming transfers are not listed by any tool (only the balance shows them), and Autopilot runs get no wallet token, so a scheduled daily or weekly report cannot read the wallet yet; no Builder template was added. - **Best price buyer (#176, `get_quotes`, skill `best-price`):** `get_quotes` reads the shop's `?quotes=1` (every seller, cheapest first, `onYourList` from the wallet's own policy) and adds `cheapestOnYourList`; `buy_data` takes an optional `seller` id. The skill shows the comparison and buys only the cheapest seller with `onYourList: true`. Sellers come from the backend's `SHOP_SELLERS` (intended `lin1er.testnet:1.0,testing7.testnet:0.8`, not set yet). Never call it NEAR Intents. - **Price watch (#179, skill `price-watch`):** `get_quotes`, then `add_numbers` (limit minus price) decides; buys through the same `buy_data` + `send_payment` approval only at or under the owner's limit. Autopilot runs drop `send_payment`, so there it only checks and reports. No Builder canvas template exists in the repo yet, so none was added. -- **Cross-chain quote (#273, `crosschain_quote` in `src/crosschain.ts`, skill `payments`):** a stablecoin payment from NEAR to another chain through NEAR Intents, as a **preview only**. NEAR Intents has no testnet and none is planned (docs.near-intents.org FAQ; HACKATHON.md Q-007 suggests `dry: true` quotes), and every wallet here is testnet. So the tool only calls 1Click `POST /v0/quote` with `dry: true` (`ONECLICK_URL`, default `https://1click.chaindefuser.com`, no key: without one 1Click adds its unauthenticated fee to the quote, Q-006). It never gets a deposit address, and nothing can be sent with it. `EXACT_INPUT`, 1% slippage, `ORIGIN_CHAIN` deposit and refund, `DESTINATION_CHAIN` recipient, deadline 10 min. `refundTo` is the Mind's own wallet address (from the backend's balance route; 1Click requires it even dry), so no wallet means "no wallet yet". Asset ids come from `GET /v0/tokens` (cached 10 min; read live 12 Nov: 230 tokens, USDC on 16 chains incl. BNB Chain with 18 decimals, USDT on 13), never typed by hand; chain names map to 1Click's `blockchain` ids (`chainId`). Amounts are converted with BigInt (`toUnits`/`fromUnits`), and `cost` is sent minus received in the token, scaled to the larger decimals. 1Click's refusal text ("recipient is not valid") is passed on. No approval: nothing moves. The playbook line says to use the owner's typed address, show amount, cost and time, say nothing was sent, and never call `send_payment` for it. **Proof (12 Nov):** 1Click signs every quote, dry ones too (docs "Verify Quote Signatures"): ed25519 by its manager key over a base58 SHA-256 of the request and quote fields. The result carries `proof: { signedBy1Click, signature, quoteHash, publicKey }`, checked with the official `verifyQuoteSignature` / `quoteHash` from `@defuse-protocol/one-click-sdk-typescript` **0.1.26, pinned** (it ships the key `ed25519:reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc`). A live quote verified and the same quote with `amountOut` changed did not; `test/fixtures/oneclick-dry-quote.json` is a real signed dry quote for the tests. A quote that does not verify is still returned with `signedBy1Click: false`, and the playbook says the signature could not be checked. Dry quotes are not on chain, so the signature is the only proof (no explorer link). The playbook asks for plain words and no field names; the model still named `signedBy1Click` once in Chrome. Graph node `tool:crosschain_quote`. Live dry quote, 12 Nov: 10 USDC on NEAR → 9.99558 on Base, ~22 s estimate, answered in ~1 s. Tests: `test/crosschain.test.ts` (unit, fake 1Click plus the recorded signed quote), `test/skills-crosschain.test.ts` (live prompts, a 14-skill Payments Mind, fake 1Click: Base answered with the signed fixture, so the reply must say it is signed; Solana USDT unsigned, never called verified; a NEAR payment still gets `send_payment`; 9/9 in 3 runs). With only `payments` equipped the model always called the tool, but a try-out Mind with ~20 skills answered from the blurb alone while it read "(cannot send them yet)"; the blurb now names the quote. Chrome e2e on a local stack with the real 1Click (12 Nov): Base USDC and Solana USDT quotes, and a proof question in English and Indonesian answered with the hash, key and signature. Real sending needs a mainnet wallet and a policy that allows 1Click deposit addresses; not built (mainnet needs Axel's approval). +- **Cross-chain quote (#273, `crosschain_quote` in `src/crosschain.ts`, skill `payments`):** a stablecoin payment from NEAR to another chain through NEAR Intents, as a **preview only**. NEAR Intents has no testnet and none is planned (docs.near-intents.org FAQ; HACKATHON.md Q-007 suggests `dry: true` quotes), and every wallet here is testnet. So the tool only calls 1Click `POST /v0/quote` with `dry: true` (`ONECLICK_URL`, default `https://1click.chaindefuser.com`, no key: without one 1Click adds its unauthenticated fee to the quote, Q-006). It never gets a deposit address, and nothing can be sent with it. `EXACT_INPUT`, 1% slippage, `ORIGIN_CHAIN` deposit and refund, `DESTINATION_CHAIN` recipient, deadline 10 min. `refundTo` is the Mind's own wallet address (from the backend's balance route; 1Click requires it even dry), so no wallet means "no wallet yet". Asset ids come from `GET /v0/tokens` (cached 10 min; read live 12 Nov: 230 tokens, USDC on 16 chains incl. BNB Chain with 18 decimals, USDT on 13), never typed by hand; chain names map to 1Click's `blockchain` ids (`chainId`). Amounts are converted with BigInt (`toUnits`/`fromUnits`), and `cost` is sent minus received in the token, scaled to the larger decimals. 1Click's refusal text ("recipient is not valid") is passed on. No approval: nothing moves. The playbook line says to use the owner's typed address, show amount, cost and time, say nothing was sent, and never call `send_payment` for it. **Proof (12 Nov):** 1Click signs every quote, dry ones too (docs "Verify Quote Signatures"): ed25519 by its manager key over a base58 SHA-256 of the request and quote fields. The result carries `proof: { signedBy1Click, signature, quoteHash, publicKey }`, checked with the official `verifyQuoteSignature` / `quoteHash` from `@defuse-protocol/one-click-sdk-typescript` **0.1.26, pinned** (it ships the key `ed25519:reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc`). A live quote verified and the same quote with `amountOut` changed did not; `test/fixtures/oneclick-dry-quote.json` is a real signed dry quote for the tests. A quote that does not verify is still returned with `signedBy1Click: false`, and the playbook says the signature could not be checked. Dry quotes are not on chain, so the signature is the only proof (no explorer link). The Mind states the proof unasked, in plain words, and is told never to retype the hash, key or signature: retyping them it dropped characters (the 88-character signature lost three, the hash was missing or wrong in 3 of 6 runs, 12 Nov), so the exact values belong on an FE card from the tool result (#273). The live test fails on any proof-like string in the reply that is not exactly the tool's. It still named `signedBy1Click` once in Chrome, and a Mind that had shown the values in an earlier chat copied that format (correctly, once). Graph node `tool:crosschain_quote`. Live dry quote, 12 Nov: 10 USDC on NEAR → 9.99558 on Base, ~22 s estimate, answered in ~1 s. Tests: `test/crosschain.test.ts` (unit, fake 1Click plus the recorded signed quote), `test/skills-crosschain.test.ts` (live prompts, a 14-skill Payments Mind, fake 1Click: Base answered with the signed fixture, so the reply must say it is signed; Solana USDT unsigned, never called verified; a NEAR payment still gets `send_payment`; 9/9 in 3 runs). With only `payments` equipped the model always called the tool, but a try-out Mind with ~20 skills answered from the blurb alone while it read "(cannot send them yet)"; the blurb now names the quote. Chrome e2e on a local stack with the real 1Click (12 Nov): Base USDC and Solana USDT quotes, and a proof question in English and Indonesian answered with the hash, key and signature. Real sending needs a mainnet wallet and a policy that allows 1Click deposit addresses; not built (mainnet needs Axel's approval). - **Invoice & get paid (#180, `near_check_transfer`, skill `invoice`):** `list_payments` only lists what the Mind sent and `get_balance` does not say who paid, so "paid" needs `near_check_transfer` (RPC `tx` by hash + sender: success, receiver, NEAR moved). The tool itself sets `toThisMindsWallet` (receiver vs the wallet's own address from `/internal/v1/wallet/balance`) and `coversAmount` (vs the required `amountNear`, in yocto; it was optional and the model once left it out): in a live test (11 Nov) the model read two equal 64-character addresses as different and called a real payment unpaid. It reads `NEAR_RPC_URL` per call. The invoice goes out with `mail_send` (approval), so the `email-address` skill must be on too. The skill has no `send_payment`. - **Mind as seller (#181, `sell_offer`, `buy_from_mind`, skill `mind-seller`):** `sell_offer` (approval) publishes through `PUT /internal/v1/offers/{item}`, paid into the Mind's own wallet; `buy_from_mind` is the 402 pattern against `GET /internal/v1/minds/{sellerMindId}/offers/{item}`. The buyer's wallet must list the seller's address or the policy refuses the payment before signing. Try-out Minds can neither sell nor be bought from. - **Email tools (#13, #43, `src/email.ts`):** `gmail_list_emails`, `gmail_read_email`, `gmail_create_draft` (no send tool; drafts only), and `gmail_organize` (#106 step 2: archive or label up to 20 emails in one approval; archive removes `INBOX`, nothing is ever deleted; `GMAIL_CREATE_LABEL` finds or makes the label, then `GMAIL_ADD_LABEL_TO_EMAIL` per email, failures listed; with `demo` it changes nothing and its `note` makes the Mind say so). A run with `demo: true` (judge try-out user) reads `SAMPLE_INBOX`, fictional and fixed, with times relative to now; results carry `source: "sample_inbox"`. Without `demo` they read the run user's own Gmail through Composio (`src/composio.ts`, REST v3.1): one tool-router session per user id (cached 30 min, reopened once on 404), then `execute` of `GMAIL_FETCH_EMAILS` / `GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID` / `GMAIL_CREATE_EMAIL_DRAFT`. The Composio user id is the backend user id (`USER_KEY` in `RequestContext`), so a session only reaches that user's Gmail. No connection (`400 ToolRouterV2_NoActiveConnection`), no user or no `COMPOSIO_API_KEY` → "Gmail is not connected". Never log the session response (it carries MCP connection headers). Owners must never get the sample. The sample keeps one email that tries to instruct the Mind: the `email-triage` playbook must flag it. App tools are named `_` so the Mind Graph maps them to `app:`. `email-triage` is `available`; no catalog skill is `blocked` right now, so tests add a temporary one. diff --git a/engine/skills/payments/SKILL.md b/engine/skills/payments/SKILL.md index 4363b574..3db6eca0 100644 --- a/engine/skills/payments/SKILL.md +++ b/engine/skills/payments/SKILL.md @@ -22,4 +22,4 @@ metadata: 7. After a `sent` payment, report the amount, the recipient and the `txHash` in one sentence. A `pending` payment waits for the owner in the OutLayer dashboard; say so. 8. Use `get_balance` for any question about this Mind's own balance and `list_payments` for past payments. Never guess either. 9. If a tool says this Mind has no wallet yet, tell the owner to create one on the Mind's wallet screen. -10. To pay USDC or USDT on another chain (Base, Arbitrum, Solana, Ethereum…), call `crosschain_quote` with the address the owner typed. It is a preview: show what the recipient would get, the cost and the time, and say plainly that nothing was sent and this Mind can't send cross-chain yet. Only after the result: if `proof.signedBy1Click` is true, say in plain words that NEAR Intents signed these numbers and the signature checked out (give `quoteHash` if asked for proof); if false, say the signature could not be checked. Never name tool fields. Never call `send_payment` for it. +10. To pay USDC or USDT on another chain (Base, Arbitrum, Solana, Ethereum…), call `crosschain_quote` with the address the owner typed. It is a preview: show what the recipient would get, the cost and the time, and say plainly that nothing was sent and this Mind can't send cross-chain yet. Only after the result, always add the proof under the quote: if `proof.signedBy1Click` is true, say in plain words that NEAR Intents signed these exact numbers and the signature checked out against its public key, and that the hash, key and signature are shown with the quote in the app; never retype them (copies come out wrong); if false, say the signature could not be checked. Never name tool fields. Never call `send_payment` for it. diff --git a/engine/test/skills-crosschain.test.ts b/engine/test/skills-crosschain.test.ts index a98c7a02..558211b3 100644 --- a/engine/test/skills-crosschain.test.ts +++ b/engine/test/skills-crosschain.test.ts @@ -94,6 +94,11 @@ test('"send 10 USDC to ": a dry quote with the owner\'s address, n const done = evs.find((e) => e.type === 'tool.result' && e.tool === 'crosschain_quote') assert.equal(done?.result?.proof?.signedBy1Click, true) assert.match(text, /sign/i, `says it is signed: ${text}`) + // The proof is stated without being asked. Its values come from the tool result (the FE shows them): retyping them, + // the model dropped characters from the signature and the hash (3 of 6 runs, 12 Nov). Any proof-like string the reply + // does carry must be exactly the tool's. + const exact = new Set([done.result.proof.quoteHash, done.result.proof.signature.replace('ed25519:', ''), done.result.proof.publicKey.replace('ed25519:', '')]) + for (const m of text.matchAll(/[1-9A-HJ-NP-Za-km-z]{40,}/g)) assert.ok(exact.has(m[0]), `a mangled proof string ${m[0]}: ${text}`) }) test('USDT on Solana: the token and chain follow the owner\'s words', async () => { From 63d1ab7c69b64f820139ba9eaaccb1e38d98ea54 Mon Sep 17 00:00:00 2001 From: Lexirieru Date: Thu, 12 Nov 2026 21:57:48 +0700 Subject: [PATCH 7/7] fix(engine): default NEAR RPC is FastNear's testnet endpoint rpc.testnet.near.org answered "THIS ENDPOINT IS DEPRECATED! STOP USING IT NOW!" instead of results on and off (12 Nov), failing near_view_account and every test that reads an account (11 in one full run). https://test.rpc.fastnear.com is listed at docs.near.org/api/rpc/providers; NEAR_RPC_URL still overrides it. Tests: test:unit 178/178; bun run test 317/318 with the new default (one workflow test where the model tried send_payment, which a workflow doesn't have: ToolNotFoundError, nothing paid; 5/5 on this branch and 5/5 with main's playbook afterwards). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q5ZrzK8une3S2YyhDG746e --- engine/.env.example | 2 +- engine/CLAUDE.md | 2 +- engine/src/tools.ts | 7 +++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/engine/.env.example b/engine/.env.example index 947d0fb8..9be2ba5c 100644 --- a/engine/.env.example +++ b/engine/.env.example @@ -9,7 +9,7 @@ PORT=4100 # NEAR network and the Mind registry contract (sc/) NEAR_NETWORK=testnet REGISTRY_CONTRACT_ID=hellonear-registry.testnet -# Optional NEAR RPC for read-only lookups, default https://rpc.testnet.near.org +# Optional NEAR RPC for read-only lookups, default https://test.rpc.fastnear.com (rpc.testnet.near.org is deprecated) NEAR_RPC_URL= # Optional, default 14: workflow run snapshots and Autopilot fire history older than this many days are pruned hourly RUN_RETENTION_DAYS= diff --git a/engine/CLAUDE.md b/engine/CLAUDE.md index 79633101..3eb5921b 100644 --- a/engine/CLAUDE.md +++ b/engine/CLAUDE.md @@ -94,4 +94,4 @@ The `mastra` skill can report bugs and doc defects to the Mastra team. Never let ## Env -See `.env.example` (`NEARAI_API_KEY`, `DATABASE_URL`, `ENGINE_API_KEY`, optional `PORT`, optional `NEAR_RPC_URL` for `near_view_account`, default `https://rpc.testnet.near.org`, optional `RUN_RETENTION_DAYS`, default 14, `BACKEND_URL` for the payment and mail tools, `COMPOSIO_API_KEY` and optional `COMPOSIO_URL` for Gmail, Google Calendar and Google Meet). `.env` is gitignored; never commit it. +See `.env.example` (`NEARAI_API_KEY`, `DATABASE_URL`, `ENGINE_API_KEY`, optional `PORT`, optional `NEAR_RPC_URL` for `near_view_account` and `near_check_transfer`, default `https://test.rpc.fastnear.com` (since 12 Nov: `rpc.testnet.near.org` is deprecated and answered "THIS ENDPOINT IS DEPRECATED!" on and off, failing 11 tests in one full run), optional `RUN_RETENTION_DAYS`, default 14, `BACKEND_URL` for the payment and mail tools, `COMPOSIO_API_KEY` and optional `COMPOSIO_URL` for Gmail, Google Calendar and Google Meet). `.env` is gitignored; never commit it. diff --git a/engine/src/tools.ts b/engine/src/tools.ts index 02623ea6..8cef2766 100644 --- a/engine/src/tools.ts +++ b/engine/src/tools.ts @@ -724,7 +724,10 @@ const buyFromMind = createTool({ }) // Read-only NEAR account lookup on testnet (#20 "check balance"). Public RPC, no keys, moves nothing. -const NEAR_RPC_URL = process.env.NEAR_RPC_URL ?? 'https://rpc.testnet.near.org' +// rpc.testnet.near.org is deprecated and was answering "THIS ENDPOINT IS DEPRECATED! STOP USING IT NOW!" instead of results +// on and off (12 Nov), so the default is FastNear's testnet RPC, listed at docs.near.org/api/rpc/providers. +export const DEFAULT_NEAR_RPC_URL = 'https://test.rpc.fastnear.com' +const NEAR_RPC_URL = process.env.NEAR_RPC_URL ?? DEFAULT_NEAR_RPC_URL const YOCTO_PER_NEAR = 10n ** 24n const nearViewAccount = createTool({ id: 'near_view_account', @@ -769,7 +772,7 @@ const nearCheckTransfer = createTool({ }), execute: async ({ txHash, senderId, amountNear }, context) => { // Read per call, not at import, so tests can point it at a fake RPC. - const res = await fetch(process.env.NEAR_RPC_URL ?? 'https://rpc.testnet.near.org', { + const res = await fetch(process.env.NEAR_RPC_URL ?? DEFAULT_NEAR_RPC_URL, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 'engine', method: 'tx', params: { tx_hash: txHash, sender_account_id: senderId, wait_until: 'FINAL' } }),