sigild 0.0.12 → 0.0.14

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.
Files changed (133) hide show
  1. package/README.md +63 -3
  2. package/THREAT_MODEL.md +4 -0
  3. package/dist/src/audit/index.d.ts +2 -1
  4. package/dist/src/audit/index.d.ts.map +1 -1
  5. package/dist/src/audit/index.js +1 -0
  6. package/dist/src/audit/index.js.map +1 -1
  7. package/dist/src/audit/log.d.ts +52 -3
  8. package/dist/src/audit/log.d.ts.map +1 -1
  9. package/dist/src/audit/log.js +226 -40
  10. package/dist/src/audit/log.js.map +1 -1
  11. package/dist/src/bin/sigil-mcp.js +79 -9
  12. package/dist/src/bin/sigil-mcp.js.map +1 -1
  13. package/dist/src/cli/main.d.ts.map +1 -1
  14. package/dist/src/cli/main.js +35 -1
  15. package/dist/src/cli/main.js.map +1 -1
  16. package/dist/src/cli/paths.d.ts +4 -0
  17. package/dist/src/cli/paths.d.ts.map +1 -1
  18. package/dist/src/cli/paths.js +2 -0
  19. package/dist/src/cli/paths.js.map +1 -1
  20. package/dist/src/cli/portal.d.ts.map +1 -1
  21. package/dist/src/cli/portal.js +11 -1
  22. package/dist/src/cli/portal.js.map +1 -1
  23. package/dist/src/confirm/config.d.ts +19 -0
  24. package/dist/src/confirm/config.d.ts.map +1 -1
  25. package/dist/src/confirm/config.js +48 -0
  26. package/dist/src/confirm/config.js.map +1 -1
  27. package/dist/src/confirm/index.d.ts +1 -1
  28. package/dist/src/confirm/index.d.ts.map +1 -1
  29. package/dist/src/confirm/index.js.map +1 -1
  30. package/dist/src/daemon/handles.d.ts +6 -0
  31. package/dist/src/daemon/handles.d.ts.map +1 -1
  32. package/dist/src/daemon/handles.js +11 -0
  33. package/dist/src/daemon/handles.js.map +1 -1
  34. package/dist/src/daemon/index.d.ts +1 -1
  35. package/dist/src/daemon/index.d.ts.map +1 -1
  36. package/dist/src/daemon/index.js.map +1 -1
  37. package/dist/src/daemon/methods.d.ts +29 -1
  38. package/dist/src/daemon/methods.d.ts.map +1 -1
  39. package/dist/src/daemon/methods.js +293 -27
  40. package/dist/src/daemon/methods.js.map +1 -1
  41. package/dist/src/eth/abi.d.ts +82 -0
  42. package/dist/src/eth/abi.d.ts.map +1 -0
  43. package/dist/src/eth/abi.js +328 -0
  44. package/dist/src/eth/abi.js.map +1 -0
  45. package/dist/src/eth/index.d.ts +1 -0
  46. package/dist/src/eth/index.d.ts.map +1 -1
  47. package/dist/src/eth/index.js +1 -0
  48. package/dist/src/eth/index.js.map +1 -1
  49. package/dist/src/fs/index.d.ts +2 -0
  50. package/dist/src/fs/index.d.ts.map +1 -0
  51. package/dist/src/fs/index.js +2 -0
  52. package/dist/src/fs/index.js.map +1 -0
  53. package/dist/src/fs/lock.d.ts +84 -0
  54. package/dist/src/fs/lock.d.ts.map +1 -0
  55. package/dist/src/fs/lock.js +329 -0
  56. package/dist/src/fs/lock.js.map +1 -0
  57. package/dist/src/mcp/parent-watchdog.d.ts +31 -0
  58. package/dist/src/mcp/parent-watchdog.d.ts.map +1 -0
  59. package/dist/src/mcp/parent-watchdog.js +35 -0
  60. package/dist/src/mcp/parent-watchdog.js.map +1 -0
  61. package/dist/src/mcp/server.d.ts +7 -0
  62. package/dist/src/mcp/server.d.ts.map +1 -1
  63. package/dist/src/mcp/server.js +13 -2
  64. package/dist/src/mcp/server.js.map +1 -1
  65. package/dist/src/mcp/tools.d.ts.map +1 -1
  66. package/dist/src/mcp/tools.js +21 -1
  67. package/dist/src/mcp/tools.js.map +1 -1
  68. package/dist/src/policy/evaluate.d.ts.map +1 -1
  69. package/dist/src/policy/evaluate.js +69 -4
  70. package/dist/src/policy/evaluate.js.map +1 -1
  71. package/dist/src/policy/index.d.ts +2 -0
  72. package/dist/src/policy/index.d.ts.map +1 -1
  73. package/dist/src/policy/index.js +2 -0
  74. package/dist/src/policy/index.js.map +1 -1
  75. package/dist/src/policy/ledger.d.ts +84 -0
  76. package/dist/src/policy/ledger.d.ts.map +1 -0
  77. package/dist/src/policy/ledger.js +276 -0
  78. package/dist/src/policy/ledger.js.map +1 -0
  79. package/dist/src/policy/loader.d.ts.map +1 -1
  80. package/dist/src/policy/loader.js +54 -0
  81. package/dist/src/policy/loader.js.map +1 -1
  82. package/dist/src/policy/template.d.ts +2 -2
  83. package/dist/src/policy/template.d.ts.map +1 -1
  84. package/dist/src/policy/template.js +52 -0
  85. package/dist/src/policy/template.js.map +1 -1
  86. package/dist/src/policy/types.d.ts +42 -0
  87. package/dist/src/policy/types.d.ts.map +1 -1
  88. package/dist/src/policy/types.js.map +1 -1
  89. package/dist/src/policy/window.d.ts +22 -0
  90. package/dist/src/policy/window.d.ts.map +1 -0
  91. package/dist/src/policy/window.js +66 -0
  92. package/dist/src/policy/window.js.map +1 -0
  93. package/dist/src/preview/abi-dir.d.ts +50 -0
  94. package/dist/src/preview/abi-dir.d.ts.map +1 -0
  95. package/dist/src/preview/abi-dir.js +175 -0
  96. package/dist/src/preview/abi-dir.js.map +1 -0
  97. package/dist/src/preview/decode.d.ts +26 -0
  98. package/dist/src/preview/decode.d.ts.map +1 -0
  99. package/dist/src/preview/decode.js +110 -0
  100. package/dist/src/preview/decode.js.map +1 -0
  101. package/dist/src/preview/format.d.ts +45 -0
  102. package/dist/src/preview/format.d.ts.map +1 -0
  103. package/dist/src/preview/format.js +222 -0
  104. package/dist/src/preview/format.js.map +1 -0
  105. package/dist/src/preview/index.d.ts +60 -0
  106. package/dist/src/preview/index.d.ts.map +1 -0
  107. package/dist/src/preview/index.js +163 -0
  108. package/dist/src/preview/index.js.map +1 -0
  109. package/dist/src/preview/known.d.ts +74 -0
  110. package/dist/src/preview/known.d.ts.map +1 -0
  111. package/dist/src/preview/known.js +425 -0
  112. package/dist/src/preview/known.js.map +1 -0
  113. package/dist/src/preview/simulate.d.ts +156 -0
  114. package/dist/src/preview/simulate.d.ts.map +1 -0
  115. package/dist/src/preview/simulate.js +768 -0
  116. package/dist/src/preview/simulate.js.map +1 -0
  117. package/dist/src/preview/simulators.d.ts +39 -0
  118. package/dist/src/preview/simulators.d.ts.map +1 -0
  119. package/dist/src/preview/simulators.js +71 -0
  120. package/dist/src/preview/simulators.js.map +1 -0
  121. package/dist/src/preview/trust.d.ts +49 -0
  122. package/dist/src/preview/trust.d.ts.map +1 -0
  123. package/dist/src/preview/trust.js +279 -0
  124. package/dist/src/preview/trust.js.map +1 -0
  125. package/dist/src/preview/types.d.ts +69 -0
  126. package/dist/src/preview/types.d.ts.map +1 -0
  127. package/dist/src/preview/types.js +11 -0
  128. package/dist/src/preview/types.js.map +1 -0
  129. package/dist/src/preview/units.d.ts +75 -0
  130. package/dist/src/preview/units.d.ts.map +1 -0
  131. package/dist/src/preview/units.js +228 -0
  132. package/dist/src/preview/units.js.map +1 -0
  133. package/package.json +5 -5
