stuntman 0.1.2 → 0.2.0

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 CHANGED
@@ -93,6 +93,18 @@ npx stuntman fund ETH 2
93
93
  npx stuntman fund 0xTokenAddress 500
94
94
  ```
95
95
 
96
+ ## Witnessed practice
97
+
98
+ Practice on your own machine is private, so nobody else can trust it. `stuntman witness` moves your agent's takes to Stuntman's server: each one is simulated at the latest block, signed by the witness and added to a public record at `stuntmanhq.xyz/a/<address>`. Takes are only ever added, never removed.
99
+
100
+ ```bash
101
+ stuntman witness # sign up the practice account; the MCP tools switch over
102
+ stuntman fund ETH 1 # practice money on the witness, listed on the record
103
+ stuntman witness off # back to practicing locally
104
+ ```
105
+
106
+ Agents that send their own transactions use the printed endpoint as their RPC address. Each agent's first 25 witnessed takes are free; after that each take is paid in the Stuntman token from prepaid credit, part burned and part to the treasury. See [stuntmanhq.xyz/economics](https://stuntmanhq.xyz/economics). The token is $STUNT on Robinhood Chain: `0xfadcdbb63b0326a772e18c5955028f2c23e81651`. The credits contract is in `contracts/StuntmanCredits.sol`.
107
+
96
108
  ## Commands
97
109
 
98
110
  ```
@@ -105,6 +117,7 @@ stuntman take <id> [--json]
105
117
  stuntman balances [token ...]
106
118
  stuntman fund ETH <amount> | <token> <amount>
107
119
  stuntman status Account, simulation mode, go-live checklist
120
+ stuntman witness [off] Witnessed practice on Stuntman's server
108
121
  stuntman reset --yes
109
122
  stuntman doctor What your RPC supports
110
123
  ```
@@ -152,7 +165,7 @@ npm test # builds, starts a local chain, runs every backend end to end
152
165
 
153
166
  `npm run build:executor` recompiles `contracts/StuntmanExecutor.sol`.
154
167
 
155
- The website lives in `site/`: static files with no build step. Deploy it on Vercel with `site` as the root directory.
168
+ The website lives in `site/` (static files) and the witness API in `api/`. Vercel builds both from the repository root using `vercel.json`.
156
169
 
157
170
  ## License
158
171
 
package/dist/cli.js CHANGED
@@ -13,6 +13,7 @@ import { formatTake, readiness } from './report.js';
13
13
  import { startProxy } from './proxy.js';
14
14
  import { runMcp } from './mcp.js';
15
15
  import { VERSION } from './version.js';
16
+ import { registerWitness, remoteCall, remoteTakes, witnessBase } from './remote.js';
16
17
  function parseArgs(argv) {
17
18
  const args = [];
18
19
  const flags = {};
@@ -63,6 +64,11 @@ Watch the takes
63
64
  stuntman balances [token ...] Practice balances
64
65
  stuntman status Account, simulation mode and go-live checklist
65
66
 
67
+ Witnessed practice
68
+ stuntman witness Practice on Stuntman's server: every take signed and kept
69
+ on a public record. The MCP tools switch over to it.
70
+ stuntman witness off Go back to practicing on this machine only
71
+
66
72
  Practice money
67
73
  stuntman fund ETH <amount>
68
74
  stuntman fund <token address> <amount>
@@ -167,9 +173,10 @@ async function cmdInit(flags) {
167
173
  async function cmdStatus() {
168
174
  const cfg = requireConfig();
169
175
  const engine = await createEngine(cfg);
170
- const state = readState(cfg.chainId, cfg.account);
171
- const r = readiness(readTakes());
176
+ const r = readiness(await allTakes(cfg));
172
177
  out(`Practicing as ${checksum(cfg.account)} on chain ${cfg.chainId}`);
178
+ if (cfg.witness)
179
+ out(`Witnessed: every take is simulated and signed by Stuntman. Record: ${witnessBase()}/a/${checksum(cfg.account)}`);
173
180
  out(`Simulation: ${describeCapabilities(engine.caps)}`);
174
181
  out(`Takes: ${r.total} (${r.filled} filled, ${r.bad} bad)`);
175
182
  out('');
@@ -181,15 +188,19 @@ async function cmdStatus() {
181
188
  out('To go live, swap the Stuntman wallet tool (or RPC address) back for your real one.');
182
189
  out('Your agent then does its own stunts.');
183
190
  }
184
- if (state.takeCount === 0) {
191
+ if (r.total === 0) {
185
192
  out('');
186
193
  out('No takes yet. Connect your agent with "npx stuntman connect" and let it trade.');
187
194
  }
188
195
  }
196
+ /** Takes oldest first, from the witness when witness mode is on. */
197
+ async function allTakes(cfg, limit = 500) {
198
+ return cfg.witness ? (await remoteTakes(cfg.witness, limit)).reverse() : readTakes();
199
+ }
189
200
  async function cmdTakes(flags) {
190
- requireConfig();
201
+ const cfg = requireConfig();
191
202
  const limit = Math.max(1, Number(flags.limit ?? 20));
192
- const takes = readTakes().slice(-limit).reverse();
203
+ const takes = (await allTakes(cfg, limit)).slice(-limit).reverse();
193
204
  if (flags.json) {
194
205
  out(JSON.stringify(takes, null, 2));
195
206
  return;
@@ -206,15 +217,22 @@ async function cmdTakes(flags) {
206
217
  }
207
218
  }
208
219
  async function cmdTake(args, flags) {
209
- requireConfig();
220
+ const cfg = requireConfig();
210
221
  const id = Number(args[0]);
211
- const take = readTakes().find((t) => t.id === id);
222
+ const take = (await allTakes(cfg)).find((t) => t.id === id);
212
223
  if (!take)
213
224
  throw new Error(`No take ${args[0] ?? ''}. Run "stuntman takes" to see them.`);
214
225
  out(flags.json ? JSON.stringify(take, null, 2) : formatTake(take, true));
215
226
  }
216
227
  async function cmdBalances(args) {
217
228
  const cfg = requireConfig();
229
+ if (cfg.witness) {
230
+ const rows = await remoteCall(cfg.witness, 'stuntman_balances');
231
+ out(`Practice balances for ${checksum(cfg.account)} (witnessed)`);
232
+ for (const r of rows)
233
+ out(` ${r.symbol.padEnd(10)} ${r.formatted.padStart(24)}${r.practice ? '' : ' real (untouched in practice)'}`);
234
+ return;
235
+ }
218
236
  const engine = await createEngine(cfg);
219
237
  const extra = args.filter(isAddr);
220
238
  const rows = await balances(engine, extra);
@@ -233,11 +251,19 @@ async function cmdFund(args) {
233
251
  if (!isEth && !isAddr(asset))
234
252
  throw new Error(`${asset} is not ETH or a token address.`);
235
253
  const decimals = isEth ? 18 : (await readTokenInfo(engine.rpc, asset)).decimals;
254
+ if (cfg.witness) {
255
+ const r = await remoteCall(cfg.witness, 'stuntman_fund', [isEth ? 'ETH' : asset, parseUnits(amount, decimals).toString()]);
256
+ out(`Added ${amount} ${r.symbol} on the witness. Practice balance: ${fmt(BigInt(r.balance), r.decimals)} ${r.symbol}.`);
257
+ out('Practice money added on the witness shows on your public record.');
258
+ return;
259
+ }
236
260
  const res = await fund(engine, isEth ? 'ETH' : asset, parseUnits(amount, decimals));
237
261
  out(`Added ${amount} ${res.symbol}. Practice balance: ${fmt(res.balance, res.decimals)} ${res.symbol}.`);
238
262
  }
239
263
  async function cmdReset(flags) {
240
264
  const cfg = requireConfig();
265
+ if (cfg.witness)
266
+ throw new Error('A witnessed record cannot be reset. Run "stuntman witness off" to practice on this machine again; that record is separate.');
241
267
  if (!flags.yes)
242
268
  throw new Error('This clears every practice balance and take. Run again with --yes to confirm.');
243
269
  resetPractice(cfg.chainId, cfg.account);
@@ -274,6 +300,9 @@ async function cmdDoctor() {
274
300
  }
275
301
  async function cmdRpc(flags) {
276
302
  const cfg = requireConfig();
303
+ if (cfg.witness) {
304
+ throw new Error(`Witness mode is on, so takes made through a local RPC would not be witnessed. Point your agent's RPC address at your witness endpoint instead (shown by "stuntman witness"), or run "stuntman witness off".`);
305
+ }
277
306
  const engine = await createEngine(cfg);
278
307
  const port = Number(flags.port ?? process.env.STUNTMAN_PORT ?? DEFAULT_PORT);
279
308
  const host = typeof flags.host === 'string' ? flags.host : '127.0.0.1';
@@ -292,6 +321,36 @@ async function cmdRpc(flags) {
292
321
  err(`Xochi practice gateway on http://${host}:${port}/xochi (quotes from ${xochiUrl()}, executes stay here).`);
293
322
  err('Press Ctrl+C to stop.');
294
323
  }
