stuntman 0.2.3 → 0.2.5

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/dist/bull.js ADDED
@@ -0,0 +1,98 @@
1
+ // Bull Streams on Robinhood Chain: the payment rail Attesta GPU rentals run on.
2
+ // The contracts are not verified on an explorer; the selector, the word layout
3
+ // of createStream and the StreamCreated event below match what Attesta checks
4
+ // against live Bull responses and logs.
5
+ import { lower } from './chain.js';
6
+ export const BULL_STREAMS = '0x80ad26c36aacfc4b846b8b81aa2c7acc762f9e39';
7
+ export const USDG = '0x5fc5360d0400a0fd4f2af552add042d716f1d168';
8
+ export const USDG_DECIMALS = 6;
9
+ export const CREATE_STREAM = '0x7257808e';
10
+ export const STREAM_CREATED = '0x11329d7d55d43657768c9720255d640f43a18c79f1564b25e33492456fe95cc8';
11
+ const word = (data, i) => data.slice(10 + i * 64, 10 + (i + 1) * 64);
12
+ const wordAddr = (data, i) => `0x${word(data, i).slice(24)}`;
13
+ const wordInt = (data, i) => BigInt(`0x${word(data, i) || '0'}`);
14
+ /** createStream calldata on Bull Streams, or null for any other call. */
15
+ export function decodeCreateStream(to, data) {
16
+ if (!to || lower(to) !== BULL_STREAMS || !data.toLowerCase().startsWith(CREATE_STREAM) || data.length < 10 + 8 * 64)
17
+ return null;
18
+ return {
19
+ payee: wordAddr(data, 0),
20
+ arbiter: wordAddr(data, 1),
21
+ asset: wordAddr(data, 2),
22
+ amount: wordInt(data, 3),
23
+ durationSeconds: Number(wordInt(data, 5)),
24
+ feeWei: wordInt(data, 7),
25
+ };
26
+ }
27
+ /** The StreamCreated events in a set of logs. */
28
+ export function streamsCreated(logs) {
29
+ const out = [];
30
+ for (const l of logs) {
31
+ if (lower(l.address) !== BULL_STREAMS || l.topics[0]?.toLowerCase() !== STREAM_CREATED || l.topics.length < 4)
32
+ continue;
33
+ const d = l.data.slice(2);
34
+ const w = (i) => d.slice(i * 64, (i + 1) * 64);
35
+ out.push({
36
+ id: BigInt(l.topics[1]).toString(),
37
+ payer: `0x${l.topics[2].slice(26)}`,
38
+ payee: `0x${l.topics[3].slice(26)}`,
39
+ arbiter: `0x${w(0).slice(24)}`,
40
+ asset: `0x${w(1).slice(24)}`,
41
+ amount: BigInt(`0x${w(2) || '0'}`),
42
+ start: Number(BigInt(`0x${w(3) || '0'}`)),
43
+ end: Number(BigInt(`0x${w(4) || '0'}`)),
44
+ });
45
+ }
46
+ return out;
47
+ }
48
+ /** Whole USDG from 6-decimal units, without trailing zeros. */
49
+ export function usdg(raw) {
50
+ const neg = raw < 0n;
51
+ const v = neg ? -raw : raw;
52
+ const whole = v / 10n ** 6n;
53
+ const frac = (v % 10n ** 6n).toString().padStart(6, '0').replace(/0+$/, '');
54
+ return `${neg ? '-' : ''}${whole}${frac ? `.${frac}` : ''}`;
55
+ }
56
+ /** 6-decimal units from a whole USDG amount such as "12.5". */
57
+ export function usdgRaw(whole) {
58
+ const s = String(whole).trim();
59
+ if (!/^\d+(\.\d{1,6})?$/.test(s))
60
+ throw new Error(`${s} is not a USDG amount`);
61
+ const [w, f = ''] = s.split('.');
62
+ return BigInt(w) * 10n ** 6n + BigInt(f.padEnd(6, '0'));
63
+ }
64
+ function minutes(seconds) {
65
+ if (seconds % 3600 === 0)
66
+ return `${seconds / 3600} h`;
67
+ if (seconds % 60 === 0)
68
+ return `${seconds / 60} min`;
69
+ return `${seconds} s`;
70
+ }
71
+ /** Names for payees Stuntman knows, such as the stand-ins its Attesta practice API uses. */
72
+ const names = new Map();
73
+ export function nameAddress(address, name) {
74
+ names.set(lower(address), name);
75
+ }
76
+ export function knownName(address) {
77
+ if (lower(address) === BULL_STREAMS)
78
+ return 'Bull Streams';
79
+ const named = names.get(lower(address));
80
+ if (named)
81
+ return named;
82
+ // Stand-in payees from Stuntman's Attesta practice API all start with "STUNTMAN".
83
+ if (lower(address).startsWith('0x5354554e544d414e'))
84
+ return 'an Attesta GPU provider (practice)';
85
+ return undefined;
86
+ }
87
+ /** A plain-words summary for a filled take that opened a Bull stream. */
88
+ export function describeBullTake(take) {
89
+ if (take.status !== 'filled')
90
+ return null;
91
+ const call = decodeCreateStream(take.request.to, take.request.data);
92
+ if (!call)
93
+ return null;
94
+ const created = streamsCreated(take.logs)[0];
95
+ const asset = lower(call.asset) === USDG ? `${usdg(call.amount)} USDG` : `${call.amount} units of ${call.asset}`;
96
+ const payee = knownName(call.payee) ?? `${call.payee.slice(0, 6)}…${call.payee.slice(-4)}`;
97
+ return `Opened a ${asset} Bull stream to ${payee} over ${minutes(call.durationSeconds)}${created ? ` (stream ${created.id})` : ''}`;
98
+ }
package/dist/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // Stuntman command line. `npx stuntman` with no arguments shows where you are.
3
- import { existsSync, readFileSync } from 'node:fs';
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
4
5
  import { homedir } from 'node:os';
