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/dist/witness.js
ADDED
|
@@ -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
|
|
3
|
+
"version": "0.2.1",
|
|
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"
|
|
@@ -49,7 +50,20 @@
|
|
|
49
50
|
"devDependencies": {
|
|
50
51
|
"@foundry-rs/anvil": "^1.7.1",
|
|
51
52
|
"@types/node": "^26.6.11",
|
|
53
|
+
"@virtuals-protocol/game": "^0.1.14",
|
|
52
54
|
"solc": "^0.8.39",
|
|
53
55
|
"typescript": "^7.0.2"
|
|
56
|
+
},
|
|
57
|
+
"exports": {
|
|
58
|
+
"./game": "./dist/game.js",
|
|
59
|
+
"./package.json": "./package.json"
|
|
60
|
+
},
|
|
61
|
+
"peerDependencies": {
|
|
62
|
+
"@virtuals-protocol/game": ">=0.1.14"
|
|
63
|
+
},
|
|
64
|
+
"peerDependenciesMeta": {
|
|
65
|
+
"@virtuals-protocol/game": {
|
|
66
|
+
"optional": true
|
|
67
|
+
}
|
|
54
68
|
}
|
|
55
69
|
}
|