@ubi.fun/agent-kit 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -2
- package/bin/agent-kit.mjs +7 -0
- package/lib/kit.mjs +399 -0
- package/lib/ubi-circle.mjs +363 -0
- package/package.json +39 -4
package/README.md
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ubi.fun Agent Kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
One command gives your AI agent its own wallet, an onchain identity and ubi.fun:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npx @ubi.fun/agent-kit
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
1. **Circle Agent Wallet.** Installs a pinned Circle CLI (the [`ubi-circle`](../skills/ubi-circle/SKILL.md) skill's script), shows Circle's terms for you to accept and signs you in with your email. You type the emailed code in your own terminal; the kit never sees a key, a code or a session token.
|
|
10
|
+
2. **Onchain identity.** Registers your agent in Arc's agent registry, the ERC-8004 Identity Registry Arc lists as its own (`0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`). Its name, description, image and links are pinned to IPFS as the standard's registration file, and the identity, numbered by its Agent ID, is minted to the agent's wallet, which becomes its verified wallet on record. ubi.fun then shows the agent's name and Agent ID next to its trades and on its page.
|
|
11
|
+
3. **Connect.** Adds the ubi.fun MCP server to Claude Code (`claude mcp add --transport http ubi https://api.ubi.fun/mcp`). Other apps take `https://api.ubi.fun/mcp` as a remote MCP server.
|
|
12
|
+
4. **Skills.** Installs the ubi.fun skills (`npx skills add ubidotfun/skills --skill '*'`).
|
|
13
|
+
|
|
14
|
+
Arc gas is paid in USDC. Every transaction is simulated before Circle sends it, and the kit asks before each one.
|
|
15
|
+
|
|
16
|
+
## Options
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
--name <text> --description <text> the agent's profile (asked for when not given)
|
|
20
|
+
--image <https url> --website <https url> optional profile fields
|
|
21
|
+
--x <@handle> --mcp <url> --a2a <url> optional links: X, the agent's own MCP or A2A endpoint
|
|
22
|
+
--address <0x...> which of your Circle Agent Wallets to use
|
|
23
|
+
--agent-id <number> update the identity with this Agent ID instead of registering another
|
|
24
|
+
--wallet <0x...> any other wallet: print the unsigned transaction to send yourself
|
|
25
|
+
--yes no confirmation prompts (Circle's terms and login still need you)
|
|
26
|
+
--skip-connect --skip-skills leave Claude Code and the skills as they are
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
A wallet that already has an onchain identity gets its profile updated instead of a second one (you are asked first). The kit never registers when it cannot tell: if the lookup fails, or the wallet holds an identity ubi.fun has not indexed yet, it stops without sending anything. If a run stops after the registration landed, it prints the `--agent-id` command that finishes the profile.
|
|
30
|
+
|
|
31
|
+
## Already connected?
|
|
32
|
+
|
|
33
|
+
Ask your agent: `Use ubi: give my agent an onchain identity`. The MCP tools are `prepare_agent_id`, `prepare_agent_id_update` and `get_agent_id`. Docs: https://ubi.fun/docs/integrate/agents
|
|
34
|
+
|
|
35
|
+
Requires Node.js 20 or newer. MIT license.
|
package/lib/kit.mjs
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
// ubi.fun Agent Kit: a Circle Agent Wallet, an onchain identity in Arc's agent registry (ERC-8004) and the
|
|
2
|
+
// ubi.fun MCP server for your agent, in one run.
|
|
3
|
+
//
|
|
4
|
+
// Trust model, same as the ubi.fun MCP server and the ubi-circle skill: no key, email code or
|
|
5
|
+
// session token passes through this kit. Circle's CLI signs and submits (lib/ubi-circle.mjs, a
|
|
6
|
+
// byte-for-byte copy of skills/ubi-circle/scripts/ubi-circle.mjs); you accept Circle's terms and
|
|
7
|
+
// type the emailed code in your own terminal; the MCP server only prepares unsigned transactions.
|
|
8
|
+
import { spawn } from 'node:child_process'
|
|
9
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
10
|
+
import { tmpdir } from 'node:os'
|
|
11
|
+
import { dirname, join } from 'node:path'
|
|
12
|
+
import { createInterface } from 'node:readline/promises'
|
|
13
|
+
import { fileURLToPath } from 'node:url'
|
|
14
|
+
|
|
15
|
+
export const MCP_URL = process.env.UBI_MCP_URL ?? 'https://api.ubi.fun/mcp'
|
|
16
|
+
export const RPC_URL = process.env.UBI_CIRCLE_RPC_URL ?? 'https://rpc.mainnet.arc.io'
|
|
17
|
+
export const SITE = 'https://ubi.fun'
|
|
18
|
+
/** Arc's ERC-8004 Identity Registry (docs.arc.io contract addresses). */
|
|
19
|
+
export const REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432'
|
|
20
|
+
const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
|
|
21
|
+
const ZERO_TOPIC = `0x${'0'.repeat(64)}`
|
|
22
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/
|
|
23
|
+
const UBI_CIRCLE = join(dirname(fileURLToPath(import.meta.url)), 'ubi-circle.mjs')
|
|
24
|
+
export const CLAUDE_MCP_ADD = ['mcp', 'add', '--transport', 'http', 'ubi', 'https://api.ubi.fun/mcp']
|
|
25
|
+
export const SKILLS_ADD = ['--yes', 'skills', 'add', 'ubidotfun/skills', '--skill', '*']
|
|
26
|
+
|
|
27
|
+
export class KitError extends Error {
|
|
28
|
+
constructor(code, message) {
|
|
29
|
+
super(message)
|
|
30
|
+
this.code = code
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// --- arguments -----------------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
const VALUE_FLAGS = { '--name': 'name', '--description': 'description', '--image': 'image', '--website': 'website', '--x': 'x', '--mcp': 'mcp', '--a2a': 'a2a', '--address': 'address', '--wallet': 'wallet', '--agent-id': 'agentId' }
|
|
37
|
+
const BOOL_FLAGS = { '--yes': 'yes', '-y': 'yes', '--skip-connect': 'skipConnect', '--skip-skills': 'skipSkills', '--help': 'help', '-h': 'help' }
|
|
38
|
+
|
|
39
|
+
export function parseArgs(argv) {
|
|
40
|
+
const args = {}
|
|
41
|
+
for (let i = 0; i < argv.length; i++) {
|
|
42
|
+
const flag = argv[i]
|
|
43
|
+
if (flag in VALUE_FLAGS) {
|
|
44
|
+
const value = argv[++i]
|
|
45
|
+
if (value === undefined || value.startsWith('--')) throw new KitError('BAD_ARGUMENT', `${flag} needs a value`)
|
|
46
|
+
args[VALUE_FLAGS[flag]] = value
|
|
47
|
+
} else if (flag in BOOL_FLAGS) {
|
|
48
|
+
args[BOOL_FLAGS[flag]] = true
|
|
49
|
+
} else {
|
|
50
|
+
throw new KitError('BAD_ARGUMENT', `Unknown option ${flag}. Run with --help.`)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
for (const key of ['address', 'wallet']) {
|
|
54
|
+
if (args[key] !== undefined && !ADDRESS.test(args[key])) throw new KitError('BAD_ARGUMENT', `--${key} must be a 0x address`)
|
|
55
|
+
}
|
|
56
|
+
if (args.agentId !== undefined && !/^\d{1,30}$/.test(args.agentId)) throw new KitError('BAD_ARGUMENT', '--agent-id must be a number')
|
|
57
|
+
if (args.agentId !== undefined && args.wallet) throw new KitError('BAD_ARGUMENT', '--agent-id works with a Circle Agent Wallet, not with --wallet')
|
|
58
|
+
return args
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const HELP = `ubi.fun Agent Kit: give your AI agent a Circle Agent Wallet, an onchain identity on Arc and ubi.fun
|
|
62
|
+
|
|
63
|
+
npx @ubi.fun/agent-kit interactive: wallet, identity, connect, skills
|
|
64
|
+
|
|
65
|
+
--name <text> --description <text> the agent's profile (asked for when not given)
|
|
66
|
+
--image <https url> --website <https url> optional profile fields
|
|
67
|
+
--x <@handle> --mcp <url> --a2a <url> optional links: X, the agent's own MCP or A2A endpoint
|
|
68
|
+
--address <0x...> which of your Circle Agent Wallets to use
|
|
69
|
+
--agent-id <number> update the identity with this Agent ID instead of registering another
|
|
70
|
+
--wallet <0x...> any other wallet: print the unsigned transaction to send yourself
|
|
71
|
+
--yes no confirmation prompts (Circle's terms and login still need you)
|
|
72
|
+
--skip-connect --skip-skills leave Claude Code and the skills as they are
|
|
73
|
+
|
|
74
|
+
The identity is an ERC-8004 token in Arc's Identity Registry (${REGISTRY}), numbered by its Agent ID.
|
|
75
|
+
ubi.fun shows the agent's name and Agent ID next to its trades. Docs: ${SITE}/docs/integrate/agents
|
|
76
|
+
`
|
|
77
|
+
|
|
78
|
+
// --- small helpers -------------------------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
/** One MCP tool call over Streamable HTTP (the server is stateless: no session needed). */
|
|
81
|
+
export async function callTool(name, args, { fetchImpl = fetch, url = MCP_URL } = {}) {
|
|
82
|
+
const response = await fetchImpl(url, {
|
|
83
|
+
method: 'POST',
|
|
84
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
|
|
85
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
|
|
86
|
+
signal: AbortSignal.timeout(90_000),
|
|
87
|
+
})
|
|
88
|
+
if (!response.ok) throw new KitError('MCP_UNAVAILABLE', `ubi.fun MCP answered HTTP ${response.status}`)
|
|
89
|
+
const payload = await response.json()
|
|
90
|
+
const text = payload?.result?.content?.[0]?.text
|
|
91
|
+
if (payload?.error) throw new KitError('MCP_ERROR', payload.error.message ?? 'MCP error')
|
|
92
|
+
if (typeof text !== 'string') throw new KitError('MCP_ERROR', `${name} returned nothing`)
|
|
93
|
+
if (payload.result.isError) throw new KitError('MCP_TOOL_ERROR', text.replace(/^MCP error -?\d+: /, ''))
|
|
94
|
+
return JSON.parse(text)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The Agent ID minted to `wallet` in a receipt: the registry's Transfer from the zero address. */
|
|
98
|
+
export function agentIdFromLogs(logs, wallet) {
|
|
99
|
+
for (const log of logs ?? []) {
|
|
100
|
+
if (String(log.address).toLowerCase() !== REGISTRY.toLowerCase()) continue
|
|
101
|
+
const [topic0, from, to, id] = log.topics ?? []
|
|
102
|
+
if (topic0 !== TRANSFER_TOPIC || from !== ZERO_TOPIC || !to || !id) continue
|
|
103
|
+
if (BigInt(to) !== BigInt(wallet)) continue
|
|
104
|
+
return BigInt(id).toString()
|
|
105
|
+
}
|
|
106
|
+
return null
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** How many Agent IDs `wallet` owns (the registry's ERC-721 balanceOf), read on chain. */
|
|
110
|
+
export async function agentIdsHeld(wallet, fetchImpl = fetch) {
|
|
111
|
+
const response = await fetchImpl(RPC_URL, {
|
|
112
|
+
method: 'POST',
|
|
113
|
+
headers: { 'content-type': 'application/json' },
|
|
114
|
+
body: JSON.stringify({
|
|
115
|
+
jsonrpc: '2.0',
|
|
116
|
+
id: 1,
|
|
117
|
+
method: 'eth_call',
|
|
118
|
+
params: [{ to: REGISTRY, data: `0x70a08231${wallet.slice(2).toLowerCase().padStart(64, '0')}` }, 'latest'],
|
|
119
|
+
}),
|
|
120
|
+
signal: AbortSignal.timeout(20_000),
|
|
121
|
+
})
|
|
122
|
+
const payload = await response.json().catch(() => null)
|
|
123
|
+
if (typeof payload?.result !== 'string' || !/^0x[0-9a-fA-F]{1,64}$/.test(payload.result)) {
|
|
124
|
+
throw new KitError('RPC_UNAVAILABLE', 'Could not read the registry on Arc. Nothing was sent; run again shortly.')
|
|
125
|
+
}
|
|
126
|
+
return BigInt(payload.result)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function receiptOf(hash, fetchImpl = fetch) {
|
|
130
|
+
const response = await fetchImpl(RPC_URL, {
|
|
131
|
+
method: 'POST',
|
|
132
|
+
headers: { 'content-type': 'application/json' },
|
|
133
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getTransactionReceipt', params: [hash] }),
|
|
134
|
+
signal: AbortSignal.timeout(20_000),
|
|
135
|
+
})
|
|
136
|
+
const payload = await response.json()
|
|
137
|
+
return payload?.result ?? null
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** An X handle or x.com link as the handle the MCP takes; undefined when it is neither. */
|
|
141
|
+
export function normalizeX(value) {
|
|
142
|
+
const match = /^@?([A-Za-z0-9_]{1,15})$/.exec(value.trim()) ?? /^https?:\/\/(?:www\.)?(?:x|twitter)\.com\/([A-Za-z0-9_]{1,15})\/?$/i.exec(value.trim())
|
|
143
|
+
return match ? `@${match[1]}` : undefined
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The prepare_agent_id arguments from the answers; only fields that were given. */
|
|
147
|
+
export function profileArgs(answers) {
|
|
148
|
+
const out = { name: answers.name.trim(), description: answers.description.trim() }
|
|
149
|
+
if (answers.image) out.imageUrl = answers.image.trim()
|
|
150
|
+
if (answers.website) out.website = answers.website.trim()
|
|
151
|
+
if (answers.x) {
|
|
152
|
+
const x = normalizeX(answers.x)
|
|
153
|
+
if (!x) throw new KitError('BAD_ARGUMENT', 'X must be a handle like @name or an x.com link')
|
|
154
|
+
out.x = x
|
|
155
|
+
}
|
|
156
|
+
if (answers.mcp) out.mcp = answers.mcp.trim()
|
|
157
|
+
if (answers.a2a) out.a2a = answers.a2a.trim()
|
|
158
|
+
return out
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Runs lib/ubi-circle.mjs; `inherit` hands the terminal over (terms, login). */
|
|
162
|
+
function ubiCircle(args, { inherit = false } = {}) {
|
|
163
|
+
return new Promise((resolve) => {
|
|
164
|
+
const child = spawn(process.execPath, [UBI_CIRCLE, ...args], { stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'] })
|
|
165
|
+
let stdout = ''
|
|
166
|
+
let stderr = ''
|
|
167
|
+
child.stdout?.on('data', (chunk) => (stdout += chunk))
|
|
168
|
+
child.stderr?.on('data', (chunk) => (stderr += chunk))
|
|
169
|
+
child.on('close', (code) => {
|
|
170
|
+
let json = null
|
|
171
|
+
try {
|
|
172
|
+
json = JSON.parse(stdout)
|
|
173
|
+
} catch {
|
|
174
|
+
// interactive or non-JSON output
|
|
175
|
+
}
|
|
176
|
+
resolve({ code, json, stdout, stderr })
|
|
177
|
+
})
|
|
178
|
+
})
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function run(command, args, { inherit = true } = {}) {
|
|
182
|
+
return new Promise((resolve) => {
|
|
183
|
+
const child = spawn(command, args, { stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32' })
|
|
184
|
+
let output = ''
|
|
185
|
+
child.stdout?.on('data', (chunk) => (output += chunk))
|
|
186
|
+
child.stderr?.on('data', (chunk) => (output += chunk))
|
|
187
|
+
child.on('error', () => resolve({ code: 127, output }))
|
|
188
|
+
child.on('close', (code) => resolve({ code, output }))
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function onPath(command) {
|
|
193
|
+
const probe = process.platform === 'win32' ? await run('where', [command], { inherit: false }) : await run('sh', ['-c', `command -v ${command}`], { inherit: false })
|
|
194
|
+
return probe.code === 0
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// --- the run -------------------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout }) {
|
|
200
|
+
const args = parseArgs(argv)
|
|
201
|
+
if (args.help) {
|
|
202
|
+
io.stdout.write(HELP)
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
const say = (line = '') => io.stdout.write(`${line}\n`)
|
|
206
|
+
const interactive = Boolean(io.stdin.isTTY)
|
|
207
|
+
let rl = interactive ? createInterface({ input: io.stdin, output: io.stdout }) : null
|
|
208
|
+
// A child that takes the terminal (Circle's terms and login, the skills installer) must be its only
|
|
209
|
+
// reader: the kit's own prompt is closed first, so no keystroke, and never the emailed code, reaches it
|
|
210
|
+
const handOver = async (fn) => {
|
|
211
|
+
rl?.close()
|
|
212
|
+
rl = null
|
|
213
|
+
try {
|
|
214
|
+
return await fn()
|
|
215
|
+
} finally {
|
|
216
|
+
if (interactive) rl = createInterface({ input: io.stdin, output: io.stdout })
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const ask = async (question, fallback) => {
|
|
220
|
+
if (!rl) return fallback
|
|
221
|
+
const answer = (await rl.question(question)).trim()
|
|
222
|
+
return answer || fallback
|
|
223
|
+
}
|
|
224
|
+
const confirm = async (question, byDefault = true) => {
|
|
225
|
+
if (args.yes) return true
|
|
226
|
+
if (!rl) return byDefault
|
|
227
|
+
const answer = (await rl.question(`${question} ${byDefault ? '[Y/n]' : '[y/N]'} `)).trim().toLowerCase()
|
|
228
|
+
return answer ? answer.startsWith('y') : byDefault
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
try {
|
|
232
|
+
const [major] = process.versions.node.split('.').map(Number)
|
|
233
|
+
if (major < 20) throw new KitError('NODE_TOO_OLD', `Node.js 20 or newer is needed (this is ${process.versions.node})`)
|
|
234
|
+
say('ubi.fun Agent Kit')
|
|
235
|
+
say(`Agent IDs live in Arc's agent registry (ERC-8004, ${REGISTRY}).`)
|
|
236
|
+
say()
|
|
237
|
+
|
|
238
|
+
// 1. Profile first: nothing is installed or signed before the user has said who the agent is
|
|
239
|
+
const answers = {
|
|
240
|
+
name: args.name ?? (await ask('Agent name: ', undefined)),
|
|
241
|
+
description: args.description ?? (await ask('What does it do? (one or two sentences): ', undefined)),
|
|
242
|
+
image: args.image ?? (await ask('Image URL (https, optional): ', undefined)),
|
|
243
|
+
website: args.website ?? (await ask('Website (https, optional): ', undefined)),
|
|
244
|
+
x: args.x ?? (await ask('X handle (optional): ', undefined)),
|
|
245
|
+
mcp: args.mcp,
|
|
246
|
+
a2a: args.a2a,
|
|
247
|
+
}
|
|
248
|
+
if (!answers.name || !answers.description) {
|
|
249
|
+
throw new KitError('BAD_ARGUMENT', 'An Agent ID needs a name and a description (--name, --description)')
|
|
250
|
+
}
|
|
251
|
+
const profile = profileArgs(answers)
|
|
252
|
+
|
|
253
|
+
// Any wallet: print the unsigned transaction and stop
|
|
254
|
+
if (args.wallet) {
|
|
255
|
+
const prepared = await callTool('prepare_agent_id', { wallet: args.wallet, ...profile })
|
|
256
|
+
say('Send this transaction from your wallet (it was simulated from it). Then ask your agent:')
|
|
257
|
+
say(` Use ubi: run prepare_agent_id_update for my new Agent ID from ${args.wallet}`)
|
|
258
|
+
say()
|
|
259
|
+
say(JSON.stringify(prepared.steps, null, 2))
|
|
260
|
+
return
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// 2. Circle Agent Wallet: the pinned CLI, then the user's own terms and login if needed
|
|
264
|
+
say('Step 1 of 4: Circle Agent Wallet')
|
|
265
|
+
const setup = await ubiCircle(['setup'])
|
|
266
|
+
if (setup.code !== 0 || !setup.json?.ok) throw new KitError(setup.json?.code ?? 'SETUP_FAILED', setup.json?.message ?? 'Installing the Circle CLI failed (npm is needed)')
|
|
267
|
+
let wallets = await ubiCircle(['wallets'])
|
|
268
|
+
if (!wallets.json?.ok) {
|
|
269
|
+
if (!interactive) {
|
|
270
|
+
throw new KitError('NEEDS_YOU', 'No Circle session. Run this kit in your own terminal: Circle terms and the emailed code are yours to answer.')
|
|
271
|
+
}
|
|
272
|
+
say("Circle's terms come first. Read them here:")
|
|
273
|
+
await handOver(() => ubiCircle(['circle', 'terms', 'show'], { inherit: true }))
|
|
274
|
+
// The human answers this in their own terminal; --yes never accepts terms for them
|
|
275
|
+
const accepted = (await rl.question("Do you accept Circle's terms? [y/N] ")).trim().toLowerCase().startsWith('y')
|
|
276
|
+
if (!accepted) throw new KitError('TERMS_DECLINED', "Circle's terms were not accepted. Nothing was set up.")
|
|
277
|
+
await handOver(() => ubiCircle(['circle', 'terms', 'accept'], { inherit: true }))
|
|
278
|
+
const email = (await rl.question('Email for your Circle Agent Wallet: ')).trim()
|
|
279
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) throw new KitError('BAD_ARGUMENT', 'That is not an email address')
|
|
280
|
+
say("Circle emails you a code. Circle's own prompt asks for it next (type it only there, never in a chat).")
|
|
281
|
+
const login = await handOver(() => ubiCircle(['circle', 'wallet', 'login', email, '--type', 'agent'], { inherit: true }))
|
|
282
|
+
if (login.code !== 0) throw new KitError('LOGIN_FAILED', 'Circle login did not finish')
|
|
283
|
+
wallets = await ubiCircle(['wallets'])
|
|
284
|
+
if (!wallets.json?.ok) throw new KitError('CIRCLE_NOT_READY', 'Still no Circle session after login')
|
|
285
|
+
}
|
|
286
|
+
const list = wallets.json.wallets ?? []
|
|
287
|
+
if (list.length === 0) throw new KitError('NO_WALLET', 'Your Circle account has no agent wallet on Arc yet')
|
|
288
|
+
let wallet = list[0].address
|
|
289
|
+
if (args.address) {
|
|
290
|
+
const chosen = list.find((w) => w.address.toLowerCase() === args.address.toLowerCase())
|
|
291
|
+
if (!chosen) throw new KitError('WALLET_NOT_FOUND', `${args.address} is not one of your Circle Agent Wallets on Arc`)
|
|
292
|
+
wallet = chosen.address
|
|
293
|
+
} else if (list.length > 1 && rl) {
|
|
294
|
+
list.forEach((w, i) => say(` ${i + 1}. ${w.address}`))
|
|
295
|
+
const pick = Number(await ask(`Which wallet? [1-${list.length}, default 1] `, '1'))
|
|
296
|
+
wallet = list[Math.min(Math.max(pick, 1), list.length) - 1].address
|
|
297
|
+
}
|
|
298
|
+
say(` Agent wallet on Arc: ${wallet}`)
|
|
299
|
+
say()
|
|
300
|
+
|
|
301
|
+
// 3. Agent ID: register (or update the one this wallet already has), then name the ID in its profile
|
|
302
|
+
say('Step 2 of 4: Agent ID')
|
|
303
|
+
let agentId = args.agentId ?? null
|
|
304
|
+
let registeredNow = false
|
|
305
|
+
// The update always carries the whole profile, so it never depends on reading the new file back
|
|
306
|
+
let updateProfile = profile
|
|
307
|
+
let register = !agentId
|
|
308
|
+
if (!agentId) {
|
|
309
|
+
// Never mint a second ID by accident: an unanswered lookup stops the run, and so does an ID the
|
|
310
|
+
// wallet holds that the index cannot name yet
|
|
311
|
+
let existing
|
|
312
|
+
try {
|
|
313
|
+
existing = await callTool('get_agent_id', { wallet })
|
|
314
|
+
} catch (error) {
|
|
315
|
+
throw new KitError('LOOKUP_FAILED', `Could not check whether ${wallet} already has an Agent ID (${error.message}). Nothing was sent; run again shortly.`)
|
|
316
|
+
}
|
|
317
|
+
const held = await agentIdsHeld(wallet)
|
|
318
|
+
agentId = existing?.primary?.agentId ?? null
|
|
319
|
+
if (agentId) {
|
|
320
|
+
// Only an explicit "n" at the prompt registers another; --yes updates
|
|
321
|
+
register = !(await confirm(`This wallet already has Agent ID #${agentId}. Update its profile instead of registering another?`))
|
|
322
|
+
} else if (held > 0n) {
|
|
323
|
+
const why = existing?.index?.complete === false ? "ubi.fun's index of the registry is still catching up" : 'none of them names it as its verified wallet'
|
|
324
|
+
if (args.yes || !interactive || !(await confirm(`This wallet already holds ${held} Agent ID(s), but ${why}. Register another anyway?`, false))) {
|
|
325
|
+
throw new KitError('ALREADY_HOLDS_ID', `${wallet} already holds ${held} Agent ID(s). Run again with --agent-id <number> to update one, or later once ubi.fun has indexed it. Nothing was sent.`)
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (!register) {
|
|
330
|
+
say(` Updating Agent ID #${agentId}`)
|
|
331
|
+
} else {
|
|
332
|
+
const prepared = await callTool('prepare_agent_id', { wallet, ...profile })
|
|
333
|
+
say(` Profile pinned: ${prepared.agentURI}`)
|
|
334
|
+
// The image is pinned once: the update reuses its CID
|
|
335
|
+
const { imageUrl: _pinned, ...rest } = profile
|
|
336
|
+
const imageCid = /^ipfs:\/\/(\w+)$/.exec(prepared.registrationFile?.image ?? '')?.[1]
|
|
337
|
+
updateProfile = { ...rest, ...(imageCid ? { imageCid } : {}) }
|
|
338
|
+
if (!(await confirm(`Register "${profile.name}" from ${wallet}? Arc gas is paid in USDC.`))) throw new KitError('CANCELLED', 'Nothing was sent')
|
|
339
|
+
const sent = await sendSteps(wallet, prepared)
|
|
340
|
+
const receipt = await receiptOf(sent.txHash).catch(() => null)
|
|
341
|
+
agentId = receipt ? agentIdFromLogs(receipt.logs, wallet) : null
|
|
342
|
+
if (!agentId) {
|
|
343
|
+
throw new KitError('ID_UNKNOWN', `Registered (${sent.explorer}), but the new ID could not be read from the receipt yet. Find it on that page, then finish with: npx @ubi.fun/agent-kit --agent-id <number> --address ${wallet}`)
|
|
344
|
+
}
|
|
345
|
+
registeredNow = true
|
|
346
|
+
say(` Registered: Agent ID #${agentId} (${sent.explorer})`)
|
|
347
|
+
}
|
|
348
|
+
// The standard asks the profile to name its own ID; an existing ID takes the new profile here too
|
|
349
|
+
try {
|
|
350
|
+
const update = await callTool('prepare_agent_id_update', { agentId, wallet, ...updateProfile })
|
|
351
|
+
const updated = await sendSteps(wallet, update)
|
|
352
|
+
say(` Profile ${registeredNow ? 'linked to its ID' : 'updated'} (${updated.explorer})`)
|
|
353
|
+
} catch (error) {
|
|
354
|
+
if (!registeredNow) throw error
|
|
355
|
+
// The ID exists: say so, and how to finish without minting another
|
|
356
|
+
throw new KitError(error.code ?? 'UPDATE_FAILED', `Agent ID #${agentId} is registered, but linking its profile failed: ${error.message}\nFinish with: npx @ubi.fun/agent-kit --agent-id ${agentId} --address ${wallet}`)
|
|
357
|
+
}
|
|
358
|
+
say()
|
|
359
|
+
|
|
360
|
+
// 4. Connect the agent and teach it the tools
|
|
361
|
+
say('Step 3 of 4: Connect ubi.fun')
|
|
362
|
+
if (!args.skipConnect && (await onPath('claude')) && (await confirm('Add ubi.fun to Claude Code?'))) {
|
|
363
|
+
const added = await run('claude', CLAUDE_MCP_ADD, { inherit: false })
|
|
364
|
+
say(added.code === 0 || /already exists/i.test(added.output) ? ' Claude Code is connected to ubi.fun' : ` Claude Code said: ${added.output.trim().slice(0, 200)}`)
|
|
365
|
+
} else {
|
|
366
|
+
say(' Other apps: add the MCP server https://api.ubi.fun/mcp (Streamable HTTP, no API key)')
|
|
367
|
+
}
|
|
368
|
+
say()
|
|
369
|
+
say('Step 4 of 4: Skills')
|
|
370
|
+
if (!args.skipSkills && (await confirm('Install the ubi.fun skills for your agent?'))) {
|
|
371
|
+
await handOver(() => run(process.platform === 'win32' ? 'npx.cmd' : 'npx', SKILLS_ADD))
|
|
372
|
+
}
|
|
373
|
+
say()
|
|
374
|
+
say(`Done. ${profile.name} is Agent ID #${agentId} on Arc.`)
|
|
375
|
+
say(` Its page: ${SITE}/notes/${wallet.toLowerCase()}`)
|
|
376
|
+
say(` Fund it with USDC on Arc to trade: ${SITE}/bridge`)
|
|
377
|
+
say(' Try: "Use ubi-circle: buy $5 of $UBI from my Circle wallet"')
|
|
378
|
+
} finally {
|
|
379
|
+
rl?.close()
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Sends a prepare_* result through ubi-circle and returns the last step's hash and link. */
|
|
384
|
+
async function sendSteps(wallet, prepared) {
|
|
385
|
+
const dir = mkdtempSync(join(tmpdir(), 'ubi-agent-kit-'))
|
|
386
|
+
const file = join(dir, 'steps.json')
|
|
387
|
+
try {
|
|
388
|
+
writeFileSync(file, JSON.stringify(prepared), { mode: 0o600 })
|
|
389
|
+
const sent = await ubiCircle(['send', '--address', wallet, '--file', file])
|
|
390
|
+
if (!sent.json?.ok) {
|
|
391
|
+
const error = sent.json ?? { code: 'SEND_FAILED', message: sent.stderr.trim() || 'Circle did not send the transaction' }
|
|
392
|
+
throw new KitError(error.code, `${error.message}${error.done?.length ? ` (sent so far: ${JSON.stringify(error.done)})` : ''}`)
|
|
393
|
+
}
|
|
394
|
+
const last = sent.json.results.at(-1)
|
|
395
|
+
return { txHash: last.txHash, explorer: last.explorer }
|
|
396
|
+
} finally {
|
|
397
|
+
rmSync(dir, { recursive: true, force: true })
|
|
398
|
+
}
|
|
399
|
+
}
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ubi-circle: send the unsigned steps from the ubi.fun MCP server (prepare_swap, prepare_launch,
|
|
3
|
+
// prepare_launch_v3, claims) from a Circle Agent Wallet on Arc mainnet.
|
|
4
|
+
//
|
|
5
|
+
// Circle's CLI signs and submits. It only accepts "function signature + text arguments", which
|
|
6
|
+
// cannot carry the lists and structs a Universal Router swap or a launch needs, while Circle's
|
|
7
|
+
// API itself accepts raw calldata (`callData` on user contract execution). `setup` installs one
|
|
8
|
+
// pinned Circle CLI version into ~/.ubi-circle, checks its hash, and writes a copy beside it that
|
|
9
|
+
// adds a `--call-data` flag for Circle Agent Wallets only. The installed CLI file is not changed.
|
|
10
|
+
//
|
|
11
|
+
// No key, email code or session token ever passes through this script: you log in with the
|
|
12
|
+
// Circle CLI in your own terminal, and the session stays in ~/.ubi-circle/home.
|
|
13
|
+
import { execFile, spawn } from 'node:child_process'
|
|
14
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
16
|
+
import { homedir } from 'node:os'
|
|
17
|
+
import { join, resolve } from 'node:path'
|
|
18
|
+
import { pathToFileURL } from 'node:url'
|
|
19
|
+
|
|
20
|
+
const CLI_PACKAGE = '@circle-fin/cli'
|
|
21
|
+
const CLI_VERSION = '1.2.2'
|
|
22
|
+
const CLI_SHA256 = '12b484ff7b1b23666ee9e2784d811bfa366b7af0fef4d842ea82e1dc8693b56e'
|
|
23
|
+
const PATCH_ID = 'ubi-circle-calldata-v1'
|
|
24
|
+
const CHAIN_ID = 5042
|
|
25
|
+
const RPC_URL = process.env.UBI_CIRCLE_RPC_URL ?? 'https://rpc.mainnet.arc.io'
|
|
26
|
+
const ROOT = process.env.UBI_CIRCLE_ROOT ?? join(homedir(), '.ubi-circle')
|
|
27
|
+
const RUNTIME = join(ROOT, 'runtime')
|
|
28
|
+
const CLI_HOME = join(ROOT, 'home')
|
|
29
|
+
const DIST = join(RUNTIME, 'node_modules', '@circle-fin', 'cli', 'dist')
|
|
30
|
+
const STOCK = join(DIST, 'index.js')
|
|
31
|
+
const PATCHED = join(DIST, 'ubi-calldata.mjs')
|
|
32
|
+
const MANIFEST = join(ROOT, 'patch.json')
|
|
33
|
+
|
|
34
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/
|
|
35
|
+
const HEX = /^0x(?:[0-9a-fA-F]{2})*$/
|
|
36
|
+
const sha256 = (text) => createHash('sha256').update(text).digest('hex')
|
|
37
|
+
const same = (a, b) => typeof a === 'string' && typeof b === 'string' && a.toLowerCase() === b.toLowerCase()
|
|
38
|
+
|
|
39
|
+
class Stop extends Error {
|
|
40
|
+
constructor(code, message, extra = {}) {
|
|
41
|
+
super(message)
|
|
42
|
+
this.code = code
|
|
43
|
+
this.extra = extra
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function print(value) {
|
|
48
|
+
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ---------------------------------------------------------------------------------------------
|
|
52
|
+
// The patch: exact anchors in @circle-fin/cli 1.2.2, each required to occur exactly once.
|
|
53
|
+
|
|
54
|
+
export function patchCircleSource(original) {
|
|
55
|
+
if (sha256(original) !== CLI_SHA256) {
|
|
56
|
+
throw new Stop('CLI_MISMATCH', `Expected the unmodified ${CLI_PACKAGE}@${CLI_VERSION} build`)
|
|
57
|
+
}
|
|
58
|
+
let out = original
|
|
59
|
+
const replace = (from, to) => {
|
|
60
|
+
if (out.split(from).length !== 2) throw new Stop('PATCH_ANCHOR', `Patch anchor not found exactly once: ${from.slice(0, 60)}`)
|
|
61
|
+
out = out.replace(from, to)
|
|
62
|
+
}
|
|
63
|
+
// 1. The hex after --call-data is a flag value, not a positional ABI argument.
|
|
64
|
+
replace(
|
|
65
|
+
' "--idempotency-key",\n "--amount",\n "--collateral",',
|
|
66
|
+
' "--idempotency-key",\n "--call-data",\n "--amount",\n "--collateral",',
|
|
67
|
+
)
|
|
68
|
+
// 2. wallet execute: raw calldata replaces the signature and its arguments, on ARC only.
|
|
69
|
+
replace(
|
|
70
|
+
' const abiFunctionSignature = pos[0];\n if (!abiFunctionSignature) {\n outputError(\n "Missing required argument: <abiFunctionSignature>. Run --help for usage.",',
|
|
71
|
+
` const abiFunctionSignature = pos[0];
|
|
72
|
+
const ubiCallData = readFlagValue(args2, "--call-data");
|
|
73
|
+
if (args2.includes("--call-data") && (args2.filter((v) => v === "--call-data").length !== 1
|
|
74
|
+
|| typeof ubiCallData !== "string" || !/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(ubiCallData)
|
|
75
|
+
|| pos.length !== 0 || blockchain !== "ARC")) {
|
|
76
|
+
outputError("--call-data needs one hex value, no ABI arguments, and --chain ARC.", args2, "INVALID_ARGUMENT");
|
|
77
|
+
process.exitCode = 1;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (!abiFunctionSignature && !ubiCallData) {
|
|
81
|
+
outputError(
|
|
82
|
+
"Missing required argument: <abiFunctionSignature>. Run --help for usage.",`,
|
|
83
|
+
)
|
|
84
|
+
// 3. Local wallets keep the stock behavior: raw calldata goes to Circle Agent Wallets only.
|
|
85
|
+
replace(
|
|
86
|
+
' if (resolved.wallet.type === "local") {\n if (estimate) {\n await handleLocalExecuteEstimate(',
|
|
87
|
+
` if (resolved.wallet.type === "local") {
|
|
88
|
+
if (args2.includes("--call-data")) {
|
|
89
|
+
outputError("--call-data is only for Circle Agent Wallets.", args2, "INVALID_ARGUMENT");
|
|
90
|
+
process.exitCode = 1;
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (estimate) {
|
|
94
|
+
await handleLocalExecuteEstimate(`,
|
|
95
|
+
)
|
|
96
|
+
// 4. The agent path sends { callData } in place of { abiFunctionSignature, abiParameters }.
|
|
97
|
+
replace(
|
|
98
|
+
'async function handleAgentExecute(wallet, env, blockchain, contractAddress, abiFunctionSignature, abiParameters, value, estimate, args2) {\n const proxyUrl',
|
|
99
|
+
`async function handleAgentExecute(wallet, env, blockchain, contractAddress, abiFunctionSignature, abiParameters, value, estimate, args2) {
|
|
100
|
+
const ubiCallData = readFlagValue(args2, "--call-data");
|
|
101
|
+
const ubiCall = ubiCallData ? { callData: ubiCallData } : { abiFunctionSignature, abiParameters: abiParameters.length > 0 ? abiParameters : void 0 };
|
|
102
|
+
const proxyUrl`,
|
|
103
|
+
)
|
|
104
|
+
replace(
|
|
105
|
+
' contractAddress,\n abiFunctionSignature,\n abiParameters: abiParameters.length > 0 ? abiParameters : void 0,\n amount: value !== "0" ? value : void 0',
|
|
106
|
+
' contractAddress,\n ...ubiCall,\n amount: value !== "0" ? value : void 0',
|
|
107
|
+
)
|
|
108
|
+
replace(
|
|
109
|
+
' idempotencyKey,\n contractAddress,\n abiFunctionSignature,\n abiParameters: abiParameters.length > 0 ? abiParameters : void 0,\n amount: value !== "0" ? value : void 0',
|
|
110
|
+
' idempotencyKey,\n contractAddress,\n ...ubiCall,\n amount: value !== "0" ? value : void 0',
|
|
111
|
+
)
|
|
112
|
+
return out
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ---------------------------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
function run(file, args, { timeoutMs = 180_000, inherit = false } = {}) {
|
|
118
|
+
const env = { ...process.env, CIRCLE_CLI_HOME: CLI_HOME, CIRCLE_VERSION_CHECK: 'off', DO_NOT_TRACK: '1' }
|
|
119
|
+
if (inherit) {
|
|
120
|
+
return new Promise((resolve) => {
|
|
121
|
+
const child = spawn(process.execPath, [file, ...args], { env, stdio: 'inherit' })
|
|
122
|
+
child.on('close', (code) => resolve({ code }))
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
return new Promise((resolve) => {
|
|
126
|
+
execFile(process.execPath, [file, ...args], { env, timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
127
|
+
resolve({ code: error ? (error.code ?? 1) : 0, stdout, stderr, interrupted: Boolean(error?.killed || error?.signal) })
|
|
128
|
+
})
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function verifyRuntime() {
|
|
133
|
+
if (!existsSync(STOCK) || !existsSync(PATCHED) || !existsSync(MANIFEST)) {
|
|
134
|
+
throw new Stop('NOT_SET_UP', 'Run: node ubi-circle.mjs setup')
|
|
135
|
+
}
|
|
136
|
+
const manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'))
|
|
137
|
+
if (manifest.patchId !== PATCH_ID || manifest.upstreamVersion !== CLI_VERSION
|
|
138
|
+
|| sha256(readFileSync(STOCK, 'utf8')) !== CLI_SHA256 || sha256(readFileSync(PATCHED, 'utf8')) !== manifest.patchedSha256) {
|
|
139
|
+
throw new Stop('RUNTIME_MISMATCH', 'The Circle runtime in ~/.ubi-circle changed. Run setup again.')
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function setup() {
|
|
144
|
+
mkdirSync(RUNTIME, { recursive: true, mode: 0o700 })
|
|
145
|
+
mkdirSync(CLI_HOME, { recursive: true, mode: 0o700 })
|
|
146
|
+
if (!existsSync(STOCK) || sha256(readFileSync(STOCK, 'utf8')) !== CLI_SHA256) {
|
|
147
|
+
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'
|
|
148
|
+
const result = await new Promise((resolve) => {
|
|
149
|
+
execFile(npm, ['install', '--prefix', RUNTIME, '--ignore-scripts', '--no-audit', '--no-fund', `${CLI_PACKAGE}@${CLI_VERSION}`],
|
|
150
|
+
{ timeout: 300_000, shell: process.platform === 'win32' }, (error, stdout, stderr) => resolve({ error, stderr }))
|
|
151
|
+
})
|
|
152
|
+
if (result.error) throw new Stop('INSTALL_FAILED', `npm install failed: ${result.stderr}`)
|
|
153
|
+
}
|
|
154
|
+
const original = readFileSync(STOCK, 'utf8')
|
|
155
|
+
const patched = patchCircleSource(original)
|
|
156
|
+
writeFileSync(PATCHED, patched, { mode: 0o600 })
|
|
157
|
+
const manifest = {
|
|
158
|
+
patchId: PATCH_ID,
|
|
159
|
+
upstreamPackage: CLI_PACKAGE,
|
|
160
|
+
upstreamVersion: CLI_VERSION,
|
|
161
|
+
upstreamSha256: CLI_SHA256,
|
|
162
|
+
patchedSha256: sha256(patched),
|
|
163
|
+
change: 'wallet execute accepts --call-data <hex> for Circle Agent Wallets on ARC; everything else is the stock CLI',
|
|
164
|
+
}
|
|
165
|
+
writeFileSync(MANIFEST, `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 })
|
|
166
|
+
print({ ok: true, ...manifest, cliHome: CLI_HOME,
|
|
167
|
+
next: [
|
|
168
|
+
'In YOUR terminal (never through an agent): node ubi-circle.mjs circle terms show, then circle terms accept',
|
|
169
|
+
'node ubi-circle.mjs circle wallet login YOUR_EMAIL --type agent (type the emailed code there)',
|
|
170
|
+
'node ubi-circle.mjs wallets',
|
|
171
|
+
] })
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// One JSON-RPC call, checked before anything trusts it: version 2.0, this request's fresh id, and
|
|
175
|
+
// exactly one of an error object or a result that passes `valid`. Anything else throws RPC_INVALID,
|
|
176
|
+
// so a malformed answer can never read as a passed simulation or a receipt.
|
|
177
|
+
async function rpc(method, params, valid) {
|
|
178
|
+
const id = randomUUID()
|
|
179
|
+
const response = await fetch(RPC_URL, {
|
|
180
|
+
method: 'POST',
|
|
181
|
+
headers: { 'content-type': 'application/json' },
|
|
182
|
+
body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
|
|
183
|
+
signal: AbortSignal.timeout(20_000),
|
|
184
|
+
})
|
|
185
|
+
if (!response.ok) throw new Stop('RPC_UNAVAILABLE', `Arc RPC answered HTTP ${response.status}`)
|
|
186
|
+
const invalid = (why) => new Stop('RPC_INVALID', `Arc RPC answered ${method} with ${why}`)
|
|
187
|
+
let payload
|
|
188
|
+
try { payload = JSON.parse(await response.text()) } catch { throw invalid('a body that is not JSON') }
|
|
189
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw invalid('something other than one response object')
|
|
190
|
+
if (payload.jsonrpc !== '2.0' || payload.id !== id) throw invalid('a different version or request id')
|
|
191
|
+
const hasResult = Object.hasOwn(payload, 'result')
|
|
192
|
+
if (hasResult === Object.hasOwn(payload, 'error')) throw invalid('both or neither of result and error')
|
|
193
|
+
if (!hasResult) {
|
|
194
|
+
const { error } = payload
|
|
195
|
+
if (!error || typeof error !== 'object' || !Number.isInteger(error.code) || typeof error.message !== 'string') throw invalid('a malformed error')
|
|
196
|
+
return { error }
|
|
197
|
+
}
|
|
198
|
+
if (!valid(payload.result)) throw invalid('a malformed result')
|
|
199
|
+
return { result: payload.result }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const isCallResult = (r) => typeof r === 'string' && HEX.test(r)
|
|
203
|
+
const isRevert = (error) => error.code === 3 || /revert/i.test(error.message)
|
|
204
|
+
|
|
205
|
+
async function agentWallets() {
|
|
206
|
+
const result = await run(STOCK, ['wallet', 'list', '--type', 'agent', '--chain', 'ARC', '--output', 'json'], { timeoutMs: 60_000 })
|
|
207
|
+
let payload
|
|
208
|
+
try { payload = JSON.parse(result.stdout) } catch { payload = null }
|
|
209
|
+
const wallets = payload?.data?.wallets
|
|
210
|
+
if (result.code !== 0 || !Array.isArray(wallets)) {
|
|
211
|
+
throw new Stop('CIRCLE_NOT_READY', 'No Circle session. Log in with: node ubi-circle.mjs circle wallet login YOUR_EMAIL --type agent', { stderr: result.stderr?.trim() })
|
|
212
|
+
}
|
|
213
|
+
return wallets.filter((w) => w.blockchain === 'ARC' && typeof w.address === 'string')
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Accepts a prepare_* tool result, its `steps` array, or one step. */
|
|
217
|
+
export function readSteps(input) {
|
|
218
|
+
const parsed = typeof input === 'string' ? JSON.parse(input) : input
|
|
219
|
+
const steps = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.steps) ? parsed.steps : parsed?.to ? [parsed] : null
|
|
220
|
+
if (!steps || steps.length === 0) throw new Stop('NO_STEPS', 'Input has no steps. Pass the JSON a ubi prepare_* tool returned.')
|
|
221
|
+
if (steps.length > 8) throw new Stop('TOO_MANY_STEPS', 'More than 8 steps in one request')
|
|
222
|
+
return steps.map((step, index) => {
|
|
223
|
+
if (step.chainId !== undefined && Number(step.chainId) !== CHAIN_ID) throw new Stop('WRONG_CHAIN', `Step ${index + 1} is for chain ${step.chainId}, not Arc (${CHAIN_ID})`)
|
|
224
|
+
if (!ADDRESS.test(step.to ?? '')) throw new Stop('BAD_STEP', `Step ${index + 1} has no valid "to" address`)
|
|
225
|
+
if (typeof step.data !== 'string' || !HEX.test(step.data) || step.data.length < 10) throw new Stop('BAD_STEP', `Step ${index + 1} has no calldata`)
|
|
226
|
+
const value = String(step.value ?? '0')
|
|
227
|
+
if (!/^(0|[1-9][0-9]{0,40})$/.test(value)) throw new Stop('BAD_STEP', `Step ${index + 1} value must be a decimal integer in wei`)
|
|
228
|
+
return { description: String(step.description ?? `step ${index + 1}`), to: step.to, data: step.data, value }
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Wei (18 decimals, Arc's native USDC) to the decimal string Circle's --amount takes. */
|
|
233
|
+
export function weiToDecimal(wei) {
|
|
234
|
+
const v = BigInt(wei)
|
|
235
|
+
const whole = v / 10n ** 18n
|
|
236
|
+
const frac = (v % 10n ** 18n).toString().padStart(18, '0').replace(/0+$/, '')
|
|
237
|
+
return frac ? `${whole}.${frac}` : `${whole}`
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** ok only for a well-formed eth_call result; a revert is { ok: false }, any other answer throws. */
|
|
241
|
+
export async function simulate(from, step) {
|
|
242
|
+
const { error } = await rpc('eth_call', [{ from, to: step.to, data: step.data, value: `0x${BigInt(step.value).toString(16)}` }, 'latest'], isCallResult)
|
|
243
|
+
if (!error) return { ok: true }
|
|
244
|
+
if (isRevert(error)) return { ok: false, error: error.message, data: error.data }
|
|
245
|
+
throw new Stop('RPC_UNAVAILABLE', `Arc RPC could not run the simulation: ${error.code} ${error.message}`)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function waitReceipt(hash, timeoutMs = 120_000) {
|
|
249
|
+
const isReceipt = (r) => r === null || (typeof r === 'object' && same(r.transactionHash, hash) && (r.status === '0x1' || r.status === '0x0'))
|
|
250
|
+
const deadline = Date.now() + timeoutMs
|
|
251
|
+
while (Date.now() < deadline) {
|
|
252
|
+
const { result, error } = await rpc('eth_getTransactionReceipt', [hash], isReceipt)
|
|
253
|
+
if (error) throw new Stop('RPC_UNAVAILABLE', `${error.code} ${error.message}`)
|
|
254
|
+
if (result) return result
|
|
255
|
+
await new Promise((r) => setTimeout(r, 2_000))
|
|
256
|
+
}
|
|
257
|
+
return null
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function send(args) {
|
|
261
|
+
verifyRuntime()
|
|
262
|
+
const address = args.address
|
|
263
|
+
if (!ADDRESS.test(address ?? '')) throw new Stop('BAD_ARGUMENT', '--address <your Circle Agent Wallet on ARC> is required')
|
|
264
|
+
const raw = args.file ? readFileSync(args.file, 'utf8') : readFileSync(0, 'utf8')
|
|
265
|
+
const steps = readSteps(raw)
|
|
266
|
+
const wallets = await agentWallets()
|
|
267
|
+
if (!wallets.some((w) => same(w.address, address))) throw new Stop('WALLET_NOT_FOUND', `${address} is not one of your Circle Agent Wallets on ARC`)
|
|
268
|
+
|
|
269
|
+
const results = []
|
|
270
|
+
for (const [index, step] of steps.entries()) {
|
|
271
|
+
// Each step is simulated against the chain as it is right now, after the previous step landed.
|
|
272
|
+
// A failed read here happens before anything of this step is sent; earlier steps stay reported.
|
|
273
|
+
let sim
|
|
274
|
+
try {
|
|
275
|
+
sim = await simulate(address, step)
|
|
276
|
+
} catch (error) {
|
|
277
|
+
throw new Stop(error.code ?? 'RPC_UNAVAILABLE', `Step ${index + 1} (${step.description}) could not be simulated (${error.message}). Nothing of this step was sent.`, { done: results })
|
|
278
|
+
}
|
|
279
|
+
if (!sim.ok) {
|
|
280
|
+
throw new Stop('SIMULATION_FAILED', `Step ${index + 1} (${step.description}) would revert: ${sim.error}. Nothing more was sent.`, { done: results, revertData: sim.data })
|
|
281
|
+
}
|
|
282
|
+
if (args.dryRun) {
|
|
283
|
+
results.push({ step: index + 1, description: step.description, simulated: true })
|
|
284
|
+
if (steps.length > 1) results.push({ note: 'Later steps depend on this one landing, so a dry run checks the first step only.' })
|
|
285
|
+
break
|
|
286
|
+
}
|
|
287
|
+
const idempotencyKey = randomUUID()
|
|
288
|
+
const result = await run(PATCHED, ['wallet', 'execute', '--call-data', step.data, '--contract', step.to, '--address', address,
|
|
289
|
+
'--chain', 'ARC', '--amount', weiToDecimal(step.value), '--idempotency-key', idempotencyKey, '--output', 'json'])
|
|
290
|
+
let data = null
|
|
291
|
+
try { data = JSON.parse(result.stdout)?.data ?? null } catch { /* reported below */ }
|
|
292
|
+
const hash = typeof data?.txHash === 'string' && /^0x[0-9a-fA-F]{64}$/.test(data.txHash) ? data.txHash : null
|
|
293
|
+
if (result.code !== 0 || result.interrupted || !hash) {
|
|
294
|
+
// After the request went out, the transaction may still land: never resend automatically.
|
|
295
|
+
// A hash Circle printed before failing is kept, so the outcome can still be looked up.
|
|
296
|
+
const known = hash ? { txHash: hash, explorer: `https://arc.etherscan.io/tx/${hash}` } : {}
|
|
297
|
+
throw new Stop('OUTCOME_UNKNOWN', `Step ${index + 1} (${step.description}): Circle did not ${hash ? 'finish cleanly' : 'confirm a transaction hash'}. Do NOT resend. Check with: node ubi-circle.mjs circle transaction list --address ${address} --chain ARC`, {
|
|
298
|
+
done: [...results, { step: index + 1, description: step.description, idempotencyKey, ...known, status: 'unknown' }],
|
|
299
|
+
idempotencyKey, ...known, circleState: data?.state, stderr: result.stderr?.trim().slice(0, 500) })
|
|
300
|
+
}
|
|
301
|
+
// Sent: from here every outcome carries the hash and the key, so nothing is ever sent twice
|
|
302
|
+
const sent = { step: index + 1, description: step.description, txHash: hash, idempotencyKey, explorer: `https://arc.etherscan.io/tx/${hash}` }
|
|
303
|
+
let receipt
|
|
304
|
+
try {
|
|
305
|
+
receipt = await waitReceipt(hash)
|
|
306
|
+
} catch (error) {
|
|
307
|
+
throw new Stop('RECEIPT_UNKNOWN', `Step ${index + 1} (${step.description}) was sent (${hash}) but its receipt could not be read (${error.message}). Do NOT resend: check the explorer link, then prepare fresh steps for whatever is left.`, {
|
|
308
|
+
done: [...results, { ...sent, status: 'unknown' }] })
|
|
309
|
+
}
|
|
310
|
+
const status = receipt ? (receipt.status === '0x1' ? 'confirmed' : 'reverted') : 'pending'
|
|
311
|
+
results.push({ ...sent, status })
|
|
312
|
+
if (status !== 'confirmed') {
|
|
313
|
+
throw new Stop(status === 'reverted' ? 'REVERTED' : 'PENDING', `Step ${index + 1} ${status}. Stopped before the next step.`, { done: results })
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
print({ ok: true, address, results })
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function parseArgs(argv) {
|
|
320
|
+
const args = { _: [] }
|
|
321
|
+
for (let i = 0; i < argv.length; i++) {
|
|
322
|
+
const a = argv[i]
|
|
323
|
+
if (a === '--address') args.address = argv[++i]
|
|
324
|
+
else if (a === '--file') args.file = argv[++i]
|
|
325
|
+
else if (a === '--dry-run') args.dryRun = true
|
|
326
|
+
else args._.push(a)
|
|
327
|
+
}
|
|
328
|
+
return args
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const HELP = `ubi-circle: send ubi.fun MCP steps from a Circle Agent Wallet on Arc
|
|
332
|
+
|
|
333
|
+
node ubi-circle.mjs setup install the pinned Circle CLI + calldata flag
|
|
334
|
+
node ubi-circle.mjs circle <args...> run the stock Circle CLI (login, terms, balances)
|
|
335
|
+
node ubi-circle.mjs wallets list your Circle Agent Wallets on ARC
|
|
336
|
+
node ubi-circle.mjs send --address 0x... [--file steps.json] [--dry-run]
|
|
337
|
+
simulate, then send each step in order (stdin if no --file)
|
|
338
|
+
`
|
|
339
|
+
|
|
340
|
+
async function main() {
|
|
341
|
+
const [command, ...rest] = process.argv.slice(2)
|
|
342
|
+
if (command === 'setup') return setup()
|
|
343
|
+
if (command === 'circle') {
|
|
344
|
+
verifyRuntime()
|
|
345
|
+
const { code } = await run(STOCK, rest, { inherit: true })
|
|
346
|
+
process.exitCode = code ?? 0
|
|
347
|
+
return
|
|
348
|
+
}
|
|
349
|
+
if (command === 'wallets') {
|
|
350
|
+
verifyRuntime()
|
|
351
|
+
const wallets = await agentWallets()
|
|
352
|
+
return print({ ok: true, wallets: wallets.map((w) => ({ address: w.address, type: w.type, accountType: w.accountType, state: w.state })) })
|
|
353
|
+
}
|
|
354
|
+
if (command === 'send') return send(parseArgs(rest))
|
|
355
|
+
process.stdout.write(HELP)
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
359
|
+
main().catch((error) => {
|
|
360
|
+
print({ ok: false, code: error.code ?? 'ERROR', message: error.message, ...(error.extra ?? {}) })
|
|
361
|
+
process.exitCode = 1
|
|
362
|
+
})
|
|
363
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ubi.fun/agent-kit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Give your AI agent a Circle Agent Wallet, an onchain identity in Arc's agent registry (ERC-8004) and the ubi.fun MCP server, in one command",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "ubi.fun",
|
|
7
|
+
"homepage": "https://ubi.fun/docs/integrate/agents",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/ubidotfun/skills.git",
|
|
11
|
+
"directory": "agent-kit"
|
|
12
|
+
},
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"ubi.fun",
|
|
18
|
+
"arc",
|
|
19
|
+
"circle",
|
|
20
|
+
"agent wallet",
|
|
21
|
+
"erc-8004",
|
|
22
|
+
"agent id",
|
|
23
|
+
"mcp",
|
|
24
|
+
"ai agent"
|
|
25
|
+
],
|
|
26
|
+
"type": "module",
|
|
27
|
+
"bin": {
|
|
28
|
+
"agent-kit": "bin/agent-kit.mjs"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"bin",
|
|
32
|
+
"lib",
|
|
33
|
+
"README.md"
|
|
34
|
+
],
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=20"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "node --test test/kit.test.mjs"
|
|
40
|
+
}
|
|
41
|
+
}
|