324
+ async function cmdWitness(args) {
325
+ const cfg = requireConfig();
326
+ if (args[0] === 'off') {
327
+ delete cfg.witness;
328
+ saveConfig(cfg);
329
+ out('Witness mode is off. Takes are simulated on this machine again. Your witnessed record stays online.');
330
+ return;
331
+ }
332
+ const { account, endpoint } = await registerWitness(cfg);
333
+ cfg.witness = endpoint;
334
+ saveConfig(cfg);
335
+ const base = witnessBase();
336
+ const conf = (await fetch(`${base}/api/witness/config`).then((r) => r.json()).catch(() => null));
337
+ out(`Witnessed practice is on for ${account}.`);
338
+ out('');
339
+ out(`Endpoint (keep it private, it is your agent's key to the record):`);
340
+ out(` ${endpoint}`);
341
+ out(`Public record:`);
342
+ out(` ${base}/a/${account}`);
343
+ out('');
344
+ out('The Stuntman MCP tools now send through the witness. Agents that send their own');
345
+ out('transactions: use the endpoint above as the RPC address.');
346
+ out('Practice money on the witness is separate: add some with "stuntman fund ETH 1".');
347
+ if (conf?.freeTakes !== undefined) {
348
+ out('');
349
+ out(conf.billing
350
+ ? `The first ${conf.freeTakes} witnessed takes are free. After that each take costs $${conf.takePriceUsd} in ${conf.symbol ?? 'the Stuntman token'}; top up at ${base}/witness.`
351
+ : `Witnessing is free while billing is off. Once it starts, each agent keeps ${conf.freeTakes} free takes.`);
352
+ }
353
+ }
295
354
  async function cmdMcp() {
296
355
  const cfg = requireConfig();
297
356
  const engine = await createEngine(cfg);
@@ -332,6 +391,8 @@ async function main() {
332
391
  return cmdMcp();
333
392
  case 'connect':
334
393
  return out(connectLines(args[0] ?? 'all'));
394
+ case 'witness':
395
+ return cmdWitness(args);
335
396
  default:
336
397
  throw new Error(`Unknown command "${cmd}". Run "stuntman help".`);
337
398
  }
@@ -0,0 +1,4 @@
1
+ // Generated by scripts/build-credits.mjs from contracts/StuntmanCredits.sol. Do not edit.
2
+ // Compiled with solc 0.8.39+commit.ce47f2c8.Emscripten.clang, optimizer on (200 runs), evmVersion paris.
3
+ export const CREDITS_ABI = [{ "inputs": [{ "internalType": "address", "name": "token_", "type": "address" }, { "internalType": "address", "name": "owner_", "type": "address" }, { "internalType": "address", "name": "treasury_", "type": "address" }, { "internalType": "address", "name": "operator_", "type": "address" }, { "internalType": "uint16", "name": "burnBps_", "type": "uint16" }], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "BadShare", "type": "error" }, { "inputs": [], "name": "LengthMismatch", "type": "error" }, { "inputs": [], "name": "NotOperator", "type": "error" }, { "inputs": [], "name": "NotOwner", "type": "error" }, { "inputs": [], "name": "NothingToWithdraw", "type": "error" }, { "inputs": [{ "internalType": "uint256", "name": "availableAt", "type": "uint256" }], "name": "TooEarly", "type": "error" }, { "inputs": [], "name": "TransferFailed", "type": "error" }, { "inputs": [], "name": "ZeroAddress", "type": "error" }, { "anonymous": false, "inputs": [{ "indexed": false, "internalType": "uint16", "name": "burnBps", "type": "uint16" }], "name": "BurnShareChanged", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": true, "internalType": "uint256", "name": "settlement", "type": "uint256" }, { "indexed": true, "internalType": "address", "name": "account", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "Charged", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": true, "internalType": "address", "name": "account", "type": "address" }, { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "Deposited", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": false, "internalType": "address", "name": "operator", "type": "address" }], "name": "OperatorChanged", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": false, "internalType": "address", "name": "owner", "type": "address" }], "name": "OwnerChanged", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": true, "internalType": "uint256", "name": "settlement", "type": "uint256" }, { "indexed": false, "internalType": "bytes32", "name": "root", "type": "bytes32" }, { "indexed": false, "internalType": "uint256", "name": "takes", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "charged", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "burned", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "toTreasury", "type": "uint256" }], "name": "Settled", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": false, "internalType": "address", "name": "treasury", "type": "address" }], "name": "TreasuryChanged", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": true, "internalType": "address", "name": "account", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "availableAt", "type": "uint256" }], "name": "WithdrawRequested", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": true, "internalType": "address", "name": "account", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "Withdrawn", "type": "event" }, { "inputs": [], "name": "BURN", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "MAX_BPS", "outputs": [{ "internalType": "uint16", "name": "", "type": "uint16" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "WITHDRAW_DELAY", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "burnBps", "outputs": [{ "internalType": "uint16", "name": "", "type": "uint16" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "", "type": "address" }], "name": "credits", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "deposit", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "lastRoot", "outputs": [{ "internalType": "bytes32", "name": "", "type": "bytes32" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "operator", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "requestWithdraw", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "uint16", "name": "burnBps_", "type": "uint16" }], "name": "setBurnShare", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "operator_", "type": "address" }], "name": "setOperator", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "treasury_", "type": "address" }], "name": "setTreasury", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "bytes32", "name": "root", "type": "bytes32" }, { "internalType": "uint256", "name": "takes", "type": "uint256" }, { "internalType": "address[]", "name": "accounts", "type": "address[]" }, { "internalType": "uint256[]", "name": "amounts", "type": "uint256[]" }], "name": "settle", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "settlements", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "token", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalBurned", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalCharged", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalTakes", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalToTreasury", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "owner_", "type": "address" }], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "treasury", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "withdraw", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "", "type": "address" }], "name": "withdrawAmount", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "", "type": "address" }], "name": "withdrawAt", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }];
4
+ export const CREDITS_BYTECODE = '0x60a060405234801561001057600080fd5b5060405161136838038061136883398101604081905261002f91610215565b6001600160a01b038516158061004c57506001600160a01b038416155b8061005e57506001600160a01b038316155b8061007057506001600160a01b038216155b1561008e5760405163d92e233d60e01b815260040160405180910390fd5b61271061ffff821611156100b5576040516311c56c8960e01b815260040160405180910390fd5b6001600160a01b03858116608052600080546001600160a01b03199081168784169081179092556002805460018054909316878616179092559286166001600160b01b031990911617600160a01b61ffff851602179091556040519081527fa2ea9883a321a3e97b8266c2b078bfeec6d50c711ed71f874a90d500ae2eaf369060200160405180910390a16040516001600160a01b03831681527f4721129e0e676ed6a92909bb24e853ccdd63ad72280cc2e974e38e480e0e6e549060200160405180910390a16040516001600160a01b03841681527fc714d22a2f08b695f81e7c707058db484aa5b4d6b4c9fd64beb10fe85832f6089060200160405180910390a160405161ffff821681527fe955937e62509fdebf0600fcf6a767397f1dd2bd02efdcc41253e35314fe839d9060200160405180910390a15050505050610285565b80516001600160a01b038116811461021057600080fd5b919050565b600080600080600060a0868803121561022d57600080fd5b610236866101f9565b9450610244602087016101f9565b9350610252604087016101f9565b9250610260606087016101f9565b9150608086015161ffff8116811461027757600080fd5b809150509295509295909350565b6080516110ba6102ae6000396000818161032101528181610c2a0152610d3801526110ba6000f3fe608060405234801561001057600080fd5b50600436106101735760003560e01c8063b3ab15fb116100de578063d89135cd11610097578063f2fde38b11610071578063f2fde38b14610309578063fc0c546a1461031c578063fd967f4714610343578063fe5ff4681461034c57600080fd5b8063d89135cd146102e4578063e4fcee29146102ed578063f0f44260146102f657600080fd5b8063b3ab15fb1461029a578063b58166f2146102ad578063c0a2526c146102b6578063c1b57edb146102bf578063ce459a29146102c8578063d3be603b146102db57600080fd5b8063570ca73511610130578063570ca7351461020d57806361d027b314610238578063745400c91461024b57806375cbda241461025e5780638da5cb5b1461027e578063a6f55d771461029157600080fd5b80630d5e5fff146101785780633ccfd60b1461019557806347e7ef241461019f5780634f420151146101b257806352153dfb146101d257806353deb3d6146101e5575b600080fd5b6101826202a30081565b6040519081526020015b60405180910390f35b61019d61036c565b005b61019d6101ad366004610e13565b6104e1565b6101826101c0366004610e3d565b60046020526000908152604090205481565b61019d6101e0366004610eab565b6105ca565b6002546101fa90600160a01b900461ffff1681565b60405161ffff909116815260200161018c565b600154610220906001600160a01b031681565b6040516001600160a01b03909116815260200161018c565b600254610220906001600160a01b031681565b61019d610259366004610f33565b61090d565b61018261026c366004610e3d565b60056020526000908152604090205481565b600054610220906001600160a01b031681565b61018260085481565b61019d6102a8366004610e3d565b61099c565b610182600b5481565b61022061dead81565b610182600a5481565b61019d6102d6366004610f4c565b610a43565b61018260065481565b61018260095481565b61018260075481565b61019d610304366004610e3d565b610ae5565b61019d610317366004610e3d565b610b85565b6102207f000000000000000000000000000000000000000000000000000000000000000081565b6101fa61271081565b61018261035a366004610e3d565b60036020526000908152604090205481565b336000908152600460205260408120549081900361039d57604051630686827b60e51b815260040160405180910390fd5b33600090815260056020526040902054428111156103d557604051630a8d68c960e21b81526004810182905260240160405180910390fd5b33600090815260036020526040812054908184106103f357816103f5565b835b3360009081526004602090815260408083208390556005909152812081905590915081900361043757604051630686827b60e51b815260040160405180910390fd5b6104418183610f86565b33600081815260036020526040908190209290925590516024810191909152604481018290526104a69063a9059cbb906064015b6040516020818303038152906040529060e01b6020820180516001600160e01b038381831617835250505050610c25565b60405181815233907f7084f5476618d8e60b11ef0d7d3f06914655adb8793e28ff7f018d4c76d505d59060200160405180910390a250505050565b6001600160a01b0382166105085760405163d92e233d60e01b815260040160405180910390fd5b6000610512610cf4565b6040513360248201523060448201526064810184905290915061053d906323b872dd90608401610475565b600081610548610cf4565b6105529190610f86565b6001600160a01b03851660009081526003602052604081208054929350839290919061057f908490610f9f565b909155505060405181815233906001600160a01b038616907f8752a472e571a816aea92eec8dae9baf628e840f4929fbcc2d155e6233ff68a79060200160405180910390a350505050565b6001546001600160a01b031633146105f557604051631f0853c160e21b815260040160405180910390fd5b828114610618576040516001621398b960e31b0319815260040160405180910390fd5b600060066000815461062990610fb2565b918290555090506000805b858110156107ae5760006003600089898581811061065457610654610fcb565b90506020020160208101906106699190610e3d565b6001600160a01b03166001600160a01b031681526020019081526020016000205490506000818787858181106106a1576106a1610fcb565b90506020020135106106b357816106cd565b8686848181106106c5576106c5610fcb565b905060200201355b9050806000036106de5750506107a6565b6106e88183610f86565b600360008b8b878181106106fe576106fe610fcb565b90506020020160208101906107139190610e3d565b6001600160a01b031681526020810191909152604001600020556107378185610f9f565b935088888481811061074b5761074b610fcb565b90506020020160208101906107609190610e3d565b6001600160a01b0316857f40860d6197dabef1dcfdd4f0d5a0833e741eb44abc0fc815485f24b3dddf7d6b8360405161079b91815260200190565b60405180910390a350505b600101610634565b50600254600090612710906107ce90600160a01b900461ffff1684610fe1565b6107d89190610ff8565b905060006107e68284610f86565b905081156108125760405161dead6024820152604481018390526108129063a9059cbb90606401610475565b8015610847576002546040516001600160a01b039091166024820152604481018290526108479063a9059cbb90606401610475565b89600b8190555088600760008282546108609190610f9f565b9250508190555082600860008282546108799190610f9f565b9250508190555081600960008282546108929190610f9f565b9250508190555080600a60008282546108ab9190610f9f565b9091555050604080518b8152602081018b9052908101849052606081018390526080810182905284907faee91e9c15012f01da6d452913dc294269e1af2c8bb74f16d7a89f44286b3ff49060a00160405180910390a250505050505050505050565b8060000361092e57604051630686827b60e51b815260040160405180910390fd5b600061093d6202a30042610f9f565b3360008181526004602090815260408083208790556005825291829020849055815186815290810184905292935090917fd72eb5d043f24a0168ae744d5c44f9596fd673a26bf74d9646bff4b844882d14910160405180910390a25050565b6000546001600160a01b031633146109c7576040516330cd747160e01b815260040160405180910390fd5b6001600160a01b0381166109ee5760405163d92e233d60e01b815260040160405180910390fd5b600180546001600160a01b0319166001600160a01b0383169081179091556040519081527f4721129e0e676ed6a92909bb24e853ccdd63ad72280cc2e974e38e480e0e6e54906020015b60405180910390a150565b6000546001600160a01b03163314610a6e576040516330cd747160e01b815260040160405180910390fd5b61271061ffff82161115610a95576040516311c56c8960e01b815260040160405180910390fd5b6002805461ffff60a01b1916600160a01b61ffff8416908102919091179091556040519081527fe955937e62509fdebf0600fcf6a767397f1dd2bd02efdcc41253e35314fe839d90602001610a38565b6000546001600160a01b03163314610b10576040516330cd747160e01b815260040160405180910390fd5b6001600160a01b038116610b375760405163d92e233d60e01b815260040160405180910390fd5b600280546001600160a01b0319166001600160a01b0383169081179091556040519081527fc714d22a2f08b695f81e7c707058db484aa5b4d6b4c9fd64beb10fe85832f60890602001610a38565b6000546001600160a01b03163314610bb0576040516330cd747160e01b815260040160405180910390fd5b6001600160a01b038116610bd75760405163d92e233d60e01b815260040160405180910390fd5b600080546001600160a01b0319166001600160a01b0383169081179091556040519081527fa2ea9883a321a3e97b8266c2b078bfeec6d50c711ed71f874a90d500ae2eaf3690602001610a38565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031683604051610c60919061101a565b6000604051808303816000865af19150503d8060008114610c9d576040519150601f19603f3d011682016040523d82523d6000602084013e610ca2565b606091505b5091509150811580610cd1575060008151118015610cd1575080806020019051810190610ccf9190611049565b155b15610cef576040516312171d8360e31b815260040160405180910390fd5b505050565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1790529051600091829182917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691610d6b919061101a565b600060405180830381855afa9150503d8060008114610da6576040519150601f19603f3d011682016040523d82523d6000602084013e610dab565b606091505b5091509150811580610dbe575060208151105b15610ddc576040516312171d8360e31b815260040160405180910390fd5b80806020019051810190610df0919061106b565b9250505090565b80356001600160a01b0381168114610e0e57600080fd5b919050565b60008060408385031215610e2657600080fd5b610e2f83610df7565b946020939093013593505050565b600060208284031215610e4f57600080fd5b610e5882610df7565b9392505050565b60008083601f840112610e7157600080fd5b50813567ffffffffffffffff811115610e8957600080fd5b6020830191508360208260051b8501011115610ea457600080fd5b9250929050565b60008060008060008060808789031215610ec457600080fd5b8635955060208701359450604087013567ffffffffffffffff811115610ee957600080fd5b610ef589828a01610e5f565b909550935050606087013567ffffffffffffffff811115610f1557600080fd5b610f2189828a01610e5f565b979a9699509497509295939492505050565b600060208284031215610f4557600080fd5b5035919050565b600060208284031215610f5e57600080fd5b813561ffff81168114610e5857600080fd5b634e487b7160e01b600052601160045260246000fd5b81810381811115610f9957610f99610f70565b92915050565b80820180821115610f9957610f99610f70565b600060018201610fc457610fc4610f70565b5060010190565b634e487b7160e01b600052603260045260246000fd5b8082028115828204841417610f9957610f99610f70565b60008261101557634e487b7160e01b600052601260045260246000fd5b500490565b6000825160005b8181101561103b5760208186018101518583015201611021565b506000920191825250919050565b60006020828403121561105b57600080fd5b81518015158114610e5857600080fd5b60006020828403121561107d57600080fd5b505191905056fea26469706673582212208a7113491b5aa91aee0ca50d9f28b1df0c45cd80a419a84c698ef64bfaab4bb464736f6c63430008270033';
package/dist/kv.js ADDED
@@ -0,0 +1,153 @@
1
+ // A tiny Redis client for the hosted witness: Upstash's REST API in
2
+ // production, an in-memory stand-in for tests. Only the commands the witness
3
+ // uses are supported.
4
+ /** Upstash Redis over REST. Reads the env vars Vercel's Upstash integration sets. */
5
+ export function upstashFromEnv(env = process.env) {
6
+ const url = env.KV_REST_API_URL ?? env.UPSTASH_REDIS_REST_URL;
7
+ const token = env.KV_REST_API_TOKEN ?? env.UPSTASH_REDIS_REST_TOKEN;
8
+ if (!url || !token)
9
+ return null;
10
+ const post = async (path, body) => {
11
+ const res = await fetch(url.replace(/\/$/, '') + path, {
12
+ method: 'POST',
13
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
14
+ body: JSON.stringify(body),
15
+ });
16
+ if (!res.ok)
17
+ throw new Error(`database: HTTP ${res.status}`);
18
+ return res.json();
19
+ };
20
+ return {
21
+ async cmd(...args) {
22
+ const out = (await post('', args.map(String)));
23
+ if (out.error)
24
+ throw new Error(`database: ${out.error}`);
25
+ return out.result;
26
+ },
27
+ async pipeline(cmds) {
28
+ if (!cmds.length)
29
+ return [];
30
+ const out = (await post('/pipeline', cmds.map((c) => c.map(String))));
31
+ return out.map((r) => {
32
+ if (r.error)
33
+ throw new Error(`database: ${r.error}`);
34
+ return r.result;
35
+ });
36
+ },
37
+ };
38
+ }
39
+ /** In-memory stand-in with Redis semantics, for tests and local runs. */
40
+ export function memoryKV() {
41
+ const strings = new Map();
42
+ const hashes = new Map();
43
+ const lists = new Map();
44
+ const sets = new Map();
45
+ const live = (k) => {
46
+ const e = strings.get(k);
47
+ if (e?.exp !== undefined && Date.now() > e.exp) {
48
+ strings.delete(k);
49
+ return undefined;
50
+ }
51
+ return e;
52
+ };
53
+ const hash = (k) => hashes.get(k) ?? (hashes.set(k, new Map()), hashes.get(k));
54
+ const list = (k) => lists.get(k) ?? (lists.set(k, []), lists.get(k));
55
+ const set = (k) => sets.get(k) ?? (sets.set(k, new Set()), sets.get(k));
56
+ const range = (len, a, b) => {
57
+ const s = a < 0 ? Math.max(len + a, 0) : a;
58
+ const e = b < 0 ? len + b : Math.min(b, len - 1);
59
+ return [s, e];
60
+ };
61
+ const run = (args) => {
62
+ const [name, ...rest] = args.map(String);
63
+ const k = rest[0];
64
+ switch (name.toUpperCase()) {
65
+ case 'GET':
66
+ return live(k)?.v ?? null;
67
+ case 'SET': {
68
+ const opts = rest.slice(2).map((o) => o.toUpperCase());
69
+ if (opts.includes('NX') && live(k))
70
+ return null;
71
+ const px = opts.indexOf('PX');
72
+ const ex = opts.indexOf('EX');
73
+ const exp = px >= 0 ? Date.now() + Number(rest[2 + px + 1]) : ex >= 0 ? Date.now() + 1000 * Number(rest[2 + ex + 1]) : undefined;
74
+ strings.set(k, { v: rest[1], exp });
75
+ return 'OK';
76
+ }
77
+ case 'DEL': {
78
+ let n = 0;
79
+ for (const key of rest)
80
+ n += [strings, hashes, lists, sets].some((m) => m.delete(key)) ? 1 : 0;
81
+ return n;
82
+ }
83
+ case 'INCRBY': {
84
+ const v = BigInt(live(k)?.v ?? '0') + BigInt(rest[1]);
85
+ strings.set(k, { v: v.toString() });
86
+ return Number(v);
87
+ }
88
+ case 'HINCRBY': {
89
+ const h = hash(k);
90
+ const v = BigInt(h.get(rest[1]) ?? '0') + BigInt(rest[2]);
91
+ h.set(rest[1], v.toString());
92
+ return Number(v);
93
+ }
94
+ case 'HSET': {
95
+ const h = hash(k);
96
+ for (let i = 1; i < rest.length; i += 2)
97
+ h.set(rest[i], rest[i + 1]);
98
+ return (rest.length - 1) / 2;
99
+ }
100
+ case 'HGET':
101
+ return hashes.get(k)?.get(rest[1]) ?? null;
102
+ case 'HGETALL':
103
+ return [...(hashes.get(k) ?? new Map()).entries()].flat();
104
+ case 'RPUSH':
105
+ list(k).push(...rest.slice(1));
106
+ return list(k).length;
107
+ case 'LLEN':
108
+ return lists.get(k)?.length ?? 0;
109
+ case 'LRANGE': {
110
+ const l = lists.get(k) ?? [];
111
+ const [s, e] = range(l.length, Number(rest[1]), Number(rest[2]));
112
+ return l.slice(s, e + 1);
113
+ }
114
+ case 'LTRIM': {
115
+ const l = lists.get(k) ?? [];
116
+ const [s, e] = range(l.length, Number(rest[1]), Number(rest[2]));
117
+ lists.set(k, l.slice(s, e + 1));
118
+ return 'OK';
119
+ }
120
+ case 'SADD': {
121
+ const s = set(k);
122
+ let n = 0;
123
+ for (const m of rest.slice(1))
124
+ if (!s.has(m))
125
+ (s.add(m), n++);
126
+ return n;
127
+ }
128
+ case 'SMEMBERS':
129
+ return [...(sets.get(k) ?? [])];
130
+ case 'SCARD':
131
+ return sets.get(k)?.size ?? 0;
132
+ default:
133
+ throw new Error(`memoryKV: ${name} is not supported`);
134
+ }
135
+ };
136
+ return {
137
+ async cmd(...args) {
138
+ return run(args);
139
+ },
140
+ async pipeline(cmds) {
141
+ return cmds.map(run);
142
+ },
143
+ };
144
+ }
145
+ /** Turn an HGETALL reply into an object. */
146
+ export function hashToObject(reply) {
147
+ if (!Array.isArray(reply))
148
+ return reply ?? {};
149
+ const out = {};
150
+ for (let i = 0; i < reply.length; i += 2)
151
+ out[String(reply[i])] = String(reply[i + 1]);
152
+ return out;
153
+ }
package/dist/launch.js ADDED
@@ -0,0 +1,21 @@
1
+ export const LAUNCH = {
2
+ /** $STUNT */
3
+ token: '0xfadcdbb63b0326a772e18c5955028f2c23e81651',
4
+ /** StuntmanCredits on Robinhood Chain */
5
+ credits: '0xA9846E958f65D2A0f9Cc69A27650c793a5E9A529',
6
+ freeTakes: 25,
7
+ takePriceUsd: 0.01,
8
+ fallbackTakePriceTokens: '10',
9
+ burnBps: 5000,
10
+ };
11
+ const addr = (v) => (v && /^0x[0-9a-fA-F]{40}$/.test(v) ? v : null);
12
+ /** Launch settings with any environment overrides applied. */
13
+ export function launchSettings(env = process.env) {
14
+ return {
15
+ ...LAUNCH,
16
+ token: addr(env.STUNTMAN_TOKEN) ?? LAUNCH.token,
17
+ credits: addr(env.STUNTMAN_CREDITS) ?? LAUNCH.credits,
18
+ freeTakes: env.STUNTMAN_FREE_TAKES !== undefined ? Number(env.STUNTMAN_FREE_TAKES) : LAUNCH.freeTakes,
19
+ takePriceUsd: env.STUNTMAN_TAKE_PRICE_USD !== undefined ? Number(env.STUNTMAN_TAKE_PRICE_USD) : LAUNCH.takePriceUsd,
20
+ };
21
+ }
package/dist/mcp.js CHANGED
@@ -12,6 +12,7 @@ import { balances, fund, runTake, TakeRejected } from './engine.js';
12
12
  import { describeCapabilities } from './caps.js';