5
6
  import { parseUnits } from 'viem';
6
7
  import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
@@ -57,7 +58,7 @@ Start
57
58
  Connect your agent
58
59
  stuntman mcp Practice wallet as an MCP server (stdio)
59
60
  stuntman rpc [--port 8545] Practice RPC for agents that send their own transactions
60
- stuntman connect [claude|codex|json|raxol|virtuals|eliza|openclaw|priors] Print the setup line for your agent
61
+ stuntman connect [claude|codex|json|raxol|virtuals|eliza|agentkit|openai|langchain|attesta|openclaw|priors] Print the setup line for your agent
61
62
 
62
63
  Watch the takes
63
64
  stuntman takes [--limit 20] Recent takes
@@ -87,7 +88,11 @@ Other
87
88
  stuntman --version
88
89
 
89
90
  Settings live in ${stuntmanHome()}. Set STUNTMAN_RPC_URL to use another node.`;
91
+ const CONNECT_TARGETS = ['claude', 'codex', 'json', 'raxol', 'virtuals', 'eliza', 'agentkit', 'openai', 'langchain', 'attesta', 'openclaw', 'priors'];
90
92
  function connectLines(target) {
93
+ if (target !== 'all' && !CONNECT_TARGETS.includes(target)) {
94
+ throw new Error(`Unknown connect target "${target}". Choose one of: ${CONNECT_TARGETS.join(', ')}.`);
95
+ }
91
96
  // Installed with the one-line installer: point agents at that exact Node.js
92
97
  // and script, so MCP apps that don't read your shell PATH still find it.
93
98
  const node = process.env.STUNTMAN_NODE;
@@ -115,6 +120,17 @@ function connectLines(target) {
115
120
  '# In code, the Xochi config raxol_payments takes:',
116
121
  `%{base_url: "http://127.0.0.1:${DEFAULT_PORT}/xochi", auth: {:member, token}}`,
117
122
  ].join('\n');
123
+ case 'attesta':
124
+ return [
125
+ '# Attesta GPU rentals: launches and Bull stream payments are practiced, never sent to Attesta.',
126
+ `# Local practice: run "${rpc}", then point the agent at:`,
127
+ `# Attesta base URL http://127.0.0.1:${DEFAULT_PORT}/attesta`,
128
+ `# RPC for the Bull steps http://127.0.0.1:${DEFAULT_PORT}`,
129
+ `# Witnessed: run "${installed ? 'stuntman' : 'npx stuntman'} witness" and use <endpoint>/attesta as the base URL, <endpoint> as the RPC.`,
130
+ '',
131
+ '# Sign in through the practice API (POST /v1/auth/challenge, then /v1/auth/login) for a practice key.',
132
+ '# Your real Attesta key is never needed. Give the practice account ETH and USDG with "stuntman fund".',
133
+ ].join('\n');
118
134
  case 'priors':
