stuntman 0.1.2 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -2
- package/dist/cli.js +106 -8
- package/dist/credits.generated.js +4 -0
- package/dist/game.js +173 -0
- package/dist/kv.js +153 -0
- package/dist/launch.js +22 -0
- package/dist/mcp.js +49 -3
- package/dist/remote.js +69 -0
- package/dist/store.js +32 -3
- package/dist/version.js +1 -1
- package/dist/witness.js +550 -0
- package/package.json +15 -1
package/README.md
CHANGED
|
@@ -93,18 +93,42 @@ npx stuntman fund ETH 2
|
|
|
93
93
|
npx stuntman fund 0xTokenAddress 500
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
+
## Virtuals agents
|
|
97
|
+
|
|
98
|
+
Virtuals GAME agents practice two ways. Agents whose plugins send their own transactions: sign the agent wallet up with `stuntman witness --key-env WALLET_PRIVATE_KEY` and point the plugin's `RPC_PROVIDER_URL` at the endpoint it prints. TypeScript GAME agents can also add Stuntman as a worker:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { stuntmanWorker } from 'stuntman/game'; // npm install stuntman @virtuals-protocol/game
|
|
102
|
+
workers: [await stuntmanWorker({ endpoint: process.env.STUNTMAN_ENDPOINT })]
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`stuntman connect virtuals` prints both setups.
|
|
106
|
+
|
|
107
|
+
## Witnessed practice
|
|
108
|
+
|
|
109
|
+
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.
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
stuntman witness # sign up the practice account; the MCP tools switch over
|
|
113
|
+
stuntman fund ETH 1 # practice money on the witness, listed on the record
|
|
114
|
+
stuntman witness off # back to practicing locally
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
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`.
|
|
118
|
+
|
|
96
119
|
## Commands
|
|
97
120
|
|
|
98
121
|
```
|
|
99
122
|
stuntman init --address <wallet> | --new [--rpc <url>] [--eth <amount>]
|
|
100
123
|
stuntman mcp MCP server over stdio
|
|
101
124
|
stuntman rpc [--port 8545] Practice RPC
|
|
102
|
-
stuntman connect [claude|codex|json|raxol]
|
|
125
|
+
stuntman connect [claude|codex|json|raxol|virtuals]
|
|
103
126
|
stuntman takes [--limit 20] [--json]
|
|
104
127
|
stuntman take <id> [--json]
|
|
105
128
|
stuntman balances [token ...]
|
|
106
129
|
stuntman fund ETH <amount> | <token> <amount>
|
|
107
130
|
stuntman status Account, simulation mode, go-live checklist
|
|
131
|
+
stuntman witness [off] Witnessed practice on Stuntman's server
|
|
108
132
|
stuntman reset --yes
|
|
109
133
|
stuntman doctor What your RPC supports
|
|
110
134
|
```
|
|
@@ -152,7 +176,7 @@ npm test # builds, starts a local chain, runs every backend end to end
|
|
|
152
176
|
|
|
153
177
|
`npm run build:executor` recompiles `contracts/StuntmanExecutor.sol`.
|
|
154
178
|
|
|
155
|
-
The website lives in `site
|
|
179
|
+
The website lives in `site/` (static files) and the witness API in `api/`. Vercel builds both from the repository root using `vercel.json`.
|
|
156
180
|
|
|
157
181
|
## License
|
|
158
182
|
|
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 = {};
|
|
@@ -55,7 +56,7 @@ Start
|
|
|
55
56
|
Connect your agent
|
|
56
57
|
stuntman mcp Practice wallet as an MCP server (stdio)
|
|
57
58
|
stuntman rpc [--port 8545] Practice RPC for agents that send their own transactions
|
|
58
|
-
stuntman connect [claude|codex|json|raxol] Print the setup line for your agent
|
|
59
|
+
stuntman connect [claude|codex|json|raxol|virtuals] Print the setup line for your agent
|
|
59
60
|
|
|
60
61
|
Watch the takes
|
|
61
62
|
stuntman takes [--limit 20] Recent takes
|
|
@@ -63,6 +64,12 @@ 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
|
+
stuntman witness --key-env VAR Sign up an agent's own wallet (key read from env VAR)
|
|
72
|
+
|
|
66
73
|
Practice money
|
|
67
74
|
stuntman fund ETH <amount>
|
|
68
75
|
stuntman fund <token address> <amount>
|
|
@@ -101,6 +108,20 @@ function connectLines(target) {
|
|
|
101
108
|
'# In code, the Xochi config raxol_payments takes:',
|
|
102
109
|
`%{base_url: "http://127.0.0.1:${DEFAULT_PORT}/xochi", auth: {:member, token}}`,
|
|
103
110
|
].join('\n');
|
|
111
|
+
case 'virtuals':
|
|
112
|
+
return [
|
|
113
|
+
'# Virtuals GAME agents, two ways (use a witness endpoint to put takes on a public record):',
|
|
114
|
+
'',
|
|
115
|
+
'# 1. Agents whose plugins send their own transactions (RPC_PROVIDER_URL + WALLET_PRIVATE_KEY):',
|
|
116
|
+
'# register the agent wallet with the witness, then point the plugin RPC at the endpoint it prints.',
|
|
117
|
+
`${installed ? 'stuntman' : 'npx stuntman'} witness --key-env WALLET_PRIVATE_KEY`,
|
|
118
|
+
'RPC_PROVIDER_URL=<the endpoint>',
|
|
119
|
+
'',
|
|
120
|
+
'# 2. Give the agent Stuntman practice functions as a GAME worker:',
|
|
121
|
+
'npm install stuntman @virtuals-protocol/game',
|
|
122
|
+
"import { stuntmanWorker } from 'stuntman/game';",
|
|
123
|
+
'workers: [await stuntmanWorker({ endpoint: process.env.STUNTMAN_ENDPOINT })]',
|
|
124
|
+
].join('\n');
|
|
104
125
|
default:
|
|
105
126
|
return [
|
|
106
127
|
`Claude Code: claude mcp add stuntman -- ${shellLine}`,
|
|
@@ -110,6 +131,7 @@ function connectLines(target) {
|
|
|
110
131
|
'',
|
|
111
132
|
`Agents that send their own transactions: run "${rpc}" and use http://127.0.0.1:${DEFAULT_PORT} as the RPC address.`,
|
|
112
133
|
`Raxol agents: run "${rpc}", then "${installed ? 'stuntman' : 'npx stuntman'} connect raxol" for the two settings.`,
|
|
134
|
+
`Virtuals GAME agents: "${installed ? 'stuntman' : 'npx stuntman'} connect virtuals".`,
|
|
113
135
|
].join('\n');
|
|
114
136
|
}
|
|
115
137
|
}
|
|
@@ -167,9 +189,10 @@ async function cmdInit(flags) {
|
|
|
167
189
|
async function cmdStatus() {
|
|
168
190
|
const cfg = requireConfig();
|
|
169
191
|
const engine = await createEngine(cfg);
|
|
170
|
-
const
|
|
171
|
-
const r = readiness(readTakes());
|
|
192
|
+
const r = readiness(await allTakes(cfg));
|
|
172
193
|
out(`Practicing as ${checksum(cfg.account)} on chain ${cfg.chainId}`);
|
|
194
|
+
if (cfg.witness)
|
|
195
|
+
out(`Witnessed: every take is simulated and signed by Stuntman. Record: ${witnessBase()}/a/${checksum(cfg.account)}`);
|
|
173
196
|
out(`Simulation: ${describeCapabilities(engine.caps)}`);
|
|
174
197
|
out(`Takes: ${r.total} (${r.filled} filled, ${r.bad} bad)`);
|
|
175
198
|
out('');
|
|
@@ -181,15 +204,19 @@ async function cmdStatus() {
|
|
|
181
204
|
out('To go live, swap the Stuntman wallet tool (or RPC address) back for your real one.');
|
|
182
205
|
out('Your agent then does its own stunts.');
|
|
183
206
|
}
|
|
184
|
-
if (
|
|
207
|
+
if (r.total === 0) {
|
|
185
208
|
out('');
|
|
186
209
|
out('No takes yet. Connect your agent with "npx stuntman connect" and let it trade.');
|
|
187
210
|
}
|
|
188
211
|
}
|
|
212
|
+
/** Takes oldest first, from the witness when witness mode is on. */
|
|
213
|
+
async function allTakes(cfg, limit = 500) {
|
|
214
|
+
return cfg.witness ? (await remoteTakes(cfg.witness, limit)).reverse() : readTakes();
|
|
215
|
+
}
|
|
189
216
|
async function cmdTakes(flags) {
|
|
190
|
-
requireConfig();
|
|
217
|
+
const cfg = requireConfig();
|
|
191
218
|
const limit = Math.max(1, Number(flags.limit ?? 20));
|
|
192
|
-
const takes =
|
|
219
|
+
const takes = (await allTakes(cfg, limit)).slice(-limit).reverse();
|
|
193
220
|
if (flags.json) {
|
|
194
221
|
out(JSON.stringify(takes, null, 2));
|
|
195
222
|
return;
|
|
@@ -206,15 +233,22 @@ async function cmdTakes(flags) {
|
|
|
206
233
|
}
|
|
207
234
|
}
|
|
208
235
|
async function cmdTake(args, flags) {
|
|
209
|
-
requireConfig();
|
|
236
|
+
const cfg = requireConfig();
|
|
210
237
|
const id = Number(args[0]);
|
|
211
|
-
const take =
|
|
238
|
+
const take = (await allTakes(cfg)).find((t) => t.id === id);
|
|
212
239
|
if (!take)
|
|
213
240
|
throw new Error(`No take ${args[0] ?? ''}. Run "stuntman takes" to see them.`);
|
|
214
241
|
out(flags.json ? JSON.stringify(take, null, 2) : formatTake(take, true));
|
|
215
242
|
}
|
|
216
243
|
async function cmdBalances(args) {
|
|
217
244
|
const cfg = requireConfig();
|
|
245
|
+
if (cfg.witness) {
|
|
246
|
+
const rows = await remoteCall(cfg.witness, 'stuntman_balances');
|
|
247
|
+
out(`Practice balances for ${checksum(cfg.account)} (witnessed)`);
|
|
248
|
+
for (const r of rows)
|
|
249
|
+
out(` ${r.symbol.padEnd(10)} ${r.formatted.padStart(24)}${r.practice ? '' : ' real (untouched in practice)'}`);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
218
252
|
const engine = await createEngine(cfg);
|
|
219
253
|
const extra = args.filter(isAddr);
|
|
220
254
|
const rows = await balances(engine, extra);
|
|
@@ -233,11 +267,19 @@ async function cmdFund(args) {
|
|
|
233
267
|
if (!isEth && !isAddr(asset))
|
|
234
268
|
throw new Error(`${asset} is not ETH or a token address.`);
|
|
235
269
|
const decimals = isEth ? 18 : (await readTokenInfo(engine.rpc, asset)).decimals;
|
|
270
|
+
if (cfg.witness) {
|
|
271
|
+
const r = await remoteCall(cfg.witness, 'stuntman_fund', [isEth ? 'ETH' : asset, parseUnits(amount, decimals).toString()]);
|
|
272
|
+
out(`Added ${amount} ${r.symbol} on the witness. Practice balance: ${fmt(BigInt(r.balance), r.decimals)} ${r.symbol}.`);
|
|
273
|
+
out('Practice money added on the witness shows on your public record.');
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
236
276
|
const res = await fund(engine, isEth ? 'ETH' : asset, parseUnits(amount, decimals));
|
|
237
277
|
out(`Added ${amount} ${res.symbol}. Practice balance: ${fmt(res.balance, res.decimals)} ${res.symbol}.`);
|
|
238
278
|
}
|
|
239
279
|
async function cmdReset(flags) {
|
|
240
280
|
const cfg = requireConfig();
|
|
281
|
+
if (cfg.witness)
|
|
282
|
+
throw new Error('A witnessed record cannot be reset. Run "stuntman witness off" to practice on this machine again; that record is separate.');
|
|
241
283
|
if (!flags.yes)
|
|
242
284
|
throw new Error('This clears every practice balance and take. Run again with --yes to confirm.');
|
|
243
285
|
resetPractice(cfg.chainId, cfg.account);
|
|
@@ -274,6 +316,9 @@ async function cmdDoctor() {
|
|
|
274
316
|
}
|
|
275
317
|
async function cmdRpc(flags) {
|
|
276
318
|
const cfg = requireConfig();
|
|
319
|
+
if (cfg.witness) {
|
|
320
|
+
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".`);
|
|
321
|
+
}
|
|
277
322
|
const engine = await createEngine(cfg);
|
|
278
323
|
const port = Number(flags.port ?? process.env.STUNTMAN_PORT ?? DEFAULT_PORT);
|
|
279
324
|
const host = typeof flags.host === 'string' ? flags.host : '127.0.0.1';
|
|
@@ -292,6 +337,57 @@ async function cmdRpc(flags) {
|
|
|
292
337
|
err(`Xochi practice gateway on http://${host}:${port}/xochi (quotes from ${xochiUrl()}, executes stay here).`);
|
|
293
338
|
err('Press Ctrl+C to stop.');
|
|
294
339
|
}
|
|
340
|
+
async function cmdWitness(args, flags) {
|
|
341
|
+
// An agent's own wallet (for example a Virtuals agent's WALLET_PRIVATE_KEY):
|
|
342
|
+
// register it without touching this machine's practice settings. The key is
|
|
343
|
+
// read from an environment variable so it never appears in the command line.
|
|
344
|
+
if (typeof flags['key-env'] === 'string') {
|
|
345
|
+
const name = flags['key-env'];
|
|
346
|
+
const key = process.env[name];
|
|
347
|
+
if (!key || !/^(0x)?[0-9a-fA-F]{64}$/.test(key.trim()))
|
|
348
|
+
throw new Error(`Set ${name} to the agent's private key first. It is only used to sign the sign-up message.`);
|
|
349
|
+
const k = (key.trim().startsWith('0x') ? key.trim() : `0x${key.trim()}`);
|
|
350
|
+
const { account, endpoint } = await registerWitness({ version: 1, rpcUrl: '', chainId: 0, account: '0x0000000000000000000000000000000000000000', mode: 'practice-key', practiceKey: k, createdAt: '' });
|
|
351
|
+
out(`Witnessed practice is on for ${account}.`);
|
|
352
|
+
out('');
|
|
353
|
+
out('Endpoint (keep it private, it is your agent\'s key to the record). Use it as the agent\'s RPC address:');
|
|
354
|
+
out(` ${endpoint}`);
|
|
355
|
+
out('Public record:');
|
|
356
|
+
out(` ${witnessBase()}/a/${account}`);
|
|
357
|
+
out('');
|
|
358
|
+
out('The agent signs as usual; Stuntman simulates every transaction it sends there and broadcasts nothing.');
|
|
359
|
+
out('Practice money for this agent: the endpoint accepts stuntman_fund, or use the GAME worker\'s add_practice_money.');
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
const cfg = requireConfig();
|
|
363
|
+
if (args[0] === 'off') {
|
|
364
|
+
delete cfg.witness;
|
|
365
|
+
saveConfig(cfg);
|
|
366
|
+
out('Witness mode is off. Takes are simulated on this machine again. Your witnessed record stays online.');
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const { account, endpoint } = await registerWitness(cfg);
|
|
370
|
+
cfg.witness = endpoint;
|
|
371
|
+
saveConfig(cfg);
|
|
372
|
+
const base = witnessBase();
|
|
373
|
+
const conf = (await fetch(`${base}/api/witness/config`).then((r) => r.json()).catch(() => null));
|
|
374
|
+
out(`Witnessed practice is on for ${account}.`);
|
|
375
|
+
out('');
|
|
376
|
+
out(`Endpoint (keep it private, it is your agent's key to the record):`);
|
|
377
|
+
out(` ${endpoint}`);
|
|
378
|
+
out(`Public record:`);
|
|
379
|
+
out(` ${base}/a/${account}`);
|
|
380
|
+
out('');
|
|
381
|
+
out('The Stuntman MCP tools now send through the witness. Agents that send their own');
|
|
382
|
+
out('transactions: use the endpoint above as the RPC address.');
|
|
383
|
+
out('Practice money on the witness is separate: add some with "stuntman fund ETH 1".');
|
|
384
|
+
if (conf?.freeTakes !== undefined) {
|
|
385
|
+
out('');
|
|
386
|
+
out(conf.billing
|
|
387
|
+
? `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.`
|
|
388
|
+
: `Witnessing is free while billing is off. Once it starts, each agent keeps ${conf.freeTakes} free takes.`);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
295
391
|
async function cmdMcp() {
|
|
296
392
|
const cfg = requireConfig();
|
|
297
393
|
const engine = await createEngine(cfg);
|
|
@@ -332,6 +428,8 @@ async function main() {
|
|
|
332
428
|
return cmdMcp();
|
|
333
429
|
case 'connect':
|
|
334
430
|
return out(connectLines(args[0] ?? 'all'));
|
|
431
|
+
case 'witness':
|
|
432
|
+
return cmdWitness(args, flags);
|
|
335
433
|
default:
|
|
336
434
|
throw new Error(`Unknown command "${cmd}". Run "stuntman help".`);
|
|
337
435
|
}
|
|
@@ -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/game.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Stuntman for Virtuals GAME agents.
|
|
2
|
+
//
|
|
3
|
+
// import { GameAgent } from '@virtuals-protocol/game';
|
|
4
|
+
// import { stuntmanWorker } from 'stuntman/game';
|
|
5
|
+
//
|
|
6
|
+
// const agent = new GameAgent(process.env.GAME_API_KEY, {
|
|
7
|
+
// name: 'My trader',
|
|
8
|
+
// goal: 'Trade on Robinhood Chain',
|
|
9
|
+
// description: '...',
|
|
10
|
+
// workers: [await stuntmanWorker({ endpoint: process.env.STUNTMAN_ENDPOINT })],
|
|
11
|
+
// });
|
|
12
|
+
//
|
|
13
|
+
// The worker gives the agent practice functions: every transaction it sends is
|
|
14
|
+
// played out at the latest block with practice money and never broadcast. With
|
|
15
|
+
// a witness endpoint (from `stuntman witness`), every take is also signed and
|
|
16
|
+
// kept on the agent's public record.
|
|
17
|
+
import { parseUnits } from 'viem';
|
|
18
|
+
import { formatTake } from './report.js';
|
|
19
|
+
import { remoteCall, RemoteError } from './remote.js';
|
|
20
|
+
async function loadGame() {
|
|
21
|
+
const name = '@virtuals-protocol/game';
|
|
22
|
+
try {
|
|
23
|
+
return (await import(name));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw new Error('stuntman/game needs the Virtuals GAME SDK. Install it with: npm install @virtuals-protocol/game');
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const isAddress = (s) => typeof s === 'string' && /^0x[0-9a-fA-F]{40}$/.test(s);
|
|
30
|
+
/** The practice functions as plain async functions, independent of the GAME SDK. */
|
|
31
|
+
export function practiceActions(endpoint) {
|
|
32
|
+
const call = (method, params = []) => remoteCall(endpoint, method, params);
|
|
33
|
+
let account = null;
|
|
34
|
+
const who = async () => (account ??= (await call('stuntman_status')).account);
|
|
35
|
+
return {
|
|
36
|
+
async status() {
|
|
37
|
+
const s = await call('stuntman_status');
|
|
38
|
+
const takes = await call('stuntman_takes', [200]);
|
|
39
|
+
const filled = takes.filter((t) => t.status === 'filled').length;
|
|
40
|
+
const failed = takes.filter((t) => t.status === 'reverted').length;
|
|
41
|
+
const witnessed = /\/w\/[0-9a-f]{48}$/.test(endpoint);
|
|
42
|
+
return [
|
|
43
|
+
`Practicing as ${s.account} on chain ${s.chainId}. Nothing is ever broadcast.`,
|
|
44
|
+
`Recent takes: ${takes.length} (${filled} filled, ${failed} failed).`,
|
|
45
|
+
witnessed ? `Witnessed: every take is signed and kept on the public record at ${new URL(endpoint).origin}/a/${s.account}.` : 'Local practice: takes stay on this machine.',
|
|
46
|
+
].join('\n');
|
|
47
|
+
},
|
|
48
|
+
async balances() {
|
|
49
|
+
const rows = await call('stuntman_balances');
|
|
50
|
+
return rows.map((r) => `${r.symbol}: ${r.formatted}${r.practice ? '' : ' (real balance)'}${r.token === 'ETH' ? '' : ` [${r.token}]`}`).join('\n');
|
|
51
|
+
},
|
|
52
|
+
async send(to, data, value) {
|
|
53
|
+
const from = await who();
|
|
54
|
+
const tx = { from, data: data && /^0x[0-9a-fA-F]*$/.test(data) ? data : '0x' };
|
|
55
|
+
if (to) {
|
|
56
|
+
if (!isAddress(to))
|
|
57
|
+
return { ok: false, text: 'to must be a contract or wallet address (0x followed by 40 characters), or empty to deploy a contract.' };
|
|
58
|
+
tx.to = to;
|
|
59
|
+
}
|
|
60
|
+
if (value) {
|
|
61
|
+
if (!/^[0-9]+$/.test(value))
|
|
62
|
+
return { ok: false, text: 'value must be a whole number of wei, for example 50000000000000000 for 0.05 ETH.' };
|
|
63
|
+
tx.value = `0x${BigInt(value).toString(16)}`;
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const hash = await call('eth_sendTransaction', [tx]);
|
|
67
|
+
const take = (await call('stuntman_takes', [5])).find((t) => t.txHash.toLowerCase() === hash.toLowerCase());
|
|
68
|
+
if (!take)
|
|
69
|
+
return { ok: true, text: `Practice transaction ${hash}. Nothing was broadcast.` };
|
|
70
|
+
return { ok: take.status === 'filled', text: `${formatTake(take)}\nNothing was broadcast.` };
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
const latest = (await call('stuntman_takes', [1]).catch(() => []))[0];
|
|
74
|
+
if (err instanceof RemoteError && latest?.status === 'rejected' && Date.now() - Date.parse(latest.at) < 15_000) {
|
|
75
|
+
return { ok: false, text: `${formatTake(latest)}\nNothing was broadcast.` };
|
|
76
|
+
}
|
|
77
|
+
return { ok: false, text: err.message };
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
async takes(limit = 10) {
|
|
81
|
+
const takes = await call('stuntman_takes', [Math.max(1, Math.min(50, limit))]);
|
|
82
|
+
return takes.length ? takes.map((t) => formatTake(t)).join('\n\n') : 'No takes yet.';
|
|
83
|
+
},
|
|
84
|
+
async fund(asset, amount) {
|
|
85
|
+
if (!asset || !amount)
|
|
86
|
+
return { ok: false, text: 'Give an asset (ETH or a token address) and an amount, for example ETH and 1.' };
|
|
87
|
+
const isEth = asset.toUpperCase() === 'ETH';
|
|
88
|
+
if (!isEth && !isAddress(asset))
|
|
89
|
+
return { ok: false, text: 'asset must be ETH or a token address.' };
|
|
90
|
+
let decimals = 18;
|
|
91
|
+
if (!isEth) {
|
|
92
|
+
const raw = await call('eth_call', [{ to: asset, data: '0x313ce567' }, 'latest']);
|
|
93
|
+
decimals = Number(BigInt(raw));
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
const units = parseUnits(amount, decimals);
|
|
97
|
+
const r = await call('stuntman_fund', [isEth ? 'ETH' : asset, units.toString()]);
|
|
98
|
+
return { ok: true, text: `Added ${amount} ${r.symbol} of practice money.` };
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
const msg = err.message;
|
|
102
|
+
return {
|
|
103
|
+
ok: false,
|
|
104
|
+
text: /method|not found|unsupported/i.test(msg) ? 'This endpoint does not add practice money. Use "stuntman fund" on the machine running it.' : msg,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** A GAME worker with Stuntman's practice functions. */
|
|
111
|
+
export async function stuntmanWorker(options = {}) {
|
|
112
|
+
const endpoint = options.endpoint ?? process.env.STUNTMAN_ENDPOINT ?? 'http://127.0.0.1:8545';
|
|
113
|
+
const game = await loadGame();
|
|
114
|
+
const actions = practiceActions(endpoint);
|
|
115
|
+
const done = (text) => new game.ExecutableGameFunctionResponse(game.ExecutableGameFunctionStatus.Done, text);
|
|
116
|
+
const failed = (text) => new game.ExecutableGameFunctionResponse(game.ExecutableGameFunctionStatus.Failed, text);
|
|
117
|
+
const safe = (fn) => async (args) => {
|
|
118
|
+
try {
|
|
119
|
+
const out = await fn(args);
|
|
120
|
+
return typeof out === 'string' ? done(out) : out.ok ? done(out.text) : failed(out.text);
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
return failed(err.message);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const functions = [
|
|
127
|
+
new game.GameFunction({
|
|
128
|
+
name: 'practice_status',
|
|
129
|
+
description: 'Show the practice account, recent takes and whether takes are witnessed on a public record.',
|
|
130
|
+
args: [],
|
|
131
|
+
executable: safe(() => actions.status()),
|
|
132
|
+
}),
|
|
133
|
+
new game.GameFunction({
|
|
134
|
+
name: 'practice_balances',
|
|
135
|
+
description: 'Practice balances of ETH and tokens. These are practice money, not real funds.',
|
|
136
|
+
args: [],
|
|
137
|
+
executable: safe(() => actions.balances()),
|
|
138
|
+
}),
|
|
139
|
+
new game.GameFunction({
|
|
140
|
+
name: 'send_practice_transaction',
|
|
141
|
+
description: 'Send a transaction in practice: it is simulated at the latest block of Robinhood Chain with real prices and practice money, and never broadcast. Returns whether it filled or failed and what changed.',
|
|
142
|
+
args: [
|
|
143
|
+
{ name: 'to', description: 'Contract or wallet address. Leave empty to deploy a contract.', optional: true },
|
|
144
|
+
{ name: 'data', description: 'Calldata as 0x hex. Empty for a plain ETH send.', optional: true },
|
|
145
|
+
{ name: 'value', description: 'ETH to send, in wei as a whole number.', optional: true },
|
|
146
|
+
],
|
|
147
|
+
executable: safe((a) => actions.send(a.to, a.data, a.value)),
|
|
148
|
+
}),
|
|
149
|
+
new game.GameFunction({
|
|
150
|
+
name: 'list_practice_takes',
|
|
151
|
+
description: 'Recent practice takes, newest first, with results and reasons for failures.',
|
|
152
|
+
args: [{ name: 'limit', description: 'How many takes, up to 50. Default 10.', optional: true }],
|
|
153
|
+
executable: safe((a) => actions.takes(Number(a.limit ?? 10) || 10)),
|
|
154
|
+
}),
|
|
155
|
+
new game.GameFunction({
|
|
156
|
+
name: 'add_practice_money',
|
|
157
|
+
description: 'Add practice money (witness endpoints only). It shows on the public record.',
|
|
158
|
+
args: [
|
|
159
|
+
{ name: 'asset', description: 'ETH or a token address' },
|
|
160
|
+
{ name: 'amount', description: 'Amount in whole units, for example 1 or 250.5' },
|
|
161
|
+
],
|
|
162
|
+
executable: safe((a) => actions.fund(a.asset, a.amount)),
|
|
163
|
+
}),
|
|
164
|
+
];
|
|
165
|
+
return new game.GameWorker({
|
|
166
|
+
id: options.id ?? 'stuntman_practice',
|
|
167
|
+
name: options.name ?? 'Stuntman practice',
|
|
168
|
+
description: options.description ??
|
|
169
|
+
'Practices trades on Robinhood Chain before they are real: transactions are simulated at the latest block with real prices and practice money, and never broadcast.',
|
|
170
|
+
functions,
|
|
171
|
+
getEnvironment: async () => ({ practice: true, endpoint: new URL(endpoint).origin }),
|
|
172
|
+
});
|
|
173
|
+
}
|
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
|
+
}
|