stuntman 0.1.1 → 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/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,9 +24,12 @@ 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
- description: 'Returns the address this agent is practising as and the chain it is on. Use it wherever an app asks for your wallet address.',
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.',
29
33
  inputSchema: {},
30
34
  annotations: { readOnlyHint: true },
31
35
  }, async () => text(JSON.stringify({ address: checksum(cfg.account), chainId: cfg.chainId, practice: true, mode: cfg.mode })));
@@ -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,9 +123,9 @@ 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
- return text('No takes yet. Send a transaction to start practising.');
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'));
91
130
  });
92
131
  server.registerTool('get_take', {
@@ -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
- `Practising as ${checksum(cfg.account)} (${cfg.mode === 'shadow' ? 'your wallet, watch only' : 'practice key'}) on chain ${cfg.chainId}.`,
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/overlay.js CHANGED
@@ -2,10 +2,19 @@
2
2
  // chain "looks" like the practice balances wherever the agent or an app reads it.
3
3
  import { numberToHex } from 'viem';
4
4
  import { PERMIT2_ADDRESS, lower, word } from './chain.js';
5
- import { packPermit2 } from './slots.js';
5
+ import { encodeField, packPermit2 } from './slots.js';
6
6
  export function slotKey(kind, token, holder, spender) {
7
7
  return [kind, lower(token), lower(holder), spender ? lower(spender) : ''].filter(Boolean).join(':');
8
8
  }
9
+ /** The slot and word that store `value` where `stored` says it lives. */
10
+ export function slotWrite(stored, value) {
11
+ if (!stored)
12
+ return null;
13
+ if (typeof stored === 'string')
14
+ return [stored, word(value)];
15
+ const encoded = encodeField(stored, value);
16
+ return encoded ? [stored.slot, encoded] : null;
17
+ }
9
18
  export function buildOverrides(state) {
10
19
  const out = {};
11
20
  const account = state.account;
@@ -20,15 +29,15 @@ export function buildOverrides(state) {
20
29
  out[lower(account)] = { ...(out[lower(account)] ?? {}), balance: numberToHex(BigInt(acc.eth)) };
21
30
  }
22
31
  for (const [token, amount] of Object.entries(acc.tokens)) {
23
- const slot = state.slots[slotKey('balance', token, account)];
24
- if (slot)
25
- add(token, slot, word(BigInt(amount)));
32
+ const w = slotWrite(state.slots[slotKey('balance', token, account)], BigInt(amount));
33
+ if (w)
34
+ add(token, w[0], w[1]);
26
35
  }
27
36
  for (const [token, spenders] of Object.entries(acc.allowances)) {
28
37
  for (const [spender, amount] of Object.entries(spenders)) {
29
- const slot = state.slots[slotKey('allowance', token, account, spender)];
30
- if (slot)
31
- add(token, slot, word(BigInt(amount)));
38
+ const w = slotWrite(state.slots[slotKey('allowance', token, account, spender)], BigInt(amount));
39
+ if (w)
40
+ add(token, w[0], w[1]);
32
41
  }
33
42
  }
34
43
  // Contracts deployed in practice exist only here: their code and storage.
@@ -40,7 +49,7 @@ export function buildOverrides(state) {
40
49
  for (const [token, spenders] of Object.entries(acc.permit2)) {
41
50
  for (const [spender, a] of Object.entries(spenders)) {
42
51
  const slot = state.slots[slotKey('permit2', token, account, spender)];
43
- if (slot)
52
+ if (typeof slot === 'string')
44
53
  add(PERMIT2_ADDRESS, slot, packPermit2(BigInt(a.amount), BigInt(a.expiration), BigInt(a.nonce)));
45
54
  }
46
55
  }
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/report.js CHANGED
@@ -27,7 +27,8 @@ export function formatTake(take, detailed = false) {
27
27
  else if (take.gasCostWei) {
28
28
  lines.push(` Gas: ${Number(take.gasUsed ?? 0).toLocaleString('en-US')} units, ${fmt(BigInt(take.gasCostWei), 18, 9)} ETH`);
29
29
  }
30
- if (take.reason && take.status !== 'filled')
30
+ // A rejected take's summary already says why.
31
+ if (take.reason && take.status === 'reverted')
31
32
  lines.push(` Why: ${take.reason}`);
32
33
  if (detailed) {
33
34
  if (take.intent)
@@ -38,7 +39,7 @@ export function formatTake(take, detailed = false) {
38
39
  lines.push(` Contract: ${take.contractAddress}`);
39
40
  if (take.request.value !== '0')
40
41
  lines.push(` Value: ${fmt(BigInt(take.request.value), 18)} ETH`);
41
- lines.push(` Block: ${BigInt(take.blockNumber).toString()} Simulated with: ${take.backend}`);
42
+ lines.push(` Block: ${BigInt(take.blockNumber).toString()}${take.backend === 'none' ? '' : ` Simulated with: ${take.backend}`}`);
42
43
  lines.push(` Practice hash: ${take.txHash}`);
43
44
  lines.push(` At: ${take.at}`);
44
45
  }
package/dist/slots.js CHANGED
@@ -7,14 +7,38 @@
7
7
  // 2. Otherwise try the common layouts (Solidity and Vyper mappings at slots
8
8
  // 0..63, OpenZeppelin v5 namespaced storage, Solady).
9
9
  // Every candidate is confirmed by overriding it with a probe value and checking
10
- // that the read returns that value. Nothing unconfirmed is ever used.
10
+ // that the read returns that value, or a byte range of it: some tokens pack the
11
+ // balance into part of a slot (Paxos USDG keeps a uint64 balance beside
12
+ // rewards data). Nothing unconfirmed is ever used.
11
13
  import { concat, encodeAbiParameters, encodeFunctionData, decodeFunctionResult, keccak256, pad } from 'viem';
12
14
  import { RpcError } from './rpc.js';
13
15
  import { ERC20_ABI, PERMIT2_ABI, PERMIT2_ADDRESS, checksum, word } from './chain.js';
14
- const PROBE = 0x5354554e544d414e000000000000002an; // "STUNTMAN" ... 42
15
16
  const PERMIT2_PROBE_AMOUNT = 0x5354554e544d414e0000002an;
16
17
  const PERMIT2_PROBE_EXPIRATION = 0x5354554en;
17
18
  const PERMIT2_PROBE_NONCE = 0x2an;
19
+ // 32 bytes with no zero byte and no repeats, so any byte range of it is unique.
20
+ const FIELD_PROBE = 0x53a4c7e1f29b6d0e8f71c3a5d2b94e67a1f8c3e5b7d9f2a4c6e8b1d3f5a7c9e2n;
21
+ const MIN_FIELD_BYTES = 4;
22
+ /** The byte range of FIELD_PROBE that a read returned, if any. Full width first. */
23
+ export function fieldOf(returned) {
24
+ for (let bytes = 32; bytes >= MIN_FIELD_BYTES; bytes--) {
25
+ for (let offset = 0; offset + bytes <= 32; offset++) {
26
+ const mask = (1n << BigInt(bytes * 8)) - 1n;
27
+ if (((FIELD_PROBE >> BigInt(offset * 8)) & mask) === returned)
28
+ return { offset, bytes };
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+ /** The slot word that stores `value` in `field`, keeping the slot's other bits. */
34
+ export function encodeField(field, value) {
35
+ const width = BigInt(field.bytes * 8);
36
+ if (value < 0n || value >= 1n << width)
37
+ return null;
38
+ const shift = BigInt(field.offset * 8);
39
+ const mask = ((1n << width) - 1n) << shift;
40
+ return word((BigInt(field.rest) & ~mask) | (value << shift));
41
+ }
18
42
  const OZ_ERC20_NAMESPACE = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00n;
19
43
  const SOLADY_BALANCE_SEED = '0x87a211a2';
20
44
  const SOLADY_ALLOWANCE_SEED = '0x7f5e9f20';
@@ -108,39 +132,66 @@ async function confirm(rpc, target, data, candidates, probe, matches) {
108
132
  }
109
133
  return null;
110
134
  }
111
- export async function findBalanceSlot(rpc, caps, token, holder) {
112
- if (!caps.stateOverride)
113
- return null;
114
- const data = encodeFunctionData({ abi: ERC20_ABI, functionName: 'balanceOf', args: [checksum(holder)] });
115
- const probe = word(PROBE);
116
- const isProbe = (ret) => decodeFunctionResult({ abi: ERC20_ABI, functionName: 'balanceOf', data: ret }) === PROBE;
117
- const traced = caps.debugTraceCall ? await tracedSlots(rpc, token, data) : [];
135
+ /** Like confirm, but also finds a value packed into part of a slot. */
136
+ async function confirmField(rpc, target, data, candidates) {
137
+ const probe = word(FIELD_PROBE);
138
+ for (let i = 0; i < candidates.length; i += 32) {
139
+ const chunk = candidates.slice(i, i + 32);
140
+ const results = await rpc.batch(chunk.map((slot) => ({
141
+ method: 'eth_call',
142
+ params: [{ to: target, data }, 'latest', { [target]: { stateDiff: { [slot]: probe } } }],
143
+ })));
144
+ for (let j = 0; j < chunk.length; j++) {
145
+ const r = results[j];
146
+ if (r instanceof RpcError || typeof r !== 'string' || r.length < 66)
147
+ continue;
148
+ const field = fieldOf(BigInt(r.slice(0, 66)));
149
+ if (!field)
150
+ continue;
151
+ const slot = chunk[j];
152
+ const rest = field.bytes === 32 ? word(0n) : ((await rpc.request('eth_getStorageAt', [target, slot, 'latest']).catch(() => null)) ?? null);
153
+ if (rest === null)
154
+ continue;
155
+ // Confirm the encoding round-trips with a second, ordinary value.
156
+ const check = 123456789n;
157
+ const encoded = encodeField({ ...field, rest }, check);
158
+ if (!encoded)
159
+ continue;
160
+ const back = await rpc
161
+ .request('eth_call', [{ to: target, data }, 'latest', { [target]: { stateDiff: { [slot]: encoded } } }])
162
+ .catch(() => null);
163
+ if (!back || back.length < 66 || BigInt(back.slice(0, 66)) !== check)
164
+ continue;
165
+ return { slot, offset: field.offset, bytes: field.bytes, rest: pad(rest, { size: 32 }) };
166
+ }
167
+ }
168
+ return null;
169
+ }
170
+ function ordered(traced, candidates) {
118
171
  const seen = new Set();
119
- const ordered = [...traced, ...balanceCandidates(holder)].filter((s) => {
120
- const k = pad(s, { size: 32 }).toLowerCase();
172
+ return [...traced, ...candidates]
173
+ .map((s) => pad(s, { size: 32 }))
174
+ .filter((s) => {
175
+ const k = s.toLowerCase();
121
176
  if (seen.has(k))
122
177
  return false;
123
178
  seen.add(k);
124
179
  return true;
125
180
  });
126
- return confirm(rpc, token, data, ordered.map((s) => pad(s, { size: 32 })), probe, isProbe);
181
+ }
182
+ export async function findBalanceSlot(rpc, caps, token, holder) {
183
+ if (!caps.stateOverride)
184
+ return null;
185
+ const data = encodeFunctionData({ abi: ERC20_ABI, functionName: 'balanceOf', args: [checksum(holder)] });
186
+ const traced = caps.debugTraceCall ? await tracedSlots(rpc, token, data) : [];
187
+ return confirmField(rpc, token, data, ordered(traced, balanceCandidates(holder)));
127
188
  }
128
189
  export async function findAllowanceSlot(rpc, caps, token, owner, spender) {
129
190
  if (!caps.stateOverride)
130
191
  return null;
131
192
  const data = encodeFunctionData({ abi: ERC20_ABI, functionName: 'allowance', args: [checksum(owner), checksum(spender)] });
132
- const probe = word(PROBE);
133
- const isProbe = (ret) => decodeFunctionResult({ abi: ERC20_ABI, functionName: 'allowance', data: ret }) === PROBE;
134
193
  const traced = caps.debugTraceCall ? await tracedSlots(rpc, token, data) : [];
135
- const seen = new Set();
136
- const ordered = [...traced, ...allowanceCandidates(owner, spender)].filter((s) => {
137
- const k = pad(s, { size: 32 }).toLowerCase();
138
- if (seen.has(k))
139
- return false;
140
- seen.add(k);
141
- return true;
142
- });
143
- return confirm(rpc, token, data, ordered.map((s) => pad(s, { size: 32 })), probe, isProbe);
194
+ return confirmField(rpc, token, data, ordered(traced, allowanceCandidates(owner, spender)));
144
195
  }
145
196
  export async function confirmPermit2Slot(rpc, caps, owner, token, spender) {
146
197
  if (!caps.stateOverride)
package/dist/store.js CHANGED
@@ -2,8 +2,11 @@
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';
8
+ /** Bumped when slot search learns new layouts, so earlier misses are tried again. */
9
+ export const SLOT_SEARCH_VERSION = 2;
7
10
  function emptyAccount() {
8
11
  return { tokens: {}, allowances: {}, permit2: {} };
9
12
  }
@@ -15,6 +18,7 @@ export function freshState(chainId, account) {
15
18
  accountState: emptyAccount(),
16
19
  tokens: {},
17
20
  slots: {},
21
+ slotSearch: SLOT_SEARCH_VERSION,
18
22
  takeCount: 0,
19
23
  hashes: {},
20
24
  contracts: {},
@@ -31,8 +35,16 @@ function lockPath() {
31
35
  return join(ensureHome(), 'state.lock');
32
36
  }
33
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));
34
43
  /** Run fn while holding the cross-process lock. */
35
44
  export async function withLock(fn) {
45
+ // The hosted witness locks each agent in its database instead.
46
+ if (memory.getStore())
47
+ return fn();
36
48
  const path = lockPath();
37
49
  const started = Date.now();
38
50
  for (;;) {
@@ -65,10 +77,13 @@ export async function withLock(fn) {
65
77
  }
66
78
  }
67
79
  export function readState(chainId, account) {
68
- const path = statePath();
69
- if (!existsSync(path))
80
+ const mem = memory.getStore();
81
+ if (mem && !mem.state)
82
+ return freshState(chainId, account);
83
+ const path = mem ? '' : statePath();
84
+ if (!mem && !existsSync(path))
70
85
  return freshState(chainId, account);
71
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
86
+ const parsed = mem ? clone(mem.state) : JSON.parse(readFileSync(path, 'utf8'));
72
87
  // A state for a different account or chain is stale: start clean.
73
88
  if (parsed.account?.toLowerCase() !== account.toLowerCase() || parsed.chainId !== chainId) {
74
89
  return freshState(chainId, account);
@@ -79,21 +94,41 @@ export function readState(chainId, account) {
79
94
  parsed.accountState.permit2 ??= {};
80
95
  parsed.tokens ??= {};
81
96
  parsed.slots ??= {};
97
+ if ((parsed.slotSearch ?? 1) < SLOT_SEARCH_VERSION) {
98
+ for (const [k, v] of Object.entries(parsed.slots))
99
+ if (v === null)
100
+ delete parsed.slots[k];
101
+ parsed.slotSearch = SLOT_SEARCH_VERSION;
102
+ }
82
103
  parsed.hashes ??= {};
83
104
  parsed.contracts ??= {};
84
105
  parsed.known ??= [];
85
106
  return parsed;
86
107
  }
87
108
  export function writeState(state) {
109
+ const mem = memory.getStore();
110
+ if (mem) {
111
+ mem.state = clone(state);
112
+ return;
113
+ }
88
114
  const path = statePath();
89
115
  const tmp = `${path}.${process.pid}.tmp`;
90
116
  writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });
91
117
  renameSync(tmp, path);
92
118
  }
93
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
+ }
94
126
  appendFileSync(takesPath(), JSON.stringify(take) + '\n', { mode: 0o600 });
95
127
  }
96
128
  export function readTakes() {
129
+ const mem = memory.getStore();
130
+ if (mem)
131
+ return clone(mem.takes);
97
132
  const path = takesPath();
98
133
  if (!existsSync(path))
99
134
  return [];
@@ -113,6 +148,9 @@ export function readTakes() {
113
148
  }
114
149
  export function findTakeByHash(hash) {
115
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);
116
154
  return readTakes().find((t) => t.txHash.toLowerCase() === lower);
117
155
  }
118
156
  export function resetPractice(chainId, account) {
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.1.1';
1
+ export const VERSION = '0.2.0';