119
135
  return [
120
136
  '# Priors agents: rehearse borrows, repays and stock trades before they are real.',
@@ -139,12 +155,39 @@ function connectLines(target) {
139
155
  '',
140
156
  `# Get a witness endpoint with "${installed ? 'stuntman' : 'npx stuntman'} witness" (or witness --key-env for the agent's own wallet).`,
141
157
  ].join('\n');
158
+ case 'openai':
159
+ return [
160
+ '# OpenAI Agents SDK: give the agent Stuntman practice tools.',
161
+ 'npm install stuntman @openai/agents zod',
162
+ "import { stuntmanTools, PRACTICE_INSTRUCTIONS } from 'stuntman/openai';",
163
+ 'instructions: PRACTICE_INSTRUCTIONS,',
164
+ 'tools: await stuntmanTools({ endpoint: process.env.STUNTMAN_ENDPOINT }),',
165
+ '',
166
+ `# Get a witness endpoint with "${installed ? 'stuntman' : 'npx stuntman'} witness", or use http://127.0.0.1:8545 from "${rpc}".`,
167
+ ].join('\n');
168
+ case 'langchain':
169
+ return [
170
+ '# LangChain and LangGraph: Stuntman practice tools as standard LangChain tools.',
171
+ 'npm install stuntman langchain @langchain/core',
172
+ "import { stuntmanTools, PRACTICE_INSTRUCTIONS } from 'stuntman/langchain';",
173
+ 'createAgent({ model, systemPrompt: PRACTICE_INSTRUCTIONS, tools: await stuntmanTools({ endpoint: process.env.STUNTMAN_ENDPOINT }) })',
174
+ '',
175
+ `# Get a witness endpoint with "${installed ? 'stuntman' : 'npx stuntman'} witness", or use http://127.0.0.1:8545 from "${rpc}".`,
176
+ ].join('\n');
177
+ case 'agentkit':
178
+ return [
179
+ '# Coinbase AgentKit: use the Stuntman wallet provider, so AgentKit transactions are practiced.',
180
+ 'npm install stuntman @coinbase/agentkit',
181
+ "import { stuntmanWalletProvider, stuntmanActionProvider } from 'stuntman/agentkit';",
182
+ 'walletProvider: await stuntmanWalletProvider({ privateKey: process.env.AGENT_KEY, endpoint: process.env.STUNTMAN_ENDPOINT }),',
183
+ 'actionProviders: [await stuntmanActionProvider({ endpoint: process.env.STUNTMAN_ENDPOINT }), ...yourProviders],',
184
+ '',
185
+ `# Get a witness endpoint for the agent's own wallet with "${installed ? 'stuntman' : 'npx stuntman'} witness --key-env AGENT_KEY".`,
186
+ ].join('\n');
142
187
  case 'openclaw':
143
188
  return [
144
189
  '# OpenClaw: add the Stuntman skill, then ask your agent to practice a trade first.',
145
- '# Until it is listed on ClawHub, copy it from the repository:',
146
- 'git clone https://github.com/stuntmanhq/stuntman',
147
- 'cp -r stuntman/skills/stuntman ~/.openclaw/skills/',
190
+ `${installed ? 'stuntman' : 'npx stuntman'} connect openclaw --install # copies the skill into ~/.openclaw/skills/stuntman`,
148
191
  '',
149
192
  '# Or connect the MCP server directly:',
150
193
  json,
@@ -172,10 +215,22 @@ function connectLines(target) {
172
215
  '',
173
216
  `Agents that send their own transactions: run "${rpc}" and use http://127.0.0.1:${DEFAULT_PORT} as the RPC address.`,
174
217
  `Raxol agents: run "${rpc}", then "${installed ? 'stuntman' : 'npx stuntman'} connect raxol" for the two settings.`,
175
- `Virtuals GAME agents: "${installed ? 'stuntman' : 'npx stuntman'} connect virtuals". ElizaOS: "connect eliza". OpenClaw: "connect openclaw". Priors: "connect priors".`,
218
+ `Virtuals GAME agents: "${installed ? 'stuntman' : 'npx stuntman'} connect virtuals". ElizaOS: "connect eliza". AgentKit: "connect agentkit". OpenAI Agents: "connect openai". LangChain: "connect langchain". Attesta: "connect attesta". OpenClaw: "connect openclaw". Priors: "connect priors".`,
176
219
  ].join('\n');
177
220
  }
178
221
  }