@@ -0,0 +1,768 @@
1
+ import { AbiDecodeError, decodeAbiParameters } from '../eth/abi.js';
2
+ import { UpstreamRpcError } from '../rpc/upstream.js';
3
+ import { EVENT_TOPICS } from './known.js';
4
+ import { hexQuantity, MAX_QTY_HEX_DIGITS, sanitizeSymbol, ZERO_ADDRESS } from './units.js';
5
+ /**
6
+ * Dry-run a transaction on the user's configured RPC node and summarize
7
+ * what it would do to the portal: status, gas, revert reason, native and
8
+ * token balance deltas, approvals granted.
9
+ *
10
+ * Primary primitive: eth_simulateV1 (one call; geth, reth, anvil and the
11
+ * big hosted providers serve it) with `traceTransfers`, which also reports
12
+ * native ETH movements as synthetic ERC-20-style Transfer logs. Nodes that
13
+ * don't serve it get an eth_call + eth_estimateGas fallback: status and gas
14
+ * only, balance changes unknown.
15
+ *
16
+ * Never throws. Any transport failure, timeout or malformed node response
17
+ * becomes `{ status: 'unavailable', reason }` — the caller decides whether
18
+ * that matters (policy `require_simulation`) or is just a warning.
19
+ *
20
+ * Trust: the node is the user's own choice and the tx would be broadcast
21
+ * there anyway, but its answer is not authenticated. Logs are whatever the
22
+ * simulated contracts chose to emit — a scam token can emit a Transfer it
23
+ * never performed, and call itself "USDC". The result is a strong hint for
24
+ * a human, not a proof.
25
+ */
26
+ export const DEFAULT_SIM_TIMEOUT_MS = 15_000;
27
+ /** Most tokens whose symbol()/decimals() we look up per simulation. */
28
+ const MAX_META_TOKENS = 10;
29
+ /** Transfers kept for the long-form listing. */
30
+ const MAX_TRANSFERS = 32;
31
+ /** Intrinsic gas of the cheapest possible transaction. */
32
+ const MIN_GAS = 21000n;
33
+ /**
34
+ * Addresses traceTransfers uses for synthetic native-ETH Transfer logs.
35
+ * geth emits them from ERC-7528's 0xEeee…EEeE, reth (seen on v2.11 against
36
+ * Sepolia) from 0xffff…fffe, and some implementations and docs use the zero
37
+ * address. All are treated as native ETH — none can host a real token
38
+ * contract emitting events (the two high addresses are precompile-range
39
+ * reserved; the zero address has no code).
40
+ */
41
+ const NATIVE_SENTINELS = new Set([
42
+ ZERO_ADDRESS,
43
+ '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
44
+ '0xfffffffffffffffffffffffffffffffffffffffe',
45
+ ]);
46
+ /**
47
+ * A call that reverts with no data while having burned (almost) all of its
48
+ * gas limit ran out of gas: EIP-150 keeps 1/64 for the caller, so a true
49
+ * out-of-gas lands just under the limit rather than exactly on it. A
50
+ * real revert with no reason string stops well short. Seen live: a USDC
51
+ * approve on Sepolia needs ~140k gas; with gas_limit 100000 reth reported
52
+ * status 0x0, data 0x, gasUsed 98844 — a bare "execution reverted" that
53
+ * would send the human chasing a contract bug instead of a gas limit.
54
+ */
55
+ const OOG_NUM = 95n;
56
+ const OOG_DEN = 100n;
57
+ export function outOfGasReason(gasUsed, gasLimit) {
58
+ if (gasUsed === null || gasLimit <= 0n)
59
+ return null;
60
+ if (gasUsed * OOG_DEN < gasLimit * OOG_NUM)
61
+ return null;
62
+ return `likely out of gas (used ${gasUsed} of the ${gasLimit} gas limit — raise gasLimit)`;
63
+ }
64
+ export async function simulateTransaction(tx, from, upstream, opts = {}) {
65
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_SIM_TIMEOUT_MS;
66
+ // A gas limit below the intrinsic 21000 can never be included; and with
67
+ // 0 the node would substitute its own limit, simulating a different tx
68
+ // than the one being signed. Unavailable, so require_simulation denies.
69
+ const gas = BigInt(tx.gasLimit);
70
+ if (gas < MIN_GAS) {
71
+ return {
72
+ status: 'unavailable',
73
+ reason: gas === 0n
74
+ ? 'gasLimit 0 cannot be simulated or sent'
75
+ : `gasLimit ${gas} is below the 21000 intrinsic minimum and cannot be simulated or sent`,
76
+ };
77
+ }
78
+ const call = (method, params) => withTimeout(upstream.call(method, params), timeoutMs, `${method} timed out after ${timeoutMs} ms`);
79
+ // Phase 1 — execution (eth_simulateV1 or the fallback, incl. the
80
+ // fee-stripped retry), bounded at 2× the per-call timeout. Only this
81
+ // phase can make the simulation 'unavailable'.
82
+ const running = execute(tx, from.toLowerCase(), call);
83
+ running.catch(() => {
84
+ /* settled below or abandoned after the overall timeout */
85
+ });
86
+ let sim;
87
+ try {
88
+ sim = await withTimeout(running, timeoutMs * 2, `simulation timed out after ${timeoutMs * 2} ms`);
89
+ }
90
+ catch (err) {
91
+ return { status: 'unavailable', reason: errText(err) };
92
+ }
93
+ // Phase 2 — token metadata, with its own budget. The status is known by
94
+ // now and nothing here may turn a known revert (or success) into
95
+ // 'unavailable': a slow or failing lookup just leaves amounts raw.
96
+ const wanted = [];
97
+ const want = (t) => {
98
+ if (t === null || NATIVE_SENTINELS.has(t) || wanted.includes(t))
99
+ return;
100
+ if (wanted.length < MAX_META_TOKENS)
101
+ wanted.push(t);
102
+ };
103
+ for (const t of opts.extraTokens ?? [])
104
+ want(t.toLowerCase());
105
+ for (const c of sim.changes?.erc20 ?? [])
106
+ want(c.token);
107
+ for (const t of sim.transfers ?? [])
108
+ if (t.standard === 'erc20')
109
+ want(t.token);
110
+ for (const ap of sim.approvals ?? [])
111
+ if (ap.standard === 'erc20')
112
+ want(ap.token);
113
+ if (wanted.length === 0)
114
+ return sim;
115
+ let unreachable = false;
116
+ const lookups = Promise.all(wanted.map(async (t) => [t, await fetchTokenMeta(t, call, () => (unreachable = true))]));
117
+ lookups.catch(() => {
118
+ /* abandoned after the metadata budget */
119
+ });
120
+ try {
121
+ const entries = await withTimeout(lookups, timeoutMs, 'token metadata timed out');
122
+ const tokenMeta = {};
123
+ for (const [t, m] of entries) {
124
+ if (m.symbol !== undefined || m.decimals !== undefined)
125
+ tokenMeta[t] = m;
126
+ }
127
+ const notes = unreachable ? [...sim.notes, 'token metadata unavailable'] : sim.notes;
128
+ return { ...sim, notes, tokenMeta };
129
+ }
130
+ catch {
131
+ return { ...sim, notes: [...sim.notes, 'token metadata unavailable'] };
132
+ }
133
+ }
134
+ /** Phase 1: run the call on the node and analyse its logs. No metadata. */
135
+ async function execute(tx, from, call) {
136
+ const to = tx.to === null ? null : tx.to.toLowerCase();
137
+ const value = BigInt(tx.value);
138
+ const dataHex = typeof tx.data === 'string' ? tx.data.toLowerCase() : '0x' + tx.data.toString('hex');
139
+ const gas = BigInt(tx.gasLimit);
140
+ // Simulate exactly the parameters that will be signed. A contract can
141
+ // branch on tx.gasprice, gasleft() or the nonce, so a call built from
142
+ // from/to/value/data alone is a different transaction.
143
+ const base = {
144
+ from,
145
+ ...(to !== null ? { to } : {}),
146
+ value: qtyHex(value),
147
+ data: dataHex,
148
+ gas: qtyHex(gas),
149
+ nonce: qtyHex(BigInt(tx.nonce)),
150
+ ...(tx.type === 'eip1559'
151
+ ? {
152
+ accessList: (tx.accessList ?? []).map((a) => ({
153
+ address: a.address.toLowerCase(),
154
+ storageKeys: a.storageKeys.map((k) => k.toLowerCase()),
155
+ })),
156
+ }
157
+ : {}),
158
+ };
159
+ const feeFields = tx.type === 'eip1559'
160
+ ? {
161
+ maxFeePerGas: qtyHex(BigInt(tx.maxFeePerGas)),
162
+ maxPriorityFeePerGas: qtyHex(BigInt(tx.maxPriorityFeePerGas)),
163
+ }
164
+ : { gasPrice: qtyHex(BigInt(tx.gasPrice)) };
165
+ const full = { ...base, ...feeFields };
166
+ let callObj = full;
167
+ const notes = [];
168
+ let faithful = true;
169
+ /**
170
+ * Some nodes (anvil, verified) enforce balance ≥ gas × price + value even
171
+ * with validation:false once fee fields are present; others (reth) don't.
172
+ * When the node refuses for insufficient funds, retry ONCE without the
173
+ * fee fields and say so — the simulation then saw tx.gasprice = 0. If the
174
+ * retry is refused too, the sender can't even cover the value: that error
175
+ * stands.
176
+ */
177
+ const viaNode = async (method, params) => {
178
+ try {
179
+ return await call(method, params(callObj));
180
+ }
181
+ catch (e) {
182
+ if (callObj !== full || !isInsufficientFunds(e))
183
+ throw e;
184
+ callObj = base;
185
+ faithful = false;
186
+ notes.push(`simulation: fee fields (${Object.keys(feeFields).join(', ')}) dropped — the node ` +
187
+ `required the sender to fund gas × price; the contract saw tx.gasprice = 0`);
188
+ return await call(method, params(callObj));
189
+ }
190
+ };
191
+ let method = 'eth_simulateV1';
192
+ let status;
193
+ let gasUsed = null;
194
+ let revertReason;
195
+ let logs = null;
196
+ try {
197
+ const res = await viaNode('eth_simulateV1', (obj) => [
198
+ { blockStateCalls: [{ calls: [obj] }], traceTransfers: true, validation: false },
199
+ 'latest',
200
+ ]);
201
+ const parsed = parseSimulateV1(res);
202
+ status = parsed.ok ? 'ok' : 'reverted';
203
+ gasUsed = parsed.gasUsed;
204
+ logs = parsed.logs;
205
+ notes.push(...parsed.notes);
206
+ if (!parsed.ok) {
207
+ revertReason = parsed.revertReason;
208
+ if (parsed.bareRevert)
209
+ revertReason = outOfGasReason(gasUsed, gas) ?? revertReason;
210
+ }
211
+ }
212
+ catch (err) {
213
+ // Some nodes serve eth_simulateV1 but can't build a creation call with
214
+ // it (anvil rejects a missing `to`); eth_call handles deploys fine.
215
+ const deployRejected = to === null && err instanceof UpstreamRpcError && !isRevert(err) && err.code === -32602;
216
+ if (err instanceof UpstreamRpcError && (isUnsupported(err) || deployRejected)) {
217
+ method = 'eth_call';
218
+ notes.push(deployRejected
219
+ ? 'simulation: eth_call only (node cannot simulate a contract creation with eth_simulateV1)'
220
+ : 'simulation: eth_call only (node lacks eth_simulateV1)');
221
+ // Only a well-formed answer counts as success: an eth_call result is
222
+ // return data (hex bytes); null, a number or odd-length hex means we
223
+ // don't know what happened.
224
+ let callOk = false;
225
+ try {
226
+ const ret = await viaNode('eth_call', (obj) => [obj, 'latest']);
227
+ if (typeof ret !== 'string' || !RETURN_DATA_RE.test(ret)) {
228
+ throw new Error('malformed eth_call result', { cause: err });
229
+ }
230
+ callOk = true;
231
+ }
232
+ catch (e) {
233
+ if (!(e instanceof UpstreamRpcError) || !isRevert(e))
234
+ throw e;
235
+ status = 'reverted';
236
+ revertReason = revertFromRpcError(e);
237
+ }
238
+ if (callOk) {
239
+ status = 'ok';
240
+ // eth_estimateGas re-executes the call; if it reverts there, the tx
241
+ // reverts — that is a result, not a missing gas figure.
242
+ try {
243
+ gasUsed = parseQty(await viaNode('eth_estimateGas', (obj) => [obj]), 'eth_estimateGas');
244
+ }
245
+ catch (e) {
246
+ if (e instanceof UpstreamRpcError && isRevert(e)) {
247
+ status = 'reverted';
248
+ revertReason = revertFromRpcError(e);
249
+ }
250
+ else {
251
+ notes.push('gas estimate unavailable');
252
+ }
253
+ }
254
+ }
255
+ }
256
+ else if (err instanceof UpstreamRpcError && isRevert(err)) {
257
+ // Some nodes surface a revert of the (only) call as a top-level error.
258
+ status = 'reverted';
259
+ revertReason = revertFromRpcError(err);
260
+ logs = [];
261
+ }
262
+ else {
263
+ throw err;
264
+ }
265
+ }
266
+ let transfers = null;
267
+ let allTransfers = null;
268
+ let approvals = null;
269
+ let wraps = null;
270
+ let changes = null;
271
+ let omitted = 0;
272
+ if (logs !== null) {
273
+ const analysis = analyzeLogs(logs, from, { to, value });
274
+ if (analysis.malformed > 0) {
275
+ notes.push(`${analysis.malformed} log${analysis.malformed === 1 ? '' : 's'} not understood`);
276
+ }
277
+ omitted = Math.max(0, analysis.transfers.length - MAX_TRANSFERS);
278
+ transfers = analysis.transfers.slice(0, MAX_TRANSFERS);
279
+ allTransfers = analysis.transfers;
280
+ approvals = analysis.approvals;
281
+ wraps = analysis.wraps;
282
+ changes = analysis.changes;
283
+ }
284
+ if (status === undefined)
285
+ throw new Error('internal: simulation status unset');
286
+ return {
287
+ status,
288
+ method,
289
+ gasUsed,
290
+ ...(revertReason !== undefined ? { revertReason } : {}),
291
+ transfers,
292
+ transfersOmitted: omitted,
293
+ allTransfers,
294
+ changes,
295
+ approvals,
296
+ wraps,
297
+ faithful,
298
+ notes,
299
+ tokenMeta: {},
300
+ };
301
+ }
302
+ class SimShapeError extends Error {
303
+ constructor(message) {
304
+ super(`eth_simulateV1 returned an unexpected shape: ${message}`);
305
+ this.name = 'SimShapeError';
306
+ }
307
+ }
308
+ /**
309
+ * Status is read first and is the only field whose absence makes the
310
+ * result unusable. Once the node has said "reverted", nothing else in the
311
+ * response may downgrade that to "unavailable" — a malformed `logs` or
312
+ * `gasUsed` next to a known revert would otherwise slip a reverting tx past
313
+ * sign_on_revert = false. Malformed secondary fields become notes, with
314
+ * logs null (balance changes unknown).
315
+ */
316
+ function parseSimulateV1(res) {
317
+ if (!Array.isArray(res) || res.length === 0)
318
+ throw new SimShapeError('no blocks');
319
+ const block = res[0];
320
+ const calls = isObj(block) ? block['calls'] : undefined;
321
+ if (!Array.isArray(calls) || calls.length === 0 || !isObj(calls[0])) {
322
+ throw new SimShapeError('no call results');
323
+ }
324
+ const c = calls[0];
325
+ const st = c['status'];
326
+ if (st !== '0x1' && st !== '0x0' && st !== '0x01' && st !== '0x00') {
327
+ throw new SimShapeError(`status ${JSON.stringify(st)}`);
328
+ }
329
+ const ok = st === '0x1' || st === '0x01';
330
+ const notes = [];
331
+ const gasUsed = hexQuantity(c['gasUsed']);
332
+ if (gasUsed === null && c['gasUsed'] !== undefined)
333
+ notes.push('gasUsed not understood');
334
+ const rawLogs = c['logs'] ?? [];
335
+ let logs = null;
336
+ if (Array.isArray(rawLogs)) {
337
+ logs = rawLogs.filter(isObj).map((l) => ({
338
+ address: typeof l['address'] === 'string' ? l['address'].toLowerCase() : '',
339
+ topics: Array.isArray(l['topics'])
340
+ ? l['topics'].map((t) => (typeof t === 'string' ? t.toLowerCase() : ''))
341
+ : [],
342
+ data: typeof l['data'] === 'string' ? l['data'].toLowerCase() : '',
343
+ }));
344
+ }
345
+ else {
346
+ notes.push('logs not understood');
347
+ }
348
+ if (ok)
349
+ return { ok, gasUsed, logs, notes };
350
+ const err = isObj(c['error']) ? c['error'] : undefined;
351
+ const errData = typeof err?.['data'] === 'string' ? err['data'] : undefined;
352
+ const ret = typeof c['returnData'] === 'string' ? c['returnData'] : undefined;
353
+ const bytes = errData ?? ret;
354
+ let revertReason;
355
+ let bareRevert = false;
356
+ if (bytes !== undefined && bytes !== '0x' && HEX_RE.test(bytes)) {
357
+ revertReason = decodeRevert(bytes);
358
+ }
359
+ else {
360
+ bareRevert = true;
361
+ revertReason =
362
+ typeof err?.['message'] === 'string'
363
+ ? cleanMessage(err['message'])
364
+ : 'execution reverted (no reason)';
365
+ }
366
+ return { ok, gasUsed, revertReason, bareRevert, logs, notes };
367
+ }
368
+ // ---------------------------------------------------------------------------
369
+ // Revert decoding
370
+ // ---------------------------------------------------------------------------
371
+ const PANIC_CODES = {
372
+ '0': 'generic compiler panic',
373
+ '1': 'assertion failed',
374
+ '17': 'arithmetic overflow/underflow',
375
+ '18': 'division or modulo by zero',
376
+ '33': 'invalid enum value',
377
+ '34': 'invalid storage byte array encoding',
378
+ '49': 'pop on empty array',
379
+ '50': 'array index out of bounds',
380
+ '65': 'out of memory / allocation too large',
381
+ '81': 'call to an uninitialized internal function',
382
+ };
383
+ /**
384
+ * Human text for revert data. Error(string) and Panic(uint256) are decoded;
385
+ * anything else is named by its selector. The reason string is chosen by
386
+ * the reverting contract — JSON-quoted and truncated so it can't break the
387
+ * layout of a push notification or impersonate sigil's own lines.
388
+ */
389
+ export function decodeRevert(hex) {
390
+ const body = hex.startsWith('0x') ? hex.slice(2) : hex;
391
+ if (body.length === 0)
392
+ return 'execution reverted (no reason)';
393
+ if (body.length < 8 || body.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) {
394
+ return `malformed revert data (${Math.floor(body.length / 2)} bytes)`;
395
+ }
396
+ const sel = body.slice(0, 8).toLowerCase();
397
+ const args = Buffer.from(body.slice(8), 'hex');
398
+ if (sel === '08c379a0') {
399
+ try {
400
+ const [msg] = decodeAbiParameters(['string'], args);
401
+ const clipped = msg.length > 160 ? msg.slice(0, 160) + '…' : msg;
402
+ return `Error(${JSON.stringify(clipped)})`;
403
+ }
404
+ catch (err) {
405
+ if (!(err instanceof AbiDecodeError))
406
+ throw err;
407
+ }
408
+ }
409
+ else if (sel === '4e487b71') {
410
+ try {
411
+ const [code] = decodeAbiParameters(['uint256'], args);
412
+ const name = PANIC_CODES[code.toString()];
413
+ return `Panic(0x${code.toString(16)}${name ? `: ${name}` : ''})`;
414
+ }
415
+ catch (err) {
416
+ if (!(err instanceof AbiDecodeError))
417
+ throw err;
418
+ }
419
+ }
420
+ return `custom error 0x${sel} (${body.length / 2} bytes)`;
421
+ }
422
+ function revertFromRpcError(e) {
423
+ if (typeof e.data === 'string' && e.data !== '0x' && HEX_RE.test(e.data)) {
424
+ return decodeRevert(e.data);
425
+ }
426
+ return cleanMessage(e.message);
427
+ }
428
+ /** Node error messages are short and node-authored, but may embed a revert string. */
429
+ function cleanMessage(m) {
430
+ const t = Array.from(m, (ch) => (ch.charCodeAt(0) < 0x20 || ch === '\u007f' ? ' ' : ch))
431
+ .join('')
432
+ .trim();
433
+ return t.length > 160 ? t.slice(0, 160) + '…' : t;
434
+ }
435
+ /**
436
+ * Exactly anvil's refusal (-32003 "Insufficient funds for gas * price +
437
+ * value"). Both the code and the message must match: the fee-stripped
438
+ * retry simulates a different tx, so it must not be reachable through any
439
+ * other error a node (or something in front of it) can produce.
440
+ */
441
+ function isInsufficientFunds(e) {
442
+ return (e instanceof UpstreamRpcError &&
443
+ e.code === -32003 &&
444
+ !isRevert(e) &&
445
+ /insufficient funds/i.test(e.message));
446
+ }
447
+ function isRevert(e) {
448
+ return e.code === 3 || /revert/i.test(e.message);
449
+ }
450
+ /** The node doesn't serve the method (vs. the call failing). */
451
+ function isUnsupported(e) {
452
+ if (isRevert(e))
453
+ return false;
454
+ return e.code === -32601 || /not supported|does not exist/i.test(e.message);
455
+ }
456
+ // ---------------------------------------------------------------------------
457
+ // Log analysis
458
+ // ---------------------------------------------------------------------------
459
+ const HEX_RE = /^0x[0-9a-fA-F]*$/;
460
+ /** Return data: whole bytes of hex. */
461
+ const RETURN_DATA_RE = /^0x(?:[0-9a-fA-F]{2})*$/;
462
+ const TOPIC_RE = /^0x[0-9a-f]{64}$/;
463
+ const ADDR_RE = /^0x[0-9a-f]{40}$/;
464
+ /**
465
+ * Pure: classify logs into transfers and approvals, and net them for the
466
+ * portal. `value` and `to` let the caller's own native send be accounted
467
+ * for when the node didn't trace the top-level transfer (see below).
468
+ */
469
+ export function analyzeLogs(logs, portal, tx) {
470
+ const transfers = [];
471
+ const approvals = [];
472
+ const wraps = [];
473
+ let malformed = 0;
474
+ for (const log of logs) {
475
+ try {
476
+ classify(log, portal, transfers, approvals, wraps);
477
+ }
478
+ catch {
479
+ malformed++;
480
+ }
481
+ }
482
+ let native = 0n;
483
+ let tracedOut = 0n;
484
+ const erc20 = new Map();
485
+ const nftIn = [];
486
+ const nftOut = [];
487
+ const erc1155 = new Map();
488
+ for (const t of transfers) {
489
+ const sign = (t.to === portal ? 1n : 0n) - (t.from === portal ? 1n : 0n);
490
+ if (t.standard === 'native' && t.from === portal)
491
+ tracedOut += t.amount;
492
+ if (sign === 0n)
493
+ continue;
494
+ switch (t.standard) {
495
+ case 'native':
496
+ native += sign * t.amount;
497
+ break;
498
+ case 'erc20':
499
+ erc20.set(t.token, (erc20.get(t.token) ?? 0n) + sign * t.amount);
500
+ break;
501
+ case 'erc721':
502
+ (sign > 0n ? nftIn : nftOut).push({ token: t.token, tokenId: t.tokenId });
503
+ break;
504
+ case 'erc1155': {
505
+ const key = `${t.token}:${t.tokenId}`;
506
+ const cur = erc1155.get(key) ?? { token: t.token, tokenId: t.tokenId, delta: 0n };
507
+ cur.delta += sign * t.amount;
508
+ erc1155.set(key, cur);
509
+ break;
510
+ }
511
+ }
512
+ }
513
+ // traceTransfers normally includes the top-level value transfer; if the
514
+ // node traced none of the portal's outflow, account for tx.value here.
515
+ // Gas is deliberately excluded — it depends on inclusion-time fees.
516
+ if (tx.value > 0n && tracedOut < tx.value && tx.to !== portal) {
517
+ native -= tx.value - tracedOut;
518
+ }
519
+ return {
520
+ transfers,
521
+ approvals,
522
+ wraps,
523
+ changes: {
524
+ native,
525
+ erc20: [...erc20].filter(([, d]) => d !== 0n).map(([token, delta]) => ({ token, delta })),
526
+ nftIn,
527
+ nftOut,
528
+ erc1155: [...erc1155.values()].filter((e) => e.delta !== 0n),
529
+ },
530
+ malformed,
531
+ };
532
+ }
533
+ function classify(log, portal, transfers, approvals, wraps) {
534
+ if (!ADDR_RE.test(log.address) || !HEX_RE.test(log.data))
535
+ throw new Error('bad log');
536
+ for (const t of log.topics)
537
+ if (!TOPIC_RE.test(t))
538
+ throw new Error('bad topic');
539
+ const [topic0] = log.topics;
540
+ if (topic0 === undefined)
541
+ return; // anonymous event: not ours
542
+ const n = log.topics.length;
543
+ const data = Buffer.from(log.data.slice(2), 'hex');
544
+ const token = log.address;
545
+ switch (topic0) {
546
+ case EVENT_TOPICS.Transfer: {
547
+ if (n === 3) {
548
+ const [amount] = decodeAbiParameters(['uint256'], data);
549
+ const native = NATIVE_SENTINELS.has(token);
550
+ transfers.push({
551
+ standard: native ? 'native' : 'erc20',
552
+ token: native ? null : token,
553
+ from: topicAddr(log.topics[1]),
554
+ to: topicAddr(log.topics[2]),
555
+ amount,
556
+ });
557
+ return;
558
+ }
559
+ if (n === 4) {
560
+ transfers.push({
561
+ standard: 'erc721',
562
+ token,
563
+ from: topicAddr(log.topics[1]),
564
+ to: topicAddr(log.topics[2]),
565
+ amount: 1n,
566
+ tokenId: BigInt(log.topics[3]),
567
+ });
568
+ return;
569
+ }
570
+ throw new Error('Transfer arity');
571
+ }
572
+ case EVENT_TOPICS.Approval: {
573
+ const owner = topicAddr(log.topics[1] ?? '');
574
+ if (n === 3) {
575
+ const [amount] = decodeAbiParameters(['uint256'], data);
576
+ if (owner === portal) {
577
+ approvals.push({ standard: 'erc20', token, spender: topicAddr(log.topics[2]), amount });
578
+ }
579
+ return;
580
+ }
581
+ if (n === 4) {
582
+ if (owner === portal) {
583
+ approvals.push({
584
+ standard: 'erc721',
585
+ token,
586
+ spender: topicAddr(log.topics[2]),
587
+ tokenId: BigInt(log.topics[3]),
588
+ });
589
+ }
590
+ return;
591
+ }
592
+ throw new Error('Approval arity');
593
+ }
594
+ case EVENT_TOPICS.ApprovalForAll: {
595
+ if (n !== 3)
596
+ throw new Error('ApprovalForAll arity');
597
+ const [approved] = decodeAbiParameters(['bool'], data);
598
+ if (topicAddr(log.topics[1]) === portal) {
599
+ approvals.push({
600
+ standard: 'operator',
601
+ token,
602
+ spender: topicAddr(log.topics[2]),
603
+ approved,
604
+ });
605
+ }
606
+ return;
607
+ }
608
+ case EVENT_TOPICS.TransferSingle: {
609
+ if (n !== 4)
610
+ throw new Error('TransferSingle arity');
611
+ const [id, amount] = decodeAbiParameters(['uint256', 'uint256'], data);
612
+ transfers.push({
613
+ standard: 'erc1155',
614
+ token,
615
+ from: topicAddr(log.topics[2]),
616
+ to: topicAddr(log.topics[3]),
617
+ amount,
618
+ tokenId: id,
619
+ });
620
+ return;
621
+ }
622
+ case EVENT_TOPICS.TransferBatch: {
623
+ if (n !== 4)
624
+ throw new Error('TransferBatch arity');
625
+ const [ids, amounts] = decodeAbiParameters(['uint256[]', 'uint256[]'], data);
626
+ if (ids.length !== amounts.length)
627
+ throw new Error('TransferBatch length mismatch');
628
+ ids.forEach((id, i) => transfers.push({
629
+ standard: 'erc1155',
630
+ token,
631
+ from: topicAddr(log.topics[2]),
632
+ to: topicAddr(log.topics[3]),
633
+ amount: amounts[i],
634
+ tokenId: id,
635
+ }));
636
+ return;
637
+ }
638
+ case EVENT_TOPICS.Deposit:
639
+ case EVENT_TOPICS.Withdrawal: {
640
+ if (n !== 2)
641
+ throw new Error('Deposit/Withdrawal arity');
642
+ const [wad] = decodeAbiParameters(['uint256'], data);
643
+ const who = topicAddr(log.topics[1]);
644
+ // WETH9 mints/burns without a Transfer event; model it as one.
645
+ const deposit = topic0 === EVENT_TOPICS.Deposit;
646
+ wraps.push({ token, who, kind: deposit ? 'deposit' : 'withdrawal', amount: wad });
647
+ transfers.push({
648
+ standard: 'erc20',
649
+ token,
650
+ from: deposit ? ZERO_ADDRESS : who,
651
+ to: deposit ? who : ZERO_ADDRESS,
652
+ amount: wad,
653
+ });
654
+ return;
655
+ }
656
+ default:
657
+ return; // some other event — not part of the balance picture
658
+ }
659
+ }
660
+ function topicAddr(topic) {
661
+ if (!TOPIC_RE.test(topic))
662
+ throw new Error('bad topic');
663
+ return '0x' + topic.slice(26);
664
+ }
665
+ // ---------------------------------------------------------------------------
666
+ // Token metadata
667
+ // ---------------------------------------------------------------------------
668
+ const SYMBOL_SELECTOR = '0x95d89b41';
669
+ const DECIMALS_SELECTOR = '0x313ce567';
670
+ /**
671
+ * symbol() + decimals() via eth_call. Tolerates bytes32 symbols (MKR-era
672
+ * tokens), reverts, EOAs and garbage: whatever fails is simply absent.
673
+ */
674
+ export async function fetchTokenMeta(token, call,
675
+ /** Called when a lookup failed for a reason other than the token's own
676
+ * answer (timeout, transport) — i.e. the metadata is unknown, not absent. */
677
+ onUnreachable) {
678
+ const [sym, dec] = await Promise.allSettled([
679
+ call('eth_call', [{ to: token, data: SYMBOL_SELECTOR }, 'latest']),
680
+ call('eth_call', [{ to: token, data: DECIMALS_SELECTOR }, 'latest']),
681
+ ]);
682
+ for (const r of [sym, dec]) {
683
+ if (r.status === 'rejected' && !(r.reason instanceof UpstreamRpcError))
684
+ onUnreachable?.();
685
+ }
686
+ const meta = {};
687
+ if (sym.status === 'fulfilled') {
688
+ const s = parseSymbol(sym.value);
689
+ if (s !== undefined)
690
+ meta.symbol = s;
691
+ }
692
+ if (dec.status === 'fulfilled') {
693
+ const d = parseDecimals(dec.value);
694
+ if (d !== undefined)
695
+ meta.decimals = d;
696
+ }
697
+ return meta;
698
+ }
699
+ export function parseSymbol(ret) {
700
+ if (typeof ret !== 'string' || !HEX_RE.test(ret) || ret.length % 2 !== 0)
701
+ return undefined;
702
+ const bytes = Buffer.from(ret.slice(2), 'hex');
703
+ if (bytes.length > 32) {
704
+ try {
705
+ const [s] = decodeAbiParameters(['string'], bytes);
706
+ return sanitizeSymbol(s);
707
+ }
708
+ catch {
709
+ return undefined;
710
+ }
711
+ }
712
+ if (bytes.length === 32) {
713
+ // bytes32 symbol: ASCII, right-padded with zeros.
714
+ const end = bytes.indexOf(0);
715
+ return sanitizeSymbol(bytes.subarray(0, end === -1 ? 32 : end).toString('latin1'));
716
+ }
717
+ return undefined;
718
+ }
719
+ export function parseDecimals(ret) {
720
+ if (typeof ret !== 'string' || !HEX_RE.test(ret) || ret.length % 2 !== 0)
721
+ return undefined;
722
+ const bytes = Buffer.from(ret.slice(2), 'hex');
723
+ if (bytes.length < 32)
724
+ return undefined;
725
+ try {
726
+ const [d] = decodeAbiParameters(['uint256'], bytes);
727
+ return d <= 36n ? Number(d) : undefined;
728
+ }
729
+ catch {
730
+ return undefined;
731
+ }
732
+ }
733
+ // ---------------------------------------------------------------------------
734
+ // Helpers
735
+ // ---------------------------------------------------------------------------
736
+ function qtyHex(v) {
737
+ return '0x' + v.toString(16);
738
+ }
739
+ /** A node quantity, or throw: malformed or wider than uint256 (oversized). */
740
+ function parseQty(v, what) {
741
+ const q = hexQuantity(v);
742
+ if (q === null) {
743
+ const oversized = typeof v === 'string' && v.length > MAX_QTY_HEX_DIGITS + 2;
744
+ throw new Error(`${what} is ${oversized ? 'an oversized quantity' : 'not a hex quantity'}`);
745
+ }
746
+ return q;
747
+ }
748
+ function isObj(v) {
749
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
750
+ }
751
+ function errText(err) {
752
+ if (err instanceof UpstreamRpcError)
753
+ return `node error ${err.code}: ${cleanMessage(err.message)}`;
754
+ return cleanMessage(err.message ?? String(err));
755
+ }
756
+ /** Race a promise against a timer; the timer never keeps the process alive. */
757
+ export function withTimeout(p, ms, message) {
758
+ let timer;
759
+ const t = new Promise((_, reject) => {
760
+ timer = setTimeout(() => reject(new Error(message)), ms);
761
+ timer.unref?.();
762
+ });
763
+ return Promise.race([p, t]).finally(() => {
764
+ if (timer)
765
+ clearTimeout(timer);
766
+ });
767
+ }
768
+ //# sourceMappingURL=simulate.js.map