13
13
  import { readiness, formatTake } from './report.js';
14
14
  import { VERSION } from './version.js';
15
+ import { RemoteError, remoteCall, remoteTake, remoteTakes } from './remote.js';
15
16
  function text(value) {
16
17
  return { content: [{ type: 'text', text: value }] };
17
18
  }
@@ -23,6 +24,9 @@ export function buildMcpServer(engine) {
23
24
  instructions: 'Stuntman is a PRACTICE wallet. Every transaction you send here is simulated against the live chain with practice money and is never broadcast. Use it exactly like a real wallet: send the transactions apps give you, then check balances and takes. Tell the user results are from practice.',
24
25
  });
25
26
  const { cfg } = engine;
27
+ // Witness mode: sends, balances and takes live on the agent's witness endpoint.
28
+ const witness = cfg.witness;
29
+ const takesNow = async (limit = 200) => (witness ? (await remoteTakes(witness, limit)).reverse() : readTakes());
26
30
  server.registerTool('wallet_address', {
27
31
  title: 'Practice wallet address',
28
32
  description: 'Returns the address this agent is practicing as and the chain it is on. Use it wherever an app asks for your wallet address.',
@@ -36,6 +40,16 @@ export function buildMcpServer(engine) {
36
40
  annotations: { readOnlyHint: true },
37
41
  }, async ({ tokens }) => {
38
42
  const extra = (tokens ?? []).filter(isAddr);
43
+ if (witness) {
44
+ try {
45
+ const rows = await remoteCall(witness, 'stuntman_balances');
46
+ const lines = rows.map((r) => `${r.symbol.padEnd(10)} ${r.formatted}${r.practice ? '' : ' (real balance, untouched in practice)'}${r.token === 'ETH' ? '' : ` ${r.token}`}`);
47
+ return text(`Practice balances for ${checksum(cfg.account)} (witnessed):\n${lines.join('\n')}`);
48
+ }
49
+ catch (err) {
50
+ return errorText(err.message);
51
+ }
52
+ }
39
53
  const rows = await balances(engine, extra);
40
54
  const lines = rows.map((r) => `${r.symbol.padEnd(10)} ${fmt(r.balance, r.decimals)}${r.practice ? '' : ' (real balance, untouched in practice)'}${r.token === 'ETH' ? '' : ` ${r.token}`}`);
41
55
  return text(`Practice balances for ${checksum(cfg.account)}:\n${lines.join('\n')}`);
@@ -67,6 +81,31 @@ export function buildMcpServer(engine) {
67
81
  catch {
68
82
  return errorText('value and gas must be whole numbers (decimal or 0x hex).');
69
83
  }
84
+ if (witness) {
85
+ try {
86
+ const tx = { from: cfg.account, data: callData, value: `0x${v.toString(16)}` };
87
+ if (!deploying)
88
+ tx.to = to;
89
+ if (g !== undefined)
90
+ tx.gas = `0x${g.toString(16)}`;
91
+ const hash = await remoteCall(witness, 'eth_sendTransaction', [tx]);
92
+ const take = await remoteTake(witness, hash);
93
+ if (!take)
94
+ return text(`Witnessed. Practice transaction hash: ${hash}\nNothing was broadcast.`);
95
+ const where = take.contractAddress ? `\nContract address: ${take.contractAddress}` : '';
96
+ const body = `${formatTake(take)}\n\nPractice transaction hash: ${take.txHash}${where}\nWitnessed by Stuntman. Nothing was broadcast.`;
97
+ return take.status === 'filled' ? text(body) : errorText(body);
98
+ }
99
+ catch (err) {
100
+ if (err instanceof RemoteError && err.code !== -32603) {
101
+ const latest = (await remoteTakes(witness, 1).catch(() => []))[0];
102
+ if (latest?.status === 'rejected' && Date.now() - Date.parse(latest.at) < 15_000) {
103
+ return errorText(`${formatTake(latest)}\n\nNothing was broadcast.`);
104
+ }
105
+ }
106
+ return errorText(`Could not simulate: ${err.message}`);
107
+ }
108
+ }
70
109
  try {
71
110
  const take = await runTake(engine, { from: cfg.account, to: deploying ? null : to, data: callData, value: v, gas: g, source: 'mcp' });
72
111
  const where = take.contractAddress ? `\nContract address: ${take.contractAddress}` : '';
@@ -84,7 +123,7 @@ export function buildMcpServer(engine) {
84
123
  inputSchema: { limit: z.number().int().min(1).max(100).optional() },
85
124
  annotations: { readOnlyHint: true },
86
125
  }, async ({ limit }) => {
87
- const takes = readTakes().slice(-(limit ?? 10)).reverse();
126
+ const takes = (await takesNow(limit ?? 10)).slice(-(limit ?? 10)).reverse();
88
127
  if (!takes.length)
89
128
  return text('No takes yet. Send a transaction to start practicing.');
90
129
  return text(takes.map((t) => `Take ${t.id} ${t.status.padEnd(8)} ${t.summary}`).join('\n'));
@@ -95,7 +134,7 @@ export function buildMcpServer(engine) {
95
134
  inputSchema: { id: z.number().int().min(1) },
96
135
  annotations: { readOnlyHint: true },
97
136
  }, async ({ id }) => {
98
- const take = readTakes().find((t) => t.id === id);
137
+ const take = (await takesNow()).find((t) => t.id === id);
99
138
  return take ? text(formatTake(take, true)) : errorText(`No take ${id}.`);
100
139
  });
101
140
  server.registerTool('fund_practice', {
@@ -119,6 +158,10 @@ export function buildMcpServer(engine) {
119
158
  }
120
159
  }
121
160
  const units = parseUnits(amount, decimals);
161
+ if (witness) {
162
+ const res = await remoteCall(witness, 'stuntman_fund', [isEth ? 'ETH' : asset, units.toString()]);
163
+ return text(`Added ${amount} ${res.symbol}. Practice balance is now ${fmt(BigInt(res.balance), res.decimals)} ${res.symbol}. This shows on the agent's public record.`);
164
+ }
122
165
  const res = await fund(engine, isEth ? 'ETH' : asset, units);
123
166
  return text(`Added ${amount} ${res.symbol}. Practice balance is now ${fmt(res.balance, res.decimals)} ${res.symbol}.`);
124
167
  }
@@ -154,9 +197,10 @@ export function buildMcpServer(engine) {
154
197
  inputSchema: {},
155
198
  annotations: { readOnlyHint: true },
156
199
  }, async () => {
157
- const r = readiness(readTakes());
200
+ const r = readiness(await takesNow().catch(() => []));
158
201
  return text([
159
202
  `Practicing as ${checksum(cfg.account)} (${cfg.mode === 'shadow' ? 'your wallet, watch only' : 'practice key'}) on chain ${cfg.chainId}.`,
203
+ ...(witness ? ['Witnessed: every take is simulated and signed by Stuntman and kept on a public record.'] : []),
160
204
  `Simulation: ${describeCapabilities(engine.caps)}.`,
161
205
  `Takes: ${r.total} (${r.filled} filled, ${r.bad} bad).`,
162
206
  `Ready to go live: ${r.ready ? 'yes' : 'not yet'}.`,
@@ -169,6 +213,8 @@ export function buildMcpServer(engine) {
169
213
  inputSchema: { confirm: z.literal(true).describe('Must be true') },
170
214
  annotations: { destructiveHint: true },
171
215
  }, async () => {
216
+ if (witness)
217
+ return errorText('A witnessed record cannot be reset: every witnessed take stays on the public record. Turn witness mode off with "stuntman witness off" to practice locally.');
172
218
  resetPractice(cfg.chainId, cfg.account);
173
219
  return text(`Practice reset for ${shortAddr(cfg.account)}.`);
174
220
  });
package/dist/remote.js ADDED
@@ -0,0 +1,69 @@
1
+ // Witness mode on the agent's side: the CLI and MCP tools send through the
2
+ // agent's hosted witness endpoint instead of simulating locally.
3
+ import { privateKeyToAccount } from 'viem/accounts';
4
+ export const DEFAULT_WITNESS_URL = 'https://stuntmanhq.xyz';
5
+ export function witnessBase() {
6
+ return (process.env.STUNTMAN_WITNESS_URL || DEFAULT_WITNESS_URL).replace(/\/$/, '');
7
+ }
8
+ export class RemoteError extends Error {
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+ let nextId = 1;
16
+ /** One JSON-RPC call to the witness endpoint. */
17
+ export async function remoteCall(endpoint, method, params = []) {
18
+ let res;
19
+ try {
20
+ res = await fetch(endpoint, {
21
+ method: 'POST',
22
+ headers: { 'content-type': 'application/json' },
23
+ body: JSON.stringify({ jsonrpc: '2.0', id: nextId++, method, params }),
24
+ signal: AbortSignal.timeout(90_000),
25
+ });
26
+ }
27
+ catch (err) {
28
+ throw new RemoteError(-32603, `Could not reach the witness at ${new URL(endpoint).host}: ${err.message}`);
29
+ }
30
+ const body = (await res.json().catch(() => null));
31
+ if (!body)
32
+ throw new RemoteError(-32603, `The witness answered HTTP ${res.status}.`);
33
+ if (body.error)
34
+ throw new RemoteError(body.error.code, body.error.message);
35
+ return body.result;
36
+ }
37
+ export async function remoteTakes(endpoint, limit = 50) {
38
+ return remoteCall(endpoint, 'stuntman_takes', [limit]);
39
+ }
40
+ /** The take a send just made: the newest take with that hash. */
41
+ export async function remoteTake(endpoint, hash) {
42
+ return (await remoteTakes(endpoint, 5)).find((t) => t.txHash.toLowerCase() === hash.toLowerCase());
43
+ }
44
+ /** Register the practice account for witnessed practice. Needs the practice key. */
45
+ export async function registerWitness(cfg) {
46
+ if (!cfg.practiceKey) {
47
+ throw new Error(`Witnessed practice needs an account that can sign. Your account ${cfg.account} is your own wallet, so sign up with it at ${witnessBase()}/witness, or run "stuntman init --new" for a practice key.`);
48
+ }
49
+ const signer = privateKeyToAccount(cfg.practiceKey);
50
+ const issued = new Date().toISOString();
51
+ const message = `Stuntman witness\nAccount: ${signer.address}\nIssued: ${issued}`;
52
+ const signature = await signer.signMessage({ message });
53
+ let res;
54
+ try {
55
+ res = await fetch(`${witnessBase()}/api/witness/register`, {
56
+ method: 'POST',
57
+ headers: { 'content-type': 'application/json' },
58
+ body: JSON.stringify({ account: signer.address, issued, signature }),
59
+ signal: AbortSignal.timeout(30_000),
60
+ });
61
+ }
62
+ catch (err) {
63
+ throw new Error(`Could not reach ${witnessBase()}: ${err.message}`);
64
+ }
65
+ const body = (await res.json().catch(() => ({})));
66
+ if (!res.ok || !body.endpoint)
67
+ throw new Error(body.error ?? `The witness answered HTTP ${res.status}.`);
68
+ return { account: signer.address, endpoint: body.endpoint };
69
+ }
package/dist/store.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // The RPC proxy and the MCP server can run at the same time, so every write goes
3
3
  // through a small cross-process lock and an atomic rename.
4
4
  import { join } from 'node:path';
5
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
6
  import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, statSync, appendFileSync } from 'node:fs';
6
7
  import { ensureHome } from './config.js';
7
8
  /** Bumped when slot search learns new layouts, so earlier misses are tried again. */
@@ -34,8 +35,16 @@ function lockPath() {
34
35
  return join(ensureHome(), 'state.lock');
35
36
  }
36
37
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
38
+ const memory = new AsyncLocalStorage();
39
+ export function withMemoryStore(store, fn) {
40
+ return memory.run(store, fn);
41
+ }
42
+ const clone = (v) => JSON.parse(JSON.stringify(v));
37
43
  /** Run fn while holding the cross-process lock. */
38
44
  export async function withLock(fn) {
45
+ // The hosted witness locks each agent in its database instead.
46
+ if (memory.getStore())
47
+ return fn();
39
48
  const path = lockPath();
40
49
  const started = Date.now();
41
50
  for (;;) {
@@ -68,10 +77,13 @@ export async function withLock(fn) {
68
77
  }
69
78
  }
70
79
  export function readState(chainId, account) {
71
- const path = statePath();
72
- if (!existsSync(path))
80
+ const mem = memory.getStore();
81
+ if (mem && !mem.state)
73
82
  return freshState(chainId, account);
74
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
83
+ const path = mem ? '' : statePath();
84
+ if (!mem && !existsSync(path))
85
+ return freshState(chainId, account);
86
+ const parsed = mem ? clone(mem.state) : JSON.parse(readFileSync(path, 'utf8'));
75
87
  // A state for a different account or chain is stale: start clean.
76
88
  if (parsed.account?.toLowerCase() !== account.toLowerCase() || parsed.chainId !== chainId) {
77
89
  return freshState(chainId, account);
@@ -94,15 +106,29 @@ export function readState(chainId, account) {
94
106
  return parsed;
95
107
  }
96
108
  export function writeState(state) {
109
+ const mem = memory.getStore();
110
+ if (mem) {
111
+ mem.state = clone(state);
112
+ return;
113
+ }
97
114
  const path = statePath();
98
115
  const tmp = `${path}.${process.pid}.tmp`;
99
116
  writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });
100
117
  renameSync(tmp, path);
101
118
  }
102
119
  export function appendTake(take) {
120
+ const mem = memory.getStore();
121
+ if (mem) {
122
+ mem.takes.push(clone(take));
123
+ mem.added.push(clone(take));
124
+ return;
125
+ }
103
126
  appendFileSync(takesPath(), JSON.stringify(take) + '\n', { mode: 0o600 });
104
127
  }
105
128
  export function readTakes() {
129
+ const mem = memory.getStore();
130
+ if (mem)
131
+ return clone(mem.takes);
106
132
  const path = takesPath();
107
133
  if (!existsSync(path))
108
134
  return [];
@@ -122,6 +148,9 @@ export function readTakes() {
122
148
  }
123
149
  export function findTakeByHash(hash) {
124
150
  const lower = hash.toLowerCase();
151
+ const mem = memory.getStore();
152
+ if (mem)
153
+ return mem.takes.find((t) => t.txHash.toLowerCase() === lower) ?? mem.byHash.get(lower);
125
154
  return readTakes().find((t) => t.txHash.toLowerCase() === lower);
126
155
  }
127
156
  export function resetPractice(chainId, account) {
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.1.2';
1
+ export const VERSION = '0.2.0';
@@ -0,0 +1,550 @@
1
+ // Witnessed practice: the hosted side of Stuntman.
2
+ //
3
+ // An agent registers its practice account and gets a private endpoint. Every
4
+ // take sent there is simulated by Stuntman itself, at the latest block, and
5
+ // signed with the witness key, so the agent's record can be trusted by people
6
+ // who never saw its machine. Each agent gets some free takes; after that every
7
+ // simulated take is charged in the Stuntman token from credit held in the
8
+ // StuntmanCredits contract. Once a day the operator settles: it puts the root
9
+ // of every take witnessed since the last settlement on chain and collects the
10
+ // charges, part burned and part to the treasury.
11
+ import { concat, createWalletClient, decodeFunctionResult, defineChain, encodeFunctionData, http, keccak256, parseUnits, toBytes, verifyMessage, } from 'viem';
12
+ import { privateKeyToAccount } from 'viem/accounts';
13
+ import { randomBytes } from 'node:crypto';
14
+ import { DEFAULT_CHAIN_ID, DEFAULT_RPC_URL } from './config.js';
15
+ import { CREDITS_ABI } from './credits.generated.js';
16
+ import { createEngine, fund } from './engine.js';
17
+ import { hashToObject } from './kv.js';
18
+ import { launchSettings } from './launch.js';
19
+ import { handle } from './proxy.js';
20
+ import { RpcClient } from './rpc.js';
21
+ import { withMemoryStore } from './store.js';
22
+ export class WitnessError extends Error {
23
+ status;
24
+ constructor(status, message) {
25
+ super(message);
26
+ this.status = status;
27
+ }
28
+ }
29
+ export function witnessEnvFromProcess(kv, env = process.env) {
30
+ const key = env.STUNTMAN_WITNESS_KEY;
31
+ if (!key || !/^0x[0-9a-fA-F]{64}$/.test(key))
32
+ throw new WitnessError(503, 'Witnessing is not set up on this server yet.');
33
+ return {
34
+ kv,
35
+ witnessKey: key,
36
+ rpcUrl: env.STUNTMAN_RPC_URL || DEFAULT_RPC_URL,
37
+ chainId: Number(env.STUNTMAN_CHAIN_ID || DEFAULT_CHAIN_ID),
38
+ launch: launchSettings(env),
39
+ baseUrl: (env.STUNTMAN_BASE_URL || 'https://stuntmanhq.xyz').replace(/\/$/, ''),
40
+ };
41
+ }
42
+ const lower = (s) => s.toLowerCase();
43
+ const isAddress = (s) => typeof s === 'string' && /^0x[0-9a-fA-F]{40}$/.test(s);
44
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
45
+ export function witnessAddress(env) {
46
+ return privateKeyToAccount(env.witnessKey).address;
47
+ }
48
+ // ---------- registration ----------
49
+ export const REGISTER_WINDOW_MS = 10 * 60 * 1000;
50
+ export function registerMessage(account, issued) {
51
+ return `Stuntman witness\nAccount: ${account}\nIssued: ${issued}`;
52
+ }
53
+ /**
54
+ * Give an account its private witness endpoint. The caller proves it holds the
55
+ * account by signing a short message. Registering again replaces the endpoint.
56
+ */
57
+ export async function register(env, body) {
58
+ const { account, issued, signature } = body ?? {};
59
+ if (!isAddress(account))
60
+ throw new WitnessError(400, 'account must be an address');
61
+ if (typeof issued !== 'string' || Number.isNaN(Date.parse(issued)))
62
+ throw new WitnessError(400, 'issued must be an ISO time');
63
+ if (Math.abs(Date.now() - Date.parse(issued)) > REGISTER_WINDOW_MS)
64
+ throw new WitnessError(400, 'The signed message has expired. Sign a new one.');
65
+ if (typeof signature !== 'string' || !signature.startsWith('0x'))
66
+ throw new WitnessError(400, 'signature is missing');
67
+ const valid = await verifyMessage({ address: account, message: registerMessage(account, issued), signature: signature }).catch(() => false);
68
+ if (!valid)
69
+ throw new WitnessError(401, 'The signature does not match the account.');
70
+ const a = lower(account);
71
+ const secret = randomBytes(24).toString('hex');
72
+ const old = await env.kv.cmd('HGET', `w:agent:${a}`, 'key');
73
+ const now = new Date().toISOString();
74
+ await env.kv.pipeline([
75
+ ...(old ? [['DEL', `w:key:${old}`]] : []),
76
+ ['SET', `w:key:${secret}`, a],
77
+ ['HSET', `w:agent:${a}`, 'account', a, 'key', secret],
78
+ ['SADD', 'w:agents', a],
79
+ ]);
80
+ const created = await env.kv.cmd('HGET', `w:agent:${a}`, 'since');
81
+ if (!created)
82
+ await env.kv.cmd('HSET', `w:agent:${a}`, 'since', now);
83
+ return { account: account, endpoint: `${env.baseUrl}/w/${secret}` };
84
+ }
85
+ export function signedFields(take, chainId) {
86
+ return {
87
+ v: 1,
88
+ chainId,
89
+ account: lower(take.account),
90
+ id: take.id,
91
+ at: take.at,
92
+ txHash: take.txHash,
93
+ blockNumber: take.blockNumber,
94
+ blockHash: take.blockHash,
95
+ status: take.status,
96
+ summary: take.summary,
97
+ request: take.request,
98
+ changes: take.changes,
99
+ };
100
+ }
101
+ /** The digest of a take's signed fields. Anyone can recompute it. */
102
+ export function takeDigest(signed) {
103
+ return keccak256(toBytes(JSON.stringify(signed)));
104
+ }
105
+ async function witnessTake(env, take, charge) {
106
+ const signer = privateKeyToAccount(env.witnessKey);
107
+ const signed = signedFields(take, env.chainId);
108
+ const digest = takeDigest(signed);
109
+ const signature = await signer.signMessage({ message: { raw: digest } });
110
+ return { signed, digest, signature, witness: signer.address, charge: charge.toString(), reason: take.reason, notes: take.notes };
111
+ }
112
+ // ---------- merkle root of a settlement ----------
113
+ const pair = (a, b) => (BigInt(a) < BigInt(b) ? keccak256(concat([a, b])) : keccak256(concat([b, a])));
114
+ export function merkleRoot(leaves) {
115
+ if (!leaves.length)
116
+ return `0x${'00'.repeat(32)}`;
117
+ let level = [...leaves];
118
+ while (level.length > 1) {
119
+ const next = [];
120
+ for (let i = 0; i < level.length; i += 2)
121
+ next.push(i + 1 < level.length ? pair(level[i], level[i + 1]) : level[i]);
122
+ level = next;
123
+ }
124
+ return level[0];
125
+ }
126
+ export function merkleProof(leaves, index) {
127
+ const proof = [];
128
+ let level = [...leaves];
129
+ let i = index;
130
+ while (level.length > 1) {
131
+ const sibling = i % 2 === 0 ? i + 1 : i - 1;
132
+ if (sibling < level.length)
133
+ proof.push(level[sibling]);
134
+ const next = [];
135
+ for (let j = 0; j < level.length; j += 2)
136
+ next.push(j + 1 < level.length ? pair(level[j], level[j + 1]) : level[j]);
137
+ level = next;
138
+ i = Math.floor(i / 2);
139
+ }
140
+ return proof;
141
+ }
142
+ export function verifyProof(leaf, proof, root) {
143
+ let h = leaf;
144
+ for (const p of proof)
145
+ h = pair(h, p);
146
+ return lower(h) === lower(root);
147
+ }
148
+ // ---------- pricing and credit ----------
149
+ async function ethCall(env, to, data) {
150
+ return new RpcClient(env.rpcUrl).request('eth_call', [{ to, data }, 'latest']);
151
+ }
152
+ async function readCredits(env, fn, args = []) {
153
+ const credits = env.launch.credits;
154
+ const data = encodeFunctionData({ abi: CREDITS_ABI, functionName: fn, args: args });
155
+ return decodeFunctionResult({ abi: CREDITS_ABI, functionName: fn, data: await ethCall(env, credits, data) });
156
+ }
157
+ const ERC20_META = [
158
+ { type: 'function', name: 'decimals', stateMutability: 'view', inputs: [], outputs: [{ type: 'uint8' }] },
159
+ { type: 'function', name: 'symbol', stateMutability: 'view', inputs: [], outputs: [{ type: 'string' }] },
160
+ ];
161
+ export async function tokenMeta(env) {
162
+ const token = env.launch.token;
163
+ if (!token)
164
+ return null;
165
+ const cached = await env.kv.cmd('GET', `w:meta:${lower(token)}`);
166
+ if (cached)
167
+ return JSON.parse(cached);
168
+ const decimals = Number(decodeFunctionResult({ abi: ERC20_META, functionName: 'decimals', data: await ethCall(env, token, encodeFunctionData({ abi: ERC20_META, functionName: 'decimals' })) }));
169
+ const symbol = String(decodeFunctionResult({ abi: ERC20_META, functionName: 'symbol', data: await ethCall(env, token, encodeFunctionData({ abi: ERC20_META, functionName: 'symbol' })) }));
170
+ const meta = { decimals, symbol };
171
+ await env.kv.cmd('SET', `w:meta:${lower(token)}`, JSON.stringify(meta));
172
+ return meta;
173
+ }
174
+ /** USD price from DexScreener: the most liquid pair that reports one. */
175
+ export async function dexScreenerPrice(token) {
176
+ try {
177
+ const res = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${token}`, { signal: AbortSignal.timeout(4000) });
178
+ if (!res.ok)
179
+ return null;
180
+ const body = (await res.json());
181
+ const pairs = (body.pairs ?? []).filter((p) => p.priceUsd && lower(p.baseToken?.address ?? '') === lower(token));
182
+ pairs.sort((a, b) => (b.liquidity?.usd ?? 0) - (a.liquidity?.usd ?? 0));
183
+ const price = Number(pairs[0]?.priceUsd);
184
+ return Number.isFinite(price) && price > 0 ? price : null;
185
+ }
186
+ catch {
187
+ return null;
188
+ }
189
+ }
190
+ /**
191
+ * Charges are counted in millionths of a token so totals fit Redis's 64-bit
192
+ * counters; this is how many of the token's smallest units make one millionth.
193
+ */
194
+ export function microScale(decimals) {
195
+ return decimals > 6 ? 10n ** BigInt(decimals - 6) : 1n;
196
+ }
197
+ /** Price of one take in the token's smallest unit, and how it was set. */
198
+ export async function takePrice(env) {
199
+ const meta = await tokenMeta(env);
200
+ if (!meta || !env.launch.token)
201
+ return { units: 0n, usd: null, source: 'fixed' };
202
+ const cached = await env.kv.cmd('GET', 'w:price');
203
+ let usd = cached ? Number(cached) : null;
204
+ if (cached === null) {
205
+ usd = await (env.priceUsd ?? dexScreenerPrice)(env.launch.token);
206
+ await env.kv.cmd('SET', 'w:price', usd === null ? '0' : String(usd), 'EX', 600);
207
+ }
208
+ if (usd && usd > 0) {
209
+ const whole = env.launch.takePriceUsd / usd;
210
+ const raw = parseUnits(whole.toFixed(Math.min(meta.decimals, 18)), meta.decimals);
211
+ const scale = microScale(meta.decimals);
212
+ const units = ((raw + scale - 1n) / scale) * scale;
213
+ return { units: units > 0n ? units : scale, usd, source: 'market' };
214
+ }
215
+ return { units: parseUnits(env.launch.fallbackTakePriceTokens, meta.decimals), usd: null, source: 'fixed' };
216
+ }
217
+ /** Credit an account can still spend: on-chain credit, less unsettled charges and pending withdrawals. */
218
+ export async function availableCredit(env, account) {
219
+ if (!env.launch.credits)
220
+ return 0n;
221
+ const [credit, pending] = await Promise.all([
222
+ readCredits(env, 'credits', [account]),
223
+ readCredits(env, 'withdrawAmount', [account]),
224
+ ]);
225
+ const meta = await tokenMeta(env);
226
+ const due = BigInt((await env.kv.cmd('HGET', 'w:due', lower(account))) ?? '0') * microScale(meta?.decimals ?? 18);
227
+ const left = credit - due - pending;
228
+ return left > 0n ? left : 0n;
229
+ }
230
+ // ---------- the witnessed RPC ----------
231
+ const TAKE_METHODS = new Set(['eth_sendRawTransaction', 'eth_sendRawTransactionConditional', 'eth_sendRawTransactionSync', 'eth_sendTransaction']);
232
+ const MAX_BATCH = 20;
233
+ const RECENT = 50;
234
+ async function lock(kv, key, ms) {
235
+ const token = randomBytes(8).toString('hex');
236
+ const started = Date.now();
237
+ for (;;) {
238
+ if (await kv.cmd('SET', key, token, 'NX', 'PX', ms))
239
+ break;
240
+ if (Date.now() - started > 25_000)
241
+ throw new WitnessError(503, 'This agent is busy with another take. Try again.');
242
+ await sleep(100);
243
+ }
244
+ return async () => {
245
+ if ((await kv.cmd('GET', key)) === token)
246
+ await kv.cmd('DEL', key);
247
+ };
248
+ }
249
+ const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
250
+ /** Handle a JSON-RPC request (or batch) sent to an agent's witness endpoint. */
251
+ export async function witnessRpc(env, secret, body) {
252
+ const batch = Array.isArray(body);
253
+ const requests = (batch ? body : [body]);
254
+ if (!requests.length || requests.length > MAX_BATCH)
255
+ return rpcError(null, -32600, `Send 1 to ${MAX_BATCH} requests at a time.`);
256
+ const account = /^[0-9a-f]{48}$/.test(secret) ? await env.kv.cmd('GET', `w:key:${secret}`) : null;
257
+ if (!account) {
258
+ const out = requests.map((r) => rpcError(r?.id, -32001, 'Unknown witness endpoint. Run `stuntman witness` to get one.'));
259
+ return batch ? out : out[0];
260
+ }
261
+ const writes = requests.some((r) => TAKE_METHODS.has(String(r?.method)));
262
+ const unlock = writes ? await lock(env.kv, `w:lock:${account}`, 60_000) : async () => { };
263
+ try {
264
+ return await runBatch(env, account, requests, batch);
265
+ }
266
+ finally {
267
+ await unlock();
268
+ }
269
+ }
270
+ async function runBatch(env, account, requests, batch) {
271
+ const { kv, launch } = env;
272
+ const [stateJson, recentRaw, agentRaw] = (await kv.pipeline([
273
+ ['GET', `w:state:${account}`],
274
+ ['LRANGE', `w:takes:${account}`, -RECENT, -1],
275
+ ['HGETALL', `w:agent:${account}`],
276
+ ]));
277
+ const agent = hashToObject(agentRaw);
278
+ const recent = (recentRaw ?? []).map((r) => JSON.parse(r));
279
+ const mem = {
280
+ state: stateJson ? JSON.parse(stateJson) : null,
281
+ takes: recent.map((r) => r.take),
282
+ byHash: new Map(),
283
+ added: [],
284
+ };
285
+ // Receipts for takes older than the recent window.
286
+ for (const r of requests) {
287
+ if (r?.method !== 'eth_getTransactionReceipt' && r?.method !== 'eth_getTransactionByHash')
288
+ continue;
289
+ const hash = Array.isArray(r.params) ? String(r.params[0] ?? '').toLowerCase() : '';
290
+ if (!/^0x[0-9a-f]{64}$/.test(hash) || mem.takes.some((t) => lower(t.txHash) === hash))
291
+ continue;
292
+ const rec = await kv.cmd('GET', `w:tx:${hash}`);
293
+ if (rec)
294
+ mem.byHash.set(hash, JSON.parse(rec).take);
295
+ }
296
+ const cfg = { version: 1, rpcUrl: env.rpcUrl, chainId: env.chainId, account, mode: 'shadow', createdAt: agent.since ?? new Date().toISOString() };
297
+ const engine = await createEngine(cfg);
298
+ let simulated = Number(agent.simulated ?? '0');
299
+ const scale = launch.credits ? microScale((await tokenMeta(env))?.decimals ?? 18) : 1n;
300
+ const out = [];
301
+ const records = [];
302
+ const funds = [];
303
+ await withMemoryStore(mem, async () => {
304
+ for (const req of requests) {
305
+ if (!req || typeof req !== 'object' || typeof req.method !== 'string') {
306
+ out.push(rpcError(req?.id, -32600, 'invalid request'));
307
+ continue;
308
+ }
309
+ if (req.method === 'stuntman_fund') {
310
+ // Practice money. Shown on the public record, so viewers see what the agent started with.
311
+ const [asset, amount] = Array.isArray(req.params) ? req.params : [];
312
+ const isEth = String(asset).toUpperCase() === 'ETH';
313
+ if ((!isEth && !isAddress(asset)) || typeof amount !== 'string' || !/^[0-9]+$/.test(amount) || BigInt(amount) === 0n) {
314
+ out.push(rpcError(req.id, -32602, 'stuntman_fund takes ["ETH" or a token address, amount in the smallest unit]'));
315
+ continue;
316
+ }
317
+ try {
318
+ const res = await fund(engine, isEth ? 'ETH' : asset, BigInt(amount));
319
+ funds.push({ asset: isEth ? 'ETH' : lower(asset), symbol: res.symbol, amount, decimals: res.decimals, at: new Date().toISOString() });
320
+ out.push({ jsonrpc: '2.0', id: req.id ?? null, result: { symbol: res.symbol, decimals: res.decimals, balance: res.balance.toString(), visible: res.visible } });
321
+ }
322
+ catch (err) {
323
+ out.push(rpcError(req.id, -32000, err.message));
324
+ }
325
+ continue;
326
+ }
327
+ let charge = 0n;
328
+ if (TAKE_METHODS.has(req.method) && simulated >= launch.freeTakes && launch.credits) {
329
+ charge = (await takePrice(env)).units;
330
+ const due = records.reduce((s, r) => s + BigInt(r.witnessed.charge), 0n);
331
+ if ((await availableCredit(env, account)) - due < charge) {
332
+ out.push(rpcError(req.id, -32002, `Out of witness credit. This agent has used its ${launch.freeTakes} free takes; top up at ${env.baseUrl}/witness to keep practicing with a witness. Nothing was sent.`));
333
+ continue;
334
+ }
335
+ }
336
+ const before = mem.added.length;
337
+ out.push(await handle(engine, req, { port: 0 }));
338
+ for (const take of mem.added.slice(before)) {
339
+ const charged = take.status === 'rejected' ? 0n : charge;
340
+ if (take.status !== 'rejected')
341
+ simulated++;
342
+ records.push({ take, witnessed: await witnessTake(env, take, charged) });
343
+ }
344
+ }
345
+ });
346
+ // Save what changed in one round trip.
347
+ const cmds = [];
348
+ if (mem.state)
349
+ cmds.push(['SET', `w:state:${account}`, JSON.stringify(mem.state)]);
350
+ const now = new Date().toISOString();
351
+ for (const { take, witnessed } of records) {
352
+ const rec = JSON.stringify({ take, witnessed });
353
+ cmds.push(['RPUSH', `w:takes:${account}`, rec]);
354
+ cmds.push(['SET', `w:tx:${lower(take.txHash)}`, rec]);
355
+ cmds.push(['HINCRBY', `w:agent:${account}`, take.status, 1]);
356
+ cmds.push(['HINCRBY', 'w:stats', take.status, 1]);
357
+ if (take.status !== 'rejected') {
358
+ cmds.push(['RPUSH', 'w:leaves', witnessed.digest]);
359
+ cmds.push(['HINCRBY', `w:agent:${account}`, 'simulated', 1]);
360
+ cmds.push(['HINCRBY', 'w:stats', 'simulated', 1]);
361
+ }
362
+ if (witnessed.charge !== '0') {
363
+ const micro = (BigInt(witnessed.charge) / scale).toString();
364
+ cmds.push(['HINCRBY', 'w:due', account, micro]);
365
+ cmds.push(['HINCRBY', `w:agent:${account}`, 'charged', micro]);
366
+ cmds.push(['HINCRBY', 'w:stats', 'charged', micro]);
367
+ }
368
+ if (!agent.first) {
369
+ cmds.push(['HSET', `w:agent:${account}`, 'first', take.at]);
370
+ agent.first = take.at;
371
+ }
372
+ cmds.push(['HSET', `w:agent:${account}`, 'last', now]);
373
+ }
374
+ for (const f of funds)
375
+ cmds.push(['RPUSH', `w:funds:${account}`, JSON.stringify(f)]);
376
+ if (cmds.length)
377
+ await kv.pipeline(cmds);
378
+ return batch ? out : out[0];
379
+ }
380
+ export async function agentRecord(env, address, limit = 50) {
381
+ if (!isAddress(address))
382
+ throw new WitnessError(400, 'address must be an address');
383
+ const a = lower(address);
384
+ const [agentRaw, recentRaw, fundsRaw] = (await env.kv.pipeline([
385
+ ['HGETALL', `w:agent:${a}`],
386
+ ['LRANGE', `w:takes:${a}`, -Math.min(Math.max(limit, 1), 200), -1],
387
+ ['LRANGE', `w:funds:${a}`, 0, 99],
388
+ ]));
389
+ const agent = hashToObject(agentRaw);
390
+ if (!agent.account)
391
+ return null;
392
+ const n = (k) => Number(agent[k] ?? '0');
393
+ const scale = microScale((await tokenMeta(env).catch(() => null))?.decimals ?? 18);
394
+ return {
395
+ account: a,
396
+ since: agent.since ?? null,
397
+ first: agent.first ?? null,
398
+ last: agent.last ?? null,
399
+ counts: { simulated: n('simulated'), filled: n('filled'), reverted: n('reverted'), rejected: n('rejected') },
400
+ charged: (BigInt(agent.charged ?? '0') * scale).toString(),
401
+ witness: witnessAddress(env),
402
+ funds: (fundsRaw ?? []).map((f) => JSON.parse(f)),
403
+ takes: (recentRaw ?? [])
404
+ .map((r) => JSON.parse(r))
405
+ .reverse()
406
+ .map(({ take, witnessed }) => ({
407
+ ...witnessed,
408
+ take: { id: take.id, status: take.status, summary: take.summary, reason: take.reason, txHash: take.txHash, blockNumber: take.blockNumber, at: take.at },
409
+ })),
410
+ };
411
+ }
412
+ export async function witnessStats(env) {
413
+ const [statsRaw, agents, lastRaw, count] = (await env.kv.pipeline([
414
+ ['HGETALL', 'w:stats'],
415
+ ['SCARD', 'w:agents'],
416
+ ['LRANGE', 'w:settlements', -1, -1],
417
+ ['LLEN', 'w:settlements'],
418
+ ]));
419
+ const stats = hashToObject(statsRaw);
420
+ const n = (k) => Number(stats[k] ?? '0');
421
+ let chain = null;
422
+ if (env.launch.credits) {
423
+ try {
424
+ const [burned, toTreasury, charged, takes, burnBps] = await Promise.all(['totalBurned', 'totalToTreasury', 'totalCharged', 'totalTakes', 'burnBps'].map((f) => readCredits(env, f)));
425
+ chain = { burned: String(burned), toTreasury: String(toTreasury), charged: String(charged), takes: String(takes), burnBps: String(burnBps) };
426
+ }
427
+ catch {
428
+ chain = null;
429
+ }
430
+ }
431
+ return {
432
+ agents: Number(agents ?? 0),
433
+ takes: { simulated: n('simulated'), filled: n('filled'), reverted: n('reverted'), rejected: n('rejected') },
434
+ charged: (BigInt(stats.charged ?? '0') * microScale((await tokenMeta(env).catch(() => null))?.decimals ?? 18)).toString(),
435
+ pendingTakes: Number(await env.kv.cmd('LLEN', 'w:leaves')),
436
+ settlements: Number(count ?? 0),
437
+ lastSettlement: lastRaw?.[0] ? JSON.parse(lastRaw[0]) : null,
438
+ chain,
439
+ };
440
+ }
441
+ /** Public settings for the site and the CLI. */
442
+ export async function witnessConfig(env) {
443
+ const meta = await tokenMeta(env).catch(() => null);
444
+ const price = env.launch.token && env.launch.credits ? await takePrice(env).catch(() => null) : null;
445
+ return {
446
+ chainId: env.chainId,
447
+ witness: witnessAddress(env),
448
+ token: env.launch.token,
449
+ credits: env.launch.credits,
450
+ symbol: meta?.symbol ?? null,
451
+ decimals: meta?.decimals ?? null,
452
+ freeTakes: env.launch.freeTakes,
453
+ takePriceUsd: env.launch.takePriceUsd,
454
+ takePrice: price ? { units: price.units.toString(), usd: price.usd, source: price.source } : null,
455
+ burnBps: env.launch.burnBps,
456
+ billing: Boolean(env.launch.token && env.launch.credits),
457
+ };
458
+ }
459
+ /** Where a take's digest sits in a settlement, with its proof. */
460
+ export async function proofFor(env, digest) {
461
+ if (!/^0x[0-9a-fA-F]{64}$/.test(digest))
462
+ throw new WitnessError(400, 'digest must be 32 bytes of hex');
463
+ const count = Number(await env.kv.cmd('LLEN', 'w:settlements'));
464
+ for (let id = count; id >= 1 && id > count - 60; id--) {
465
+ const leaves = (await env.kv.cmd('LRANGE', `w:settlement:${id}:leaves`, 0, -1));
466
+ const index = leaves.findIndex((l) => lower(l) === lower(digest));
467
+ if (index < 0)
468
+ continue;
469
+ const settlement = JSON.parse((await env.kv.cmd('LRANGE', 'w:settlements', id - 1, id - 1))[0]);
470
+ return { settlement, index, proof: merkleProof(leaves, index) };
471
+ }
472
+ return null;
473
+ }
474
+ // ---------- daily settlement ----------
475
+ const SETTLE_CHUNK = 100;
476
+ /**
477
+ * Settle every take witnessed since the last settlement: anchor their root and
478
+ * collect the charges on chain (when the credits contract is set), then record
479
+ * the settlement. Safe to run again: it only settles what is still pending.
480
+ */
481
+ export async function settle(env) {
482
+ const { kv, launch } = env;
483
+ const unlock = await lock(kv, 'w:lock:settle', 5 * 60_000);
484
+ try {
485
+ const n = Number(await kv.cmd('LLEN', 'w:leaves'));
486
+ if (n === 0)
487
+ return { skipped: 'No takes to settle.' };
488
+ const leaves = (await kv.cmd('LRANGE', 'w:leaves', 0, n - 1));
489
+ const root = merkleRoot(leaves);
490
+ const due = Object.entries(hashToObject(await kv.cmd('HGETALL', 'w:due')))
491
+ .map(([a, v]) => [a, BigInt(v)])
492
+ .filter(([, v]) => v > 0n);
493
+ const id = Number(await kv.cmd('LLEN', 'w:settlements')) + 1;
494
+ const scale = microScale((await tokenMeta(env).catch(() => null))?.decimals ?? 18);
495
+ const txs = [];
496
+ if (launch.credits) {
497
+ const chain = defineChain({
498
+ id: env.chainId,
499
+ name: 'Robinhood Chain',
500
+ nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
501
+ rpcUrls: { default: { http: [env.rpcUrl] } },
502
+ });
503
+ const wallet = createWalletClient({ account: privateKeyToAccount(env.witnessKey), chain, transport: http(env.rpcUrl) });
504
+ const rpc = new RpcClient(env.rpcUrl);
505
+ const chunks = due.length ? Array.from({ length: Math.ceil(due.length / SETTLE_CHUNK) }, (_, i) => due.slice(i * SETTLE_CHUNK, (i + 1) * SETTLE_CHUNK)) : [[]];
506
+ for (let i = 0; i < chunks.length; i++) {
507
+ const hash = await wallet.writeContract({
508
+ address: launch.credits,
509
+ abi: CREDITS_ABI,
510
+ functionName: 'settle',
511
+ args: [root, i === 0 ? BigInt(n) : 0n, chunks[i].map(([a]) => a), chunks[i].map(([, v]) => v * scale)],
512
+ });
513
+ for (let tries = 0;; tries++) {
514
+ const receipt = await rpc.request('eth_getTransactionReceipt', [hash]);
515
+ if (receipt) {
516
+ if (receipt.status !== '0x1')
517
+ throw new WitnessError(502, `Settlement transaction ${hash} failed on chain.`);
518
+ break;
519
+ }
520
+ if (tries > 120)
521
+ throw new WitnessError(504, `Settlement transaction ${hash} was not mined in time.`);
522
+ await sleep(1000);
523
+ }
524
+ txs.push(hash);
525
+ }
526
+ }
527
+ const settlement = {
528
+ id,
529
+ at: new Date().toISOString(),
530
+ root,
531
+ takes: n,
532
+ accounts: due.length,
533
+ charged: (due.reduce((s, [, v]) => s + v, 0n) * scale).toString(),
534
+ txs,
535
+ onChain: txs.length > 0,
536
+ };
537
+ const cmds = [];
538
+ for (let i = 0; i < leaves.length; i += 500)
539
+ cmds.push(['RPUSH', `w:settlement:${id}:leaves`, ...leaves.slice(i, i + 500)]);
540
+ cmds.push(['RPUSH', 'w:settlements', JSON.stringify(settlement)]);
541
+ cmds.push(['LTRIM', 'w:leaves', n, -1]);
542
+ for (const [a, v] of due)
543
+ cmds.push(['HINCRBY', 'w:due', a, (-v).toString()]);
544
+ await kv.pipeline(cmds);
545
+ return settlement;
546
+ }
547
+ finally {
548
+ await unlock();
549
+ }
550
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stuntman",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Practice mode for AI agents. Real apps, real prices, practice money. Every send is played out against the live chain and nothing is broadcast.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,6 +16,7 @@
16
16
  },
17
17
  "scripts": {
18
18
  "build:executor": "node scripts/build-executor.mjs",
19
+ "build:credits": "node scripts/build-credits.mjs",
19
20
  "build": "tsc -p . && node scripts/postbuild.mjs",
20
21
  "test": "npm run build && node --test --test-concurrency=1 \"test/*.test.mjs\"",
21
22
  "prepublishOnly": "npm test"