222
+ /** Copies the Stuntman skill that ships in this package into OpenClaw's skills folder. */
223
+ function installOpenClawSkill(flags) {
224
+ const source = new URL('../skills/stuntman/SKILL.md', import.meta.url);
225
+ if (!existsSync(source))
226
+ throw new Error('The Stuntman skill is missing from this install. Reinstall stuntman.');
227
+ const root = typeof flags.dir === 'string' ? flags.dir : join(homedir(), '.openclaw', 'skills');
228
+ const dir = join(root, 'stuntman');
229
+ mkdirSync(dir, { recursive: true });
230
+ copyFileSync(source, join(dir, 'SKILL.md'));
231
+ out(`Installed the Stuntman skill in ${dir}.`);
232
+ out('Restart OpenClaw or start a new session, then ask your agent to practice a trade before making it.');
233
+ }
179
234
  async function cmdInit(flags) {
180
235
  const rpcUrl = typeof flags.rpc === 'string' ? flags.rpc : process.env.STUNTMAN_RPC_URL || DEFAULT_RPC_URL;
181
236
  let account;
@@ -208,9 +263,11 @@ async function cmdInit(flags) {
208
263
  if (!previous || previous.account.toLowerCase() !== account.toLowerCase() || previous.chainId !== chainId) {
209
264
  resetPractice(chainId, account);
210
265
  }
211
- if (typeof flags.eth === 'string') {
266
+ // A new practice key starts with 1 practice ETH, so the first send works.
267
+ const startEth = typeof flags.eth === 'string' ? flags.eth : mode === 'practice-key' ? '1' : undefined;
268
+ if (startEth !== undefined && Number(startEth) > 0) {
212
269
  const engine = await createEngine(cfg);
213
- const res = await fund(engine, 'ETH', parseUnits(flags.eth, 18));
270
+ const res = await fund(engine, 'ETH', parseUnits(startEth, 18));
214
271
  out(`Practice ETH set to ${fmt(res.balance, 18)}.`);
215
272
  }
216
273
  out(`Stuntman is set up.`);
@@ -280,6 +337,9 @@ async function cmdTake(args, flags) {
280
337
  if (!take)
281
338
  throw new Error(`No take ${args[0] ?? ''}. Run "stuntman takes" to see them.`);
282
339
  out(flags.json ? JSON.stringify(take, null, 2) : formatTake(take, true));
340
+ if (!flags.json) {
341
+ out(cfg.witness ? `Take link: ${witnessBase()}/a/${checksum(cfg.account)}/t/${take.id}` : `Take page (while "stuntman rpc" runs): http://127.0.0.1:${DEFAULT_PORT}/takes/${take.id}`);
342
+ }
283
343
  }
284
344
  async function cmdBalances(args) {
285
345
  const cfg = requireConfig();
@@ -369,13 +429,15 @@ async function cmdRpc(flags) {
369
429
  await startProxy(engine, {
370
430
  port,
371
431
  host,
372
- onTake: (t) => err(`Take ${t.id} ${t.status === 'filled' ? 'filled' : 'bad '} ${t.summary}`),
432
+ onTake: (t) => err(`Take ${t.id} ${t.status === 'filled' ? 'filled' : 'bad '} ${t.summary} http://${host}:${port}/takes/${t.id}`),
373
433
  onError: (m) => err(`Error: ${m}`),
374
434
  });
375
435
  err(`Stuntman practice RPC on http://${host}:${port}`);
376
436
  err(`Practicing as ${checksum(cfg.account)} on chain ${cfg.chainId}, reads from ${cfg.rpcUrl}`);
377
437
  err(`Simulation: ${describeCapabilities(engine.caps)}. Nothing sent here is ever broadcast.`);
378
438
  err(`Xochi practice gateway on http://${host}:${port}/xochi (quotes from ${xochiUrl()}, executes stay here).`);
439
+ err(`Your takes: http://${host}:${port}/takes`);
440
+ err(`Attesta practice API on http://${host}:${port}/attesta (GPU catalog and quotes from Attesta, rentals practiced here).`);
379
441
  err('Press Ctrl+C to stop.');
380
442
  }
381
443
  async function cmdWitness(args, flags) {
@@ -412,6 +474,7 @@ async function cmdWitness(args, flags) {
412
474
  out('');
413
475
  out('The agent signs as usual; Stuntman simulates every transaction it sends there and broadcasts nothing.');
414
476
  out('Practice money for this agent: the endpoint accepts stuntman_fund, or use the GAME worker\'s add_practice_money.');
477
+ out(`Attesta GPU rentals in practice: use ${endpoint}/attesta as the Attesta base URL.`);
415
478
  return;
416
479
  }
417
480
  const cfg = requireConfig();
@@ -421,10 +484,18 @@ async function cmdWitness(args, flags) {
421
484
  out('Witness mode is off. Takes are simulated on this machine again. Your witnessed record stays online.');
422
485
  return;
423
486
  }
487
+ // The witness keeps its own ledger and record: say so before switching over.
488
+ const wasLocal = !cfg.witness;
489
+ const localTakes = wasLocal ? readTakes().length : 0;
490
+ const localEth = wasLocal ? readState(cfg.chainId, cfg.account).accountState.eth : undefined;
424
491
  const { account, endpoint } = await registerWitness(cfg);
425
492
  cfg.witness = endpoint;
426
493
  saveConfig(cfg);
427
494
  const base = witnessBase();
495
+ if (wasLocal && (localTakes || (localEth && localEth !== '0'))) {
496
+ out(`Note: the witness starts this agent from zero. Your ${localTakes} local take${localTakes === 1 ? '' : 's'}${localEth && localEth !== '0' ? ` and ${fmt(BigInt(localEth), 18)} practice ETH` : ''} stay on this machine and come back with "stuntman witness off".`);
497
+ out('');
498
+ }
428
499
  const conf = (await fetch(`${base}/api/witness/config`).then((r) => r.json()).catch(() => null));
429
500
  out(`Witnessed practice is on for ${account}.`);
430
501
  out('');
@@ -435,7 +506,18 @@ async function cmdWitness(args, flags) {
435
506
  out('');
436
507
  out('The Stuntman MCP tools now send through the witness. Agents that send their own');
437
508
  out('transactions: use the endpoint above as the RPC address.');
438
- out('Practice money on the witness is separate: add some with "stuntman fund ETH 1".');
509
+ out(`Attesta GPU rentals in practice: use ${endpoint}/attesta as the Attesta base URL.`);
510
+ const witnessEth = await remoteCall(endpoint, 'stuntman_balances')
511
+ .then((rows) => rows.find((r) => r.token === 'ETH')?.formatted)
512
+ .catch(() => undefined);
513
+ out('');
514
+ if (!witnessEth || Number(witnessEth) === 0) {
515
+ out('The witness has no practice money for this agent yet. Add some before the first take:');
516
+ out(' stuntman fund ETH 1');
517
+ }
518
+ else {
519
+ out(`Practice ETH on the witness: ${witnessEth}. Add more with "stuntman fund ETH 1".`);
520
+ }
439
521
  if (conf?.freeTakes !== undefined) {
440
522
  out('');
441
523
  out(conf.billing
@@ -475,6 +557,8 @@ async function cmdSend(flags) {
475
557
  if (take)
476
558
  out(formatTake(take));
477
559
  out('Witnessed by Stuntman. Nothing was broadcast.');
560
+ if (take)
561
+ out(`Take link: ${witnessBase()}/a/${checksum(cfg.account)}/t/${take.id}`);
478
562
  if (take && take.status !== 'filled')
479
563
  process.exitCode = 1;
480
564
  return;
@@ -535,7 +619,9 @@ async function main() {
535
619
  case 'mcp':
536
620
  return cmdMcp();
537
621
  case 'connect':
538
- return out(connectLines(args[0] ?? 'all'));
622
+ if ((args[0] ?? '').toLowerCase() === 'openclaw' && flags.install)
623
+ return installOpenClawSkill(flags);
624
+ return out(connectLines((args[0] ?? 'all').toLowerCase()));
539
625
  case 'witness':
540
626
  return cmdWitness(args, flags);
541
627
  case 'send':
package/dist/engine.js CHANGED
@@ -5,7 +5,7 @@ import { encodeFunctionData as encodeFn, getContractAddress, keccak256, numberTo
5
5
  import { RpcClient, RpcError } from './rpc.js';
6
6
  import { detectCapabilities } from './caps.js';
7
7
  import { PERMIT2_ADDRESS, TOPICS, checksum, fmt, isAddr, lower, readAllowance, readBalanceOf, readPermit2Allowance, readTokenInfo, revertReason, shortAddr, topicToAddress, } from './chain.js';
8
- import { appendTake, readState, withLock, writeState, } from './store.js';
8
+ import { appendTake, readTakes, readState, withLock, writeState, } from './store.js';
9
9
  import { buildOverrides, slotKey } from './overlay.js';
10
10
  import { confirmPermit2Slot, findAllowanceSlot, findBalanceSlot } from './slots.js';
11
11
  import { compatRun, debugTrace, ethBalanceRead, readNow, simulateV1 } from './simulate.js';
@@ -13,6 +13,7 @@ import { DEPLOYER_RUNTIME } from './executor.generated.js';
13
13
  import { addressesInInitcode, balanceReadCall, rememberAddresses, simulateAndCapture, slotsFor, storageCandidates, touchedContracts } from './contracts.js';
14
14
  import { decodeFunctionResult, encodeFunctionData } from 'viem';
15
15
  import { ERC20_ABI, PERMIT2_ABI } from './chain.js';
16
+ import { decodeCreateStream, describeBullTake, knownName } from './bull.js';
16
17
  // Anything this large is an "infinite" approval (MaxUint256 for ERC-20, MaxUint160 for Permit2).
17
18
  const UNLIMITED = 1n << 128n;
18
19
  const MAX_CANDIDATES = 12;
@@ -282,8 +283,17 @@ export async function runTake(engine, req) {
282
283
  blockHash,
283
284
  logs: [],
284
285
  });
285
- const reject = (reason, code = -32000) => {
286
+ const reject = (reason, code = -32000, outOfFunds = false) => {
287
+ if (outOfFunds)
288
+ reason = `${reason}. Out of practice ETH: run "stuntman fund ETH 1" to add more.`;
286
289
  const take = { ...baseTake(), status: 'rejected', reason, summary: `Rejected: ${reason}` };
290
+ // Running out of practice money is a setup problem, not the agent's mistake:
291
+ // the first miss isn't kept, so it never counts against the record.
292
+ if (outOfFunds && !state.accountState.missedFunds) {
293
+ state.accountState.missedFunds = true;
294
+ writeState(state);
295
+ throw new TakeRejected(reason, take, code);
296
+ }
287
297
  state.takeCount = id;
288
298
  writeState(state);
289
299
  appendTake(take);
@@ -295,6 +305,14 @@ export async function runTake(engine, req) {
295
305
  if (req.chainId !== undefined && req.chainId !== cfg.chainId) {
296
306
  reject(`Transaction is signed for chain ${req.chainId}, but this is chain ${cfg.chainId}. It was not sent anywhere.`, -32602);
297
307
  }
308
+ // A Bull createStream carries a fee quote signed for one stream, so the exact
309
+ // same calldata twice means paying for the same stream twice.
310
+ if (decodeCreateStream(req.to, req.data)) {
311
+ const again = readTakes().find((t) => t.status === 'filled' && lower(t.request.to ?? '') === lower(req.to ?? '') && t.request.data.toLowerCase() === req.data.toLowerCase());
312
+ if (again) {
313
+ reject(`This repeats take ${again.id}: the same Bull stream was already opened (${again.summary}). Opening it again would lock the USDG twice. Report the first stream instead.`);
314
+ }
315
+ }
298
316
  // Nonce: practice nonce, starting from the real pending nonce.
299
317
  const realNonce = Number(BigInt(await rpc.request('eth_getTransactionCount', [account, 'pending'])));
300
318
  const expectedNonce = Math.max(state.accountState.nonce ?? 0, realNonce);
@@ -327,7 +345,7 @@ export async function runTake(engine, req) {
327
345
  // A node refuses a transaction the account can't fund before running it.
328
346
  const upfront = req.value + (req.gas ?? 0n) * feeCap;
329
347
  if (ethBefore < upfront) {
330
- reject(`insufficient funds for gas * price + value: address ${account} have ${ethBefore} want ${upfront}`);
348
+ reject(`insufficient funds for gas * price + value: address ${account} have ${ethBefore} want ${upfront}`, -32000, true);
331
349
  }
332
350
  if (!req.to) {
333
351
  return deployTake({ engine, state, req, account, id, notes, baseTake, reject, ethBefore, overrides, expectedNonce, price, feeCap });
@@ -541,7 +559,7 @@ export async function runTake(engine, req) {
541
559
  // The node would refuse a transaction the account can't fund.
542
560
  const required = req.value + gasLimit * feeCap;
543
561
  if (ethBefore < required) {
544
- reject(`insufficient funds for gas * price + value: address ${account} have ${ethBefore} want ${required}`);
562
+ reject(`insufficient funds for gas * price + value: address ${account} have ${ethBefore} want ${required}`, -32000, true);
545
563
  }
546
564
  const changes = [];
547
565
  const approvals = [];
@@ -675,7 +693,7 @@ async function deployTake(c) {
675
693
  const gasLimit = req.gas ?? estimate ?? 5000000n;
676
694
  const required = req.value + gasLimit * feeCap;
677
695
  if (ethBefore < required) {
678
- reject(`insufficient funds for gas * price + value: address ${account} have ${ethBefore} want ${required}`);
696
+ reject(`insufficient funds for gas * price + value: address ${account} have ${ethBefore} want ${required}`, -32000, true);
679
697
  }
680
698
  const known = [account, address, ...addressesInInitcode(req.data), ...state.known];
681
699
  const ov = { ...overrides, [lower(account)]: { ...(overrides[lower(account)] ?? {}), balance: numberToHex(ethBefore), nonce: numberToHex(nonce) } };
@@ -930,6 +948,9 @@ export function summarize(take, gasCost) {
930
948
  return `Rejected: ${take.reason ?? 'not accepted'}`;
931
949
  if (take.status === 'reverted')
932
950
  return `Reverted: ${take.reason ?? 'execution reverted'}`;
951
+ const bull = describeBullTake(take);
952
+ if (bull)
953
+ return bull;
933
954
  const moves = take.changes
934
955
  .map((c) => {
935
956
  let delta = BigInt(c.delta);
@@ -952,7 +973,7 @@ export function summarize(take, gasCost) {
952
973
  if (take.approvals.length) {
953
974
  const a = take.approvals[0];
954
975
  const amt = BigInt(a.amount);
955
- const what = amt === 0n ? `Revoked ${shortAddr(a.spender)} from spending ${a.symbol}` : `Approved ${shortAddr(a.spender)} to spend ${fmtAmount(amt, a)}`;
976
+ const what = amt === 0n ? `Revoked ${shortAddr(a.spender)} from spending ${a.symbol}` : `Approved ${knownName(a.spender) ?? shortAddr(a.spender)} to spend ${fmtAmount(amt, a)}`;
956
977
  return take.approvals.length > 1 ? `${what} (+${take.approvals.length - 1} more)` : what;
957
978
  }
958
979
  const to = take.request.to ?? '';
@@ -972,6 +993,7 @@ export async function fund(engine, asset, amount) {
972
993
  if (next < 0n)
973
994
  throw new Error('That would take the practice ETH balance below zero.');
974
995
  state.accountState.eth = next.toString();
996
+ delete state.accountState.missedFunds;
975
997
  writeState(state);
976
998
  return { symbol: 'ETH', decimals: 18, balance: next, visible: true };
977
999
  }
@@ -996,6 +1018,7 @@ export async function fund(engine, asset, amount) {
996
1018
  if (next < 0n)
997
1019
  throw new Error(`That would take the practice ${info.symbol} balance below zero.`);
998
1020
  state.accountState.tokens[token] = next.toString();
1021
+ delete state.accountState.missedFunds;
999
1022
  writeState(state);
1000
1023
  return { symbol: info.symbol, decimals: info.decimals, balance: next, visible: true };
1001
1024
  });
@@ -0,0 +1,23 @@
1
+ // Stuntman for LangChain and LangGraph.
2
+ //
3
+ // import { createAgent } from 'langchain';
4
+ // import { stuntmanTools, PRACTICE_INSTRUCTIONS } from 'stuntman/langchain';
5
+ //
6
+ // const agent = createAgent({
7
+ // model: 'openai:gpt-5',
8
+ // systemPrompt: PRACTICE_INSTRUCTIONS,
9
+ // tools: await stuntmanTools({ endpoint: process.env.STUNTMAN_ENDPOINT }),
10
+ // });
11
+ //
12
+ // The tools are standard LangChain tools, so they also work in LangGraph's
13
+ // ToolNode and any agent that takes LangChain tools. Every transaction is
14
+ // practiced on Robinhood Chain through a Stuntman endpoint and never broadcast.
15
+ import { loadPeer } from './peer.js';
16
+ import { practiceTools, PRACTICE_INSTRUCTIONS } from './practice.js';
17
+ export { PRACTICE_INSTRUCTIONS };
18
+ /** Stuntman practice tools for LangChain and LangGraph agents. */
19
+ export async function stuntmanTools(options = {}) {
20
+ const endpoint = options.endpoint ?? process.env.STUNTMAN_ENDPOINT ?? 'http://127.0.0.1:8545';
21
+ const { mod, z } = await loadPeer('@langchain/core', '@langchain/core zod', '@langchain/core/tools');
22
+ return practiceTools(endpoint, z).map((t) => mod.tool((input) => t.run(input ?? {}), { name: t.name, description: t.description, schema: t.schema }));
23
+ }
package/dist/openai.js ADDED
@@ -0,0 +1,24 @@
1
+ // Stuntman for the OpenAI Agents SDK.
2
+ //
3
+ // import { Agent, run } from '@openai/agents';
4
+ // import { stuntmanTools, PRACTICE_INSTRUCTIONS } from 'stuntman/openai';
5
+ //
6
+ // const agent = new Agent({
7
+ // name: 'Trader',
8
+ // instructions: `${PRACTICE_INSTRUCTIONS} Trade tokenized stocks on Robinhood Chain.`,
9
+ // tools: await stuntmanTools({ endpoint: process.env.STUNTMAN_ENDPOINT }),
10
+ // });
11
+ //
12
+ // The tools practice transactions on Robinhood Chain through a Stuntman
13
+ // endpoint: simulated at the latest block with practice money, never
14
+ // broadcast. With a witness endpoint, every take is kept on the agent's
15
+ // public record.
16
+ import { loadPeer } from './peer.js';
17
+ import { practiceTools, PRACTICE_INSTRUCTIONS } from './practice.js';
18
+ export { PRACTICE_INSTRUCTIONS };
19
+ /** Stuntman practice tools for an OpenAI Agents SDK agent. */
20
+ export async function stuntmanTools(options = {}) {
21
+ const endpoint = options.endpoint ?? process.env.STUNTMAN_ENDPOINT ?? 'http://127.0.0.1:8545';
22
+ const { mod, z } = await loadPeer('@openai/agents', '@openai/agents zod');
23
+ return practiceTools(endpoint, z).map((t) => mod.tool({ name: t.name, description: t.description, parameters: t.schema, execute: (input) => t.run(input ?? {}) }));
24
+ }
package/dist/peer.js ADDED
@@ -0,0 +1,23 @@
1
+ // Loading an agent framework the user installed, plus the zod copy it uses,
2
+ // so tool schemas are built with the same zod the framework reads them with.
3
+ import { createRequire } from 'node:module';
4
+ import * as ownZod from 'zod';
5
+ const requireHere = createRequire(import.meta.url);
6
+ export async function loadPeer(pkg, install, entry = pkg) {
7
+ let path;
8
+ try {
9
+ path = requireHere.resolve(entry);
10
+ }
11
+ catch {
12
+ throw new Error(`This needs ${pkg}. Install it with: npm install ${install}`);
13
+ }
14
+ const mod = (await import(entry));
15
+ let z;
16
+ try {
17
+ z = createRequire(path)('zod');
18
+ }
19
+ catch {
20
+ z = ownZod;
21
+ }
22
+ return { mod, z };
23
+ }
package/dist/practice.js CHANGED
@@ -85,3 +85,58 @@ export function practiceActions(endpoint) {
85
85
  },
86
86
  };
87
87
  }
88
+ /** What an agent should know while practicing, for its system prompt. */
89
+ export const PRACTICE_INSTRUCTIONS = 'You are in practice mode on Robinhood Chain through Stuntman. Every transaction you send is simulated at the latest block with practice money and never broadcast. Practice a trade before making it for real, and read the result before deciding.';
90
+ /** The practice functions as framework-neutral tools: name, description, input schema and a runner that always returns text. */
91
+ export function practiceTools(endpoint, z) {
92
+ const a = practiceActions(endpoint);
93
+ const text = (out) => (typeof out === 'string' ? out : out.ok ? out.text : `Failed: ${out.text}`);
94
+ const safe = (fn) => async (args) => {
95
+ try {
96
+ return text(await fn(args ?? {}));
97
+ }
98
+ catch (err) {
99
+ return `Failed: ${err.message}`;
100
+ }
101
+ };
102
+ const str = (v) => (v === null || v === undefined || v === '' ? undefined : String(v));
103
+ return [
104
+ {
105
+ name: 'stuntman_practice_status',
106
+ description: 'Show the practice account on Robinhood Chain, recent practice results, and whether takes are witnessed on a public record. Every transaction sent through Stuntman is practice: simulated, never broadcast.',
107
+ schema: z.object({}),
108
+ run: safe(() => a.status()),
109
+ },
110
+ {
111
+ name: 'stuntman_practice_balances',
112
+ description: 'Practice balances of ETH and tokens on Robinhood Chain. These are practice money, not real funds.',
113
+ schema: z.object({}),
114
+ run: safe(() => a.balances()),
115
+ },
116
+ {
117
+ name: 'stuntman_practice_takes',
118
+ description: 'Recent practice takes, newest first, with results and the reason for any failure.',
119
+ schema: z.object({ limit: z.number().int().min(1).max(50).optional().describe('How many takes, up to 50. Default 10.') }),
120
+ run: safe((args) => a.takes(Number(args.limit ?? 10))),
121
+ },
122
+ {
123
+ name: 'stuntman_send_practice_transaction',
124
+ description: 'Send any transaction in practice: simulated at the latest block of Robinhood Chain with practice money, never broadcast. Returns whether it filled and what changed.',
125
+ schema: z.object({
126
+ to: z.string().optional().describe('Contract or wallet address. Leave out to deploy a contract.'),
127
+ data: z.string().optional().describe('Calldata as 0x hex. Leave out for a plain ETH send.'),
128
+ value: z.string().optional().describe('ETH to send, in wei as a whole number.'),
129
+ }),
130
+ run: safe((args) => a.send(str(args.to), str(args.data), str(args.value))),
131
+ },
132
+ {
133
+ name: 'stuntman_add_practice_money',
134
+ description: 'Add practice money on a witness endpoint. It shows on the public record.',
135
+ schema: z.object({
136
+ asset: z.string().describe('ETH or a token address'),
137
+ amount: z.string().describe('Amount in whole units, for example 1 or 250.5'),
138
+ }),
139
+ run: safe((args) => a.fund(str(args.asset), str(args.amount))),
140
+ },
141
+ ];
142
+ }
package/dist/proxy.js CHANGED
@@ -12,6 +12,8 @@ import { readState, readTakes, findTakeByHash } from './store.js';
12
12
  import { runTake, balances, TakeRejected } from './engine.js';
13
13
  import { describeCapabilities } from './caps.js';
14
14
  import { handleXochi } from './xochi.js';
15
+ import { handleAttesta, localAttestaContext } from './attesta.js';
16
+ import { renderLocalTakes } from './record-page.js';
15
17
  const BLOCKED_SEND_PATTERN = /^(eth|personal|wallet|debug|admin|miner|engine|flashbots|mev)_(send|submit|sign)/i;
16
18
  const LATEST_TAGS = new Set(['latest', 'pending', 'safe', 'finalized', undefined]);
17
19
  const ZERO_BLOOM = (`0x${'0'.repeat(512)}`);
@@ -362,6 +364,33 @@ function serveXochi(engine, req, res, opts) {
362
364
  }
363
365
  });
364
366
  }
367
+ function serveAttesta(engine, req, res, opts) {
368
+ const chunks = [];
369
+ let size = 0;
370
+ req.on('data', (c) => {
371
+ size += c.length;
372
+ if (size > MAX_BODY) {
373
+ res.writeHead(413).end();
374
+ req.destroy();
375
+ return;
376
+ }
377
+ chunks.push(c);
378
+ });
379
+ req.on('end', async () => {
380
+ const body = chunks.length ? Buffer.concat(chunks).toString('utf8') : undefined;
381
+ const url = new URL(req.url ?? '/', 'http://local');
382
+ try {
383
+ const out = await handleAttesta(localAttestaContext(engine), req.method ?? 'GET', url.pathname.replace(/^\/attesta/, ''), url.search, req.headers, req.method === 'GET' ? undefined : body);
384
+ res.writeHead(out.status, { 'content-type': 'application/json' });
385
+ res.end(JSON.stringify(out.body));
386
+ }
387
+ catch (err) {
388
+ opts.onError?.(`attesta: ${err.message}`);
389
+ res.writeHead(500, { 'content-type': 'application/json' });
390
+ res.end(JSON.stringify({ error: { code: 'internal', message: err.message } }));
391
+ }
392
+ });
393
+ }
365
394
  export function startProxy(engine, opts) {
366
395
  const server = http.createServer((req, res) => {
367
396
  // Only local pages may talk to the practice RPC. A random website open in
@@ -378,7 +407,7 @@ export function startProxy(engine, opts) {
378
407
  if (origin) {
379
408
  res.setHeader('access-control-allow-origin', origin);
380
409
  res.setHeader('vary', 'origin');
381
- res.setHeader('access-control-allow-headers', 'content-type, authorization, x-xochi-delegation, x-xochi-read-token');
410
+ res.setHeader('access-control-allow-headers', 'content-type, authorization, idempotency-key, x-xochi-delegation, x-xochi-read-token');
382
411
  res.setHeader('access-control-allow-methods', 'POST, GET, OPTIONS');
383
412
  }
384
413
  if (req.method === 'OPTIONS') {
@@ -389,6 +418,17 @@ export function startProxy(engine, opts) {
389
418
  serveXochi(engine, req, res, opts);
390
419
  return;
391
420
  }
421
+ if ((req.url ?? '').startsWith('/attesta/')) {
422
+ serveAttesta(engine, req, res, opts);
423
+ return;
424
+ }
425
+ const takePage = (req.url ?? '').match(/^\/takes(?:\/(\d+))?\/?(?:\?.*)?$/);
426
+ if (req.method === 'GET' && takePage) {
427
+ const page = renderLocalTakes(checksum(engine.cfg.account), readTakes(), takePage[1] ? Number(takePage[1]) : undefined);
428
+ res.writeHead(page.status, { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'" });
429
+ res.end(page.html);
430
+ return;
431
+ }
392
432
  if (req.method === 'GET') {
393
433
  res.writeHead(200, { 'content-type': 'application/json' });
394
434
  res.end(JSON.stringify({ name: 'stuntman', practicing: true, account: checksum(engine.cfg.account), chainId: engine.cfg.chainId }));