@sig-net/midnight 0.0.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.
Files changed (90) hide show
  1. package/README.md +20 -0
  2. package/dist/constants.d.ts +62 -0
  3. package/dist/constants.d.ts.map +1 -0
  4. package/dist/constants.js +83 -0
  5. package/dist/constants.js.map +1 -0
  6. package/dist/epsilon-derivation.d.ts +32 -0
  7. package/dist/epsilon-derivation.d.ts.map +1 -0
  8. package/dist/epsilon-derivation.js +54 -0
  9. package/dist/epsilon-derivation.js.map +1 -0
  10. package/dist/index.d.ts +26 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +30 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/managed/compiler/contract-info.json +165 -0
  15. package/dist/managed/compiler/contract-manifest.json +32 -0
  16. package/dist/managed/contract/index.d.ts +65 -0
  17. package/dist/managed/contract/index.js +611 -0
  18. package/dist/managed/contract/index.js.map +8 -0
  19. package/dist/schnorr.d.ts +100 -0
  20. package/dist/schnorr.d.ts.map +1 -0
  21. package/dist/schnorr.js +144 -0
  22. package/dist/schnorr.js.map +1 -0
  23. package/dist/signature-requests-state-reader.d.ts +74 -0
  24. package/dist/signature-requests-state-reader.d.ts.map +1 -0
  25. package/dist/signature-requests-state-reader.js +167 -0
  26. package/dist/signature-requests-state-reader.js.map +1 -0
  27. package/dist/signature-response-verification.d.ts +27 -0
  28. package/dist/signature-response-verification.d.ts.map +1 -0
  29. package/dist/signature-response-verification.js +45 -0
  30. package/dist/signature-response-verification.js.map +1 -0
  31. package/dist/signature-state-reading.d.ts +36 -0
  32. package/dist/signature-state-reading.d.ts.map +1 -0
  33. package/dist/signature-state-reading.js +62 -0
  34. package/dist/signature-state-reading.js.map +1 -0
  35. package/dist/signet-contract-state-reader.d.ts +146 -0
  36. package/dist/signet-contract-state-reader.d.ts.map +1 -0
  37. package/dist/signet-contract-state-reader.js +226 -0
  38. package/dist/signet-contract-state-reader.js.map +1 -0
  39. package/dist/signet-event-observer.d.ts +102 -0
  40. package/dist/signet-event-observer.d.ts.map +1 -0
  41. package/dist/signet-event-observer.js +127 -0
  42. package/dist/signet-event-observer.js.map +1 -0
  43. package/dist/signet-events.d.ts +175 -0
  44. package/dist/signet-events.d.ts.map +1 -0
  45. package/dist/signet-events.js +210 -0
  46. package/dist/signet-events.js.map +1 -0
  47. package/dist/signet-request-feed.d.ts +78 -0
  48. package/dist/signet-request-feed.d.ts.map +1 -0
  49. package/dist/signet-request-feed.js +116 -0
  50. package/dist/signet-request-feed.js.map +1 -0
  51. package/dist/signet-request-resolver.d.ts +58 -0
  52. package/dist/signet-request-resolver.d.ts.map +1 -0
  53. package/dist/signet-request-resolver.js +76 -0
  54. package/dist/signet-request-resolver.js.map +1 -0
  55. package/dist/signet-request-response-reader.d.ts +160 -0
  56. package/dist/signet-request-response-reader.d.ts.map +1 -0
  57. package/dist/signet-request-response-reader.js +198 -0
  58. package/dist/signet-request-response-reader.js.map +1 -0
  59. package/dist/signet-requests.d.ts +363 -0
  60. package/dist/signet-requests.d.ts.map +1 -0
  61. package/dist/signet-requests.js +497 -0
  62. package/dist/signet-requests.js.map +1 -0
  63. package/dist/signet-response-feed.d.ts +161 -0
  64. package/dist/signet-response-feed.d.ts.map +1 -0
  65. package/dist/signet-response-feed.js +234 -0
  66. package/dist/signet-response-feed.js.map +1 -0
  67. package/package.json +47 -0
  68. package/src/Schnorr.compact +63 -0
  69. package/src/Signet.compact +529 -0
  70. package/src/circuits.compact +36 -0
  71. package/src/constants.ts +97 -0
  72. package/src/epsilon-derivation.ts +62 -0
  73. package/src/index.ts +31 -0
  74. package/src/managed/compiler/contract-info.json +165 -0
  75. package/src/managed/compiler/contract-manifest.json +32 -0
  76. package/src/managed/contract/index.d.ts +65 -0
  77. package/src/managed/contract/index.js +611 -0
  78. package/src/managed/contract/index.js.map +8 -0
  79. package/src/schnorr.ts +210 -0
  80. package/src/signature-requests-state-reader.ts +223 -0
  81. package/src/signature-response-verification.ts +64 -0
  82. package/src/signature-state-reading.ts +87 -0
  83. package/src/signet-contract-state-reader.ts +391 -0
  84. package/src/signet-event-observer.ts +186 -0
  85. package/src/signet-events.ts +337 -0
  86. package/src/signet-request-feed.ts +158 -0
  87. package/src/signet-request-resolver.ts +116 -0
  88. package/src/signet-request-response-reader.ts +324 -0
  89. package/src/signet-requests.ts +737 -0
  90. package/src/signet-response-feed.ts +325 -0
@@ -0,0 +1,737 @@
1
+ // TypeScript twins of the request-side structs in the Compact library
2
+ // `Signet.compact` (same directory). The shapes MUST stay in lockstep with the Compact structs: the
3
+ // compiler inlines struct types anonymously into each contract's generated
4
+ // managed/contract/index.d.ts, and these named types match them structurally,
5
+ // so ledger reads assign to them without casts.
6
+ //
7
+ // The lockstep is enforced by each consuming contract's simulator tests: the
8
+ // "erc20-vault ledger shape" test in packages/vault-contract/tests/
9
+ // contract.test.ts assigns the generated `ledger().signetRequestsIndex` to the
10
+ // named SignBidirectionalRequestLedgerIndex type — the assignment itself is
11
+ // the assertion, so any structural drift between the generated managed types
12
+ // and these twins fails that package's `yarn build` / `yarn test`.
13
+ //
14
+ // Read more: https://docs.sig.network/ (signet protocol) and the module
15
+ // header in Signet.compact (layout convention, path binding).
16
+
17
+ import {
18
+ CompactTypeBoolean,
19
+ CompactTypeBytes,
20
+ CompactTypeEnum,
21
+ CompactTypeUnsignedInteger,
22
+ CompactTypeVector,
23
+ persistentHash,
24
+ type CompactType,
25
+ } from "@midnight-ntwrk/compact-runtime";
26
+ import { getAddress, getBytes, Signature, Transaction } from "ethers";
27
+
28
+ import { asciiPadded } from "./constants.ts";
29
+ import { bigintToBytes32, bytesToBigint } from "./schnorr.ts";
30
+ import type { SignatureResponse } from "./signet-contract-state-reader.ts";
31
+
32
+ /**
33
+ * 32-byte signet request id (Compact: `new type RequestId = Bytes<32>`).
34
+ * Chain-agnostic: downstream consumers treat it as an opaque key. Ids are
35
+ * minted by `calculateRequestId` in Signet.compact — the domain-separated
36
+ * hash of the full {@link SignBidirectionalRequest} record.
37
+ */
38
+ export type RequestId = Uint8Array;
39
+
40
+ /**
41
+ * Which transaction-param decomposition a request carries (Compact:
42
+ * `enum TxParamType`), as the generated code represents enums: a `number`
43
+ * holding the 0-based variant index. Exported as a `const` object (not a TS
44
+ * `enum`) so the values stay structurally `number`.
45
+ */
46
+ export const TxParamType = {
47
+ /** {@link EVMType2TxParams}: an EIP-1559 EVM transaction. */
48
+ evmType2: 0,
49
+ /**
50
+ * Never emitted — mirrors the Compact-side padding variant that keeps the
51
+ * enum at >= 2 variants (a 1-variant enum is a zero-byte value the proof
52
+ * server cannot parse inside persistentHash preimages).
53
+ */
54
+ reserved: 1,
55
+ } as const;
56
+
57
+ /**
58
+ * Compact's standard-library `Maybe<T>` as the compiler generates it: a
59
+ * plain struct. Even when `is_some` is false, `value` carries a full
60
+ * default-valued `T` (so vector capacities remain inferable).
61
+ */
62
+ export interface Maybe<T> {
63
+ is_some: boolean;
64
+ value: T;
65
+ }
66
+
67
+ /**
68
+ * ABI calldata as a 4-byte selector + 32-byte word slots (Compact:
69
+ * `EVMCalldata<#maxWords>`). Each word is a little-endian field embed (what the
70
+ * contract's `x as Field as Bytes<32>` cast produces); the MPC re-encodes the
71
+ * leading {@link noWords} of them big-endian to form the calldata body —
72
+ * `data = selector || BE(words[0..noWords])`, see {@link assembleCalldata}.
73
+ */
74
+ export interface EVMCalldata {
75
+ /** The literal first 4 calldata bytes (big-endian, as broadcast). */
76
+ selector: Uint8Array;
77
+ /** How many leading {@link words} are real (Compact `noWords: Uint<16>`). */
78
+ noWords: bigint;
79
+ /** 32-byte word slots; capacity is the contract's `#maxWords` (vault: 2). */
80
+ words: Uint8Array[];
81
+ }
82
+
83
+ /**
84
+ * One EIP-2930 access-list entry (Compact:
85
+ * `EVMAccessListEntry<#maxStorageKeys>`).
86
+ */
87
+ export interface EVMAccessListEntry {
88
+ /** The pre-declared contract address, 20 display-order bytes. */
89
+ address: Uint8Array;
90
+ /** How many leading {@link storageKeys} are real. */
91
+ storageKeyCount: bigint;
92
+ /** Raw 32-byte storage keys, copied verbatim into the transaction. */
93
+ storageKeys: Uint8Array[];
94
+ }
95
+
96
+ /**
97
+ * The EVM transaction to be signed, decomposed into typed fields (Compact:
98
+ * `EVMType2TxParams<#maxCalldataWords, #maxAccessListEntries,
99
+ * #maxStorageKeysPerEntry>`; EIP-1559 — https://eips.ethereum.org/EIPS/eip-1559).
100
+ * Compact `Bytes<N>` fields arrive as N-byte `Uint8Array`s, `Uint<N>` as
101
+ * `bigint`. Vector capacities are each contract's compile-time throttle;
102
+ * the runtime counts say how many leading slots are real.
103
+ */
104
+ export interface EVMType2TxParams {
105
+ /** Call target (e.g. the ERC20 contract), 20 bytes. */
106
+ to: Uint8Array;
107
+ /** EVM chain id (also expressed in {@link SignBidirectionalRequest.caip2Id}). */
108
+ chainId: bigint;
109
+ /** Account nonce of the MPC-derived sender address. */
110
+ nonce: bigint;
111
+ /** Gas ceiling for the call. */
112
+ gasLimit: bigint;
113
+ /** Max total fee per gas, wei. */
114
+ maxFeePerGas: bigint;
115
+ /** Max priority fee per gas, wei. */
116
+ maxPriorityFeePerGas: bigint;
117
+ /** ETH sent with the call, wei. */
118
+ value: bigint;
119
+ /** How many leading {@link accessList} entries are real. */
120
+ accessListEntryCount: bigint;
121
+ /** EIP-2930 access list slots (capacity = contract's throttle). */
122
+ accessList: EVMAccessListEntry[];
123
+ /** Call data; `is_some: false` means a plain ETH transfer (`0x` data). */
124
+ calldata: Maybe<EVMCalldata>;
125
+ }
126
+
127
+ /**
128
+ * Canonical signet request record (Compact:
129
+ * `SignBidirectionalRequest<TxParams>`), stored per {@link RequestId} in a
130
+ * requesting contract's index (ledger field 0). Mirrors the MPC's
131
+ * SignBidirectionalRequest with the transaction decomposed. The TS twin fixes
132
+ * the type parameter at {@link EVMType2TxParams} — the only decomposition
133
+ * so far; new tx kinds add a union here alongside their Compact struct.
134
+ */
135
+ export interface SignBidirectionalRequest {
136
+ /** Contract-local nonce captured when the request was created. */
137
+ requestNonce: bigint;
138
+ /** A {@link TxParamType} value tagging the txParams decomposition. */
139
+ txParamType: number;
140
+ /** The transaction decomposition. */
141
+ txParams: EVMType2TxParams;
142
+ /** Target chain in CAIP-2 form (https://chainagnostic.org/CAIPs/caip-2), zero-padded; 32 bytes. */
143
+ caip2Id: Uint8Array;
144
+ /** MPC root-key version to derive from (>= 1; version 0 is the unsupported legacy format). */
145
+ keyVersion: bigint;
146
+ /** Key-derivation path: canonical lowercase hex of the caller's identity commitment, zero-padded; 256 bytes. */
147
+ path: Uint8Array;
148
+ /** Signature scheme, zero-padded ASCII, e.g. "ecdsa"; 32 bytes. */
149
+ algo: Uint8Array;
150
+ /** Response destination, zero-padded ASCII, e.g. "ethereum"; 32 bytes. */
151
+ dest: Uint8Array;
152
+ /** Scheme-specific extras, opaque; 64 bytes. */
153
+ params: Uint8Array;
154
+ /** MPC output_deserialization_schema (destination chain -> MPC); 128 bytes. */
155
+ outputDeserializationSchema: Uint8Array;
156
+ /** MPC respond_serialization_schema (MPC -> source chain); 128 bytes. */
157
+ respondSerializationSchema: Uint8Array;
158
+ }
159
+
160
+ // ---- Request id (TS twin of the Compact circuit) ---------------------------
161
+ //
162
+ // DEVIATION from the "pure circuits are compiled, never re-written in TS"
163
+ // rule (see circuits.compact): `calculateRequestId` is generic over the
164
+ // tx-params type, the Compact compiler cannot export type-parameterized
165
+ // circuits from the top level, and a compiled copy would have to be
166
+ // monomorphized at ONE capacity instantiation — a client contract's choice
167
+ // that never belongs in this client-agnostic package. So the request-id
168
+ // circuit alone gets a TS twin here.
169
+ //
170
+ // It is NOT a hand-port of the hash algorithm: it calls the very
171
+ // `persistentHash` runtime builtin that compiled circuits call, over runtime
172
+ // type descriptors mirroring the ones the compiler generates (compare
173
+ // `_calculateRequestId_0` in any consuming contract's
174
+ // managed/contract/index.js). What must stay in lockstep with Signet.compact
175
+ // is exactly what this file already keeps in lockstep — the struct shapes,
176
+ // field by field, in declaration order. Enforced by vault-contract's
177
+ // "deposit round-trip" test, which asserts the id computed here equals the
178
+ // ledger map key minted by the REAL compiled contract.
179
+
180
+ // Runtime descriptors of the Compact base types the request record uses.
181
+ // CompactTypeUnsignedInteger takes (maxValue, byte length) — same literals
182
+ // the compiler emits for Uint<8/32/64/128>. CompactTypeEnum takes
183
+ // (variantCount - 1, byte length); NOTE a 1-variant enum would compile to
184
+ // `CompactTypeEnum(0, 0)` — zero bytes, which the proof server cannot parse
185
+ // inside persistentHash preimages. TxParamType therefore carries a padding
186
+ // `reserved` variant so it stays at (1, 1).
187
+ const BYTES_4 = new CompactTypeBytes(4);
188
+ const BYTES_20 = new CompactTypeBytes(20);
189
+ const BYTES_32 = new CompactTypeBytes(32);
190
+ const BYTES_64 = new CompactTypeBytes(64);
191
+ const BYTES_128 = new CompactTypeBytes(128);
192
+ const BYTES_256 = new CompactTypeBytes(256);
193
+ const UINT_8 = new CompactTypeUnsignedInteger(2n ** 8n - 1n, 1);
194
+ const UINT_16 = new CompactTypeUnsignedInteger(2n ** 16n - 1n, 2);
195
+ const UINT_32 = new CompactTypeUnsignedInteger(2n ** 32n - 1n, 4);
196
+ const UINT_64 = new CompactTypeUnsignedInteger(2n ** 64n - 1n, 8);
197
+ const UINT_128 = new CompactTypeUnsignedInteger(2n ** 128n - 1n, 16);
198
+ const TX_PARAM_TYPE = new CompactTypeEnum(1, 1);
199
+
200
+ /**
201
+ * Build the runtime descriptor of a Compact struct from its per-field
202
+ * descriptors — the generic form of the struct descriptor classes the
203
+ * compiler generates (field-by-field concatenation of alignments and values).
204
+ *
205
+ * Field ORDER must match the Compact struct declaration order; object
206
+ * literals preserve insertion order for string keys, so pass fields in
207
+ * declaration order.
208
+ *
209
+ * @param fields - One runtime descriptor per struct field, in declaration order.
210
+ * @returns The composed struct descriptor.
211
+ */
212
+ function compactStructDescriptor<T extends object>(fields: {
213
+ readonly [K in keyof T]-?: CompactType<T[K]>;
214
+ }): CompactType<T> {
215
+ const entries = Object.entries(fields) as unknown as ReadonlyArray<
216
+ [keyof T & string, CompactType<T[keyof T & string]>]
217
+ >;
218
+ return {
219
+ alignment: () =>
220
+ entries.flatMap(([, type]) => type.alignment()),
221
+ toValue: (value) =>
222
+ entries.flatMap(([key, type]) => type.toValue(value[key])),
223
+ fromValue: (value) => {
224
+ const result = {} as Record<keyof T & string, unknown>;
225
+ for (const [key, type] of entries) {
226
+ result[key] = type.fromValue(value);
227
+ }
228
+ return result as T;
229
+ },
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Descriptor of Compact's standard-library `Maybe<T>` — the compiler
235
+ * generates it as the struct `{ is_some: Boolean, value: T }`.
236
+ *
237
+ * @param inner - Descriptor of the wrapped type.
238
+ * @returns The Maybe struct descriptor.
239
+ */
240
+ function compactMaybeDescriptor<T>(inner: CompactType<T>): CompactType<Maybe<T>> {
241
+ return compactStructDescriptor<Maybe<T>>({
242
+ is_some: CompactTypeBoolean,
243
+ value: inner,
244
+ });
245
+ }
246
+
247
+ /**
248
+ * Descriptor of {@link EVMCalldata} at one word capacity — the TS analogue
249
+ * of instantiating Compact's `EVMCalldata<#maxWords>`.
250
+ *
251
+ * @param maxWords - The contract's calldata word capacity (the vault uses 2).
252
+ * @returns The calldata descriptor.
253
+ */
254
+ export function evmCalldataDescriptor(maxWords: number): CompactType<EVMCalldata> {
255
+ return compactStructDescriptor<EVMCalldata>({
256
+ selector: BYTES_4,
257
+ noWords: UINT_16,
258
+ words: new CompactTypeVector(maxWords, BYTES_32),
259
+ });
260
+ }
261
+
262
+ /**
263
+ * Descriptor of {@link EVMAccessListEntry} at one storage-key capacity
264
+ * (Compact: `EVMAccessListEntry<#maxStorageKeys>`).
265
+ *
266
+ * @param maxStorageKeys - Storage-key capacity per entry.
267
+ * @returns The entry descriptor.
268
+ */
269
+ export function evmAccessListEntryDescriptor(
270
+ maxStorageKeys: number,
271
+ ): CompactType<EVMAccessListEntry> {
272
+ return compactStructDescriptor<EVMAccessListEntry>({
273
+ address: BYTES_20,
274
+ storageKeyCount: UINT_8,
275
+ storageKeys: new CompactTypeVector(maxStorageKeys, BYTES_32),
276
+ });
277
+ }
278
+
279
+ /**
280
+ * Descriptor of {@link EVMType2TxParams} at one capacity instantiation —
281
+ * the TS analogue of Compact's `EVMType2TxParams<#maxCalldataWords,
282
+ * #maxAccessListEntries, #maxStorageKeysPerEntry>`.
283
+ *
284
+ * @param maxCalldataWords - Calldata word capacity.
285
+ * @param maxAccessListEntries - Access-list entry capacity.
286
+ * @param maxStorageKeysPerEntry - Storage-key capacity per entry.
287
+ * @returns The tx-params descriptor.
288
+ */
289
+ export function evmType2TxParamsDescriptor(
290
+ maxCalldataWords: number,
291
+ maxAccessListEntries: number,
292
+ maxStorageKeysPerEntry: number,
293
+ ): CompactType<EVMType2TxParams> {
294
+ return compactStructDescriptor<EVMType2TxParams>({
295
+ to: BYTES_20,
296
+ chainId: UINT_64,
297
+ nonce: UINT_64,
298
+ gasLimit: UINT_64,
299
+ maxFeePerGas: UINT_128,
300
+ maxPriorityFeePerGas: UINT_128,
301
+ value: UINT_128,
302
+ accessListEntryCount: UINT_8,
303
+ accessList: new CompactTypeVector(
304
+ maxAccessListEntries,
305
+ evmAccessListEntryDescriptor(maxStorageKeysPerEntry),
306
+ ),
307
+ calldata: compactMaybeDescriptor(evmCalldataDescriptor(maxCalldataWords)),
308
+ });
309
+ }
310
+
311
+ /**
312
+ * Descriptor of {@link SignBidirectionalRequest} at one capacity instantiation.
313
+ *
314
+ * @param maxCalldataWords - Calldata word capacity.
315
+ * @param maxAccessListEntries - Access-list entry capacity.
316
+ * @param maxStorageKeysPerEntry - Storage-key capacity per entry.
317
+ * @returns The request record descriptor.
318
+ */
319
+ export function signBidirectionalRequestDescriptor(
320
+ maxCalldataWords: number,
321
+ maxAccessListEntries: number,
322
+ maxStorageKeysPerEntry: number,
323
+ ): CompactType<SignBidirectionalRequest> {
324
+ return compactStructDescriptor<SignBidirectionalRequest>({
325
+ requestNonce: UINT_64,
326
+ txParamType: TX_PARAM_TYPE,
327
+ txParams: evmType2TxParamsDescriptor(
328
+ maxCalldataWords,
329
+ maxAccessListEntries,
330
+ maxStorageKeysPerEntry,
331
+ ),
332
+ caip2Id: BYTES_32,
333
+ keyVersion: UINT_32,
334
+ path: BYTES_256,
335
+ algo: BYTES_32,
336
+ dest: BYTES_32,
337
+ params: BYTES_64,
338
+ outputDeserializationSchema: BYTES_128,
339
+ respondSerializationSchema: BYTES_128,
340
+ });
341
+ }
342
+
343
+ /**
344
+ * Domain tag partitioning the {@link RequestId} space
345
+ * (Compact: `pad(32, "signet:midnight:request")`).
346
+ */
347
+ const REQUEST_ID_DOMAIN_TAG = asciiPadded("signet:midnight:request", 32);
348
+
349
+ /**
350
+ * Canonical id of a signet request: the domain-separated persistent hash of
351
+ * the entire request record. TS twin of Signet.compact's `calculateRequestId`
352
+ * circuit (see the deviation note atop this section), generic over the
353
+ * capacity instantiation via the record's own array lengths — pass the
354
+ * record exactly as the ledger stores it, unused slots included.
355
+ *
356
+ * @param request - The full request record (contract-shaped, all slots).
357
+ * @returns The 32-byte request id — the record's ledger map key.
358
+ */
359
+ export function calculateRequestId(request: SignBidirectionalRequest): RequestId {
360
+ const { txParams } = request;
361
+ const maxCalldataWords = txParams.calldata.value.words.length;
362
+ const maxAccessListEntries = txParams.accessList.length;
363
+ const maxStorageKeysPerEntry =
364
+ maxAccessListEntries === 0 ? 0 : txParams.accessList[0].storageKeys.length;
365
+ return persistentHash(new CompactTypeVector(2, BYTES_32), [
366
+ REQUEST_ID_DOMAIN_TAG,
367
+ persistentHash(
368
+ signBidirectionalRequestDescriptor(
369
+ maxCalldataWords,
370
+ maxAccessListEntries,
371
+ maxStorageKeysPerEntry,
372
+ ),
373
+ request,
374
+ ),
375
+ ]);
376
+ }
377
+
378
+ // ---- Calldata / transaction assembly ----------------------------------------
379
+
380
+ /**
381
+ * The 32-byte value of a numeric ABI word: the little-endian field embed of
382
+ * the number, exactly what Compact's `x as Field as Bytes<32>` cast produces
383
+ * in-circuit. Use when building words off-chain (UIs, expected-record
384
+ * builders, tests).
385
+ *
386
+ * @param value - The word's numeric value (e.g. an amount).
387
+ * @returns The 32-byte LE embed to store in an {@link EVMCalldata} word.
388
+ */
389
+ export function numericAbiWordValue(value: bigint): Uint8Array {
390
+ return bigintToBytes32(value);
391
+ }
392
+
393
+ /**
394
+ * The 32-byte staticArg word value for an EVM address: the BIG-ENDIAN
395
+ * numeric reading of its 20 display-order bytes, LE-embedded. TS mirror of
396
+ * Signet.compact's `evmAddressAbiValue` circuit (+ `as Bytes<32>`); see the
397
+ * warning there — embedding the display-order bytes directly would come out
398
+ * byte-reversed in the assembled calldata.
399
+ *
400
+ * @param address - The 20-byte address in display order.
401
+ * @returns The 32-byte word value to store in an {@link EVMCalldata} word.
402
+ */
403
+ export function evmAddressAbiWord(address: Uint8Array): Uint8Array {
404
+ let value = 0n;
405
+ for (const byte of address) {
406
+ value = value * 256n + BigInt(byte);
407
+ }
408
+ return bigintToBytes32(value);
409
+ }
410
+
411
+ /**
412
+ * Re-assemble the raw calldata a request's words describe:
413
+ * `data = selector || BE(words[0..noWords])`. Each word is a little-endian
414
+ * field embed (the contract's `x as Field as Bytes<32>` cast); the leading
415
+ * `noWords` are re-encoded big-endian into 32-byte ABI words and any remaining
416
+ * capacity slots are dropped. This is THE implementation of the MPC re-assembly
417
+ * documented on `EVMCalldata` in Signet.compact.
418
+ *
419
+ * @param calldata - The request's calldata field.
420
+ * @returns Hex calldata for the transaction (`"0x"` when absent).
421
+ */
422
+ export function assembleCalldata(calldata: Maybe<EVMCalldata>): string {
423
+ if (!calldata.is_some) {
424
+ return "0x";
425
+ }
426
+ const { selector, noWords, words } = calldata.value;
427
+ let data = `0x${bytesToHex(selector)}`;
428
+ for (let i = 0; i < Number(noWords); i++) {
429
+ data += bytesToHex(bigintToBytes32BE(bytesToBigint(words[i])));
430
+ }
431
+ return data;
432
+ }
433
+
434
+ /**
435
+ * Decode the real (count-trimmed) access list of a request into the shape
436
+ * ethers' `Transaction.from` accepts.
437
+ *
438
+ * @param txParams - The request's transaction decomposition.
439
+ * @returns The access list, possibly empty.
440
+ */
441
+ function decodeAccessList(
442
+ txParams: EVMType2TxParams,
443
+ ): Array<{ address: string; storageKeys: string[] }> {
444
+ return txParams.accessList
445
+ .slice(0, Number(txParams.accessListEntryCount))
446
+ .map((entry) => ({
447
+ address: getAddress(`0x${bytesToHex(entry.address)}`),
448
+ storageKeys: entry.storageKeys
449
+ .slice(0, Number(entry.storageKeyCount))
450
+ .map((key) => `0x${bytesToHex(key)}`),
451
+ }));
452
+ }
453
+
454
+ /**
455
+ * Rebuild the unsigned EIP-1559 transaction a request record describes,
456
+ * byte-identical to the one the MPC assembles and signs: calldata from the
457
+ * tagged words (see {@link assembleCalldata}), the count-trimmed access
458
+ * list, and the stored envelope fields. This is the canonical
459
+ * request→transaction transform; response-side verification
460
+ * (`signature-response-verification.ts`) and the signed-transaction builder
461
+ * below both go through it, so the transaction a client broadcasts is
462
+ * provably the one the MPC put its signature over.
463
+ *
464
+ * @param event - The on-ledger request record.
465
+ * @returns The unsigned ethers transaction (`unsignedHash` is the digest the
466
+ * MPC signs).
467
+ * @throws Error if a calldata word carries an unknown kind.
468
+ */
469
+ export function signBidirectionalRequestToUnsignedEVMTransaction(
470
+ event: SignBidirectionalRequest,
471
+ ): Transaction {
472
+ const { txParams } = event;
473
+ return Transaction.from({
474
+ type: 2,
475
+ chainId: txParams.chainId,
476
+ nonce: Number(txParams.nonce),
477
+ gasLimit: txParams.gasLimit,
478
+ maxFeePerGas: txParams.maxFeePerGas,
479
+ maxPriorityFeePerGas: txParams.maxPriorityFeePerGas,
480
+ to: getAddress(`0x${bytesToHex(txParams.to)}`),
481
+ value: txParams.value,
482
+ accessList: decodeAccessList(txParams),
483
+ data: assembleCalldata(txParams.calldata),
484
+ });
485
+ }
486
+
487
+ /**
488
+ * Decode a response signature record (as posted to the signet contract's
489
+ * signature response log — the canonical MPC `Signature { big_r, s,
490
+ * recovery_id }` shape) into an ethers {@link Signature}: `r` is `bigR`'s x
491
+ * coordinate, `v` the legacy parity derived from the recovery id.
492
+ *
493
+ * @param response - The posted signature record.
494
+ * @returns The ethers signature.
495
+ * @throws Error if the recovery id is not 0 or 1.
496
+ */
497
+ export function signatureResponseToSignature(
498
+ response: SignatureResponse,
499
+ ): Signature {
500
+ const recoveryId = Number(response.recoveryId);
501
+ if (recoveryId !== 0 && recoveryId !== 1) {
502
+ throw new Error(`expected a recovery id of 0 or 1, got ${recoveryId}`);
503
+ }
504
+ return Signature.from({
505
+ r: `0x${bytesToHex(response.bigRx)}`,
506
+ s: `0x${bytesToHex(response.s)}`,
507
+ v: recoveryId + 27,
508
+ });
509
+ }
510
+
511
+ /** secp256k1 base field prime (2^256 - 2^32 - 977). */
512
+ const SECP256K1_P = 2n ** 256n - 2n ** 32n - 977n;
513
+
514
+ /** Modular exponentiation by squaring. */
515
+ function modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {
516
+ let result = 1n;
517
+ let b = base % modulus;
518
+ let e = exponent;
519
+ while (e > 0n) {
520
+ if (e & 1n) result = (result * b) % modulus;
521
+ b = (b * b) % modulus;
522
+ e >>= 1n;
523
+ }
524
+ return result;
525
+ }
526
+
527
+ /** Encode a bigint as exactly 32 BIG-endian bytes (secp256k1 scalar form). */
528
+ function bigintToBytes32BE(value: bigint): Uint8Array {
529
+ const out = new Uint8Array(32);
530
+ let v = value;
531
+ for (let i = 31; i >= 0; i--) {
532
+ out[i] = Number(v & 0xffn);
533
+ v >>= 8n;
534
+ }
535
+ return out;
536
+ }
537
+
538
+ /**
539
+ * Encode an ECDSA signature as the response record posted to the signet
540
+ * contract — the inverse of {@link signatureResponseToSignature},
541
+ * for MPC-side posters (the fakenet signer, tests). The canonical record
542
+ * carries `bigR` as a full affine point but an `r || s || v` signature only
543
+ * has R.x and the parity of R.y, so R.y is recovered by decompressing the
544
+ * point on the curve (y² = x³ + 7 over the secp256k1 base field).
545
+ *
546
+ * The parameter is structural (the r/s/yParity subset of an ethers
547
+ * {@link Signature}) so signatures from ANY ethers instance qualify — posters
548
+ * living in other repos resolve their own ethers install, and nominal class
549
+ * typing would reject it.
550
+ *
551
+ * @param signature - The signature to encode (`r`/`s` as 0x hex, `yParity` 0 or 1).
552
+ * @returns The response record, ready to post.
553
+ * @throws Error if `r` is not the x coordinate of a curve point.
554
+ */
555
+ export function signatureToSignatureResponse(
556
+ signature: Pick<Signature, "r" | "s" | "yParity">,
557
+ ): SignatureResponse {
558
+ const x = BigInt(signature.r);
559
+ const ySquared = (modPow(x, 3n, SECP256K1_P) + 7n) % SECP256K1_P;
560
+ // P ≡ 3 (mod 4), so a square root (when one exists) is c^((P+1)/4).
561
+ let y = modPow(ySquared, (SECP256K1_P + 1n) / 4n, SECP256K1_P);
562
+ if ((y * y) % SECP256K1_P !== ySquared) {
563
+ throw new Error("signature r is not the x coordinate of a secp256k1 point");
564
+ }
565
+ if ((y & 1n) !== BigInt(signature.yParity)) {
566
+ y = SECP256K1_P - y;
567
+ }
568
+ return {
569
+ bigRx: getBytes(signature.r),
570
+ bigRy: bigintToBytes32BE(y),
571
+ s: getBytes(signature.s),
572
+ recoveryId: BigInt(signature.yParity),
573
+ };
574
+ }
575
+
576
+ /**
577
+ * Assemble the broadcast-ready signed EIP-1559 transaction for a request from
578
+ * its MPC signature response: rebuild the exact unsigned transaction the MPC
579
+ * signed (see {@link signBidirectionalRequestToUnsignedEVMTransaction}) and
580
+ * attach the signature. Does NOT check that the signature recovers to the
581
+ * requester's derived address — the response log is unauthenticated, so
582
+ * verify first with `verifySignatureResponse`.
583
+ *
584
+ * @param event - The on-ledger request record.
585
+ * @param response - The posted signature record answering it.
586
+ * @returns The signed ethers transaction; `serialized` is the raw payload for
587
+ * `eth_sendRawTransaction`, `hash` its on-chain hash, `from` the recovered
588
+ * sender.
589
+ * @throws Error if the request record is malformed (see
590
+ * {@link signBidirectionalRequestToUnsignedEVMTransaction}) or the response
591
+ * is not a decodable signature.
592
+ */
593
+ export function signBidirectionalRequestToSignedEVMTransaction(
594
+ event: SignBidirectionalRequest,
595
+ response: SignatureResponse,
596
+ ): Transaction {
597
+ const transaction = signBidirectionalRequestToUnsignedEVMTransaction(event);
598
+ transaction.signature = signatureResponseToSignature(response);
599
+ return transaction;
600
+ }
601
+
602
+ /**
603
+ * The generated ledger shape of `Map<RequestId, SignBidirectionalRequest>`:
604
+ * what a contract's `ledger(state).signetRequestsIndex` provides. Structural,
605
+ * so any contract exposing the index satisfies it.
606
+ */
607
+ export interface SignBidirectionalRequestLedgerIndex
608
+ extends Iterable<[RequestId, SignBidirectionalRequest]> {
609
+ /** @returns `true` when the index holds no requests. */
610
+ isEmpty(): boolean;
611
+ /** @returns Number of requests in the index. */
612
+ size(): bigint;
613
+ /**
614
+ * @param requestId - 32-byte request id to probe.
615
+ * @returns `true` when the index holds an entry for `requestId`.
616
+ */
617
+ member(requestId: RequestId): boolean;
618
+ /**
619
+ * @param requestId - 32-byte request id to fetch.
620
+ * @returns The stored request record; throws when absent — guard with
621
+ * {@link member} first.
622
+ */
623
+ lookup(requestId: RequestId): SignBidirectionalRequest;
624
+ }
625
+
626
+ declare const requestIdHexBrand: unique symbol;
627
+
628
+ /**
629
+ * 64-char lowercase hex rendering of a {@link RequestId} — THE
630
+ * representation of a request id everywhere in TypeScript. Raw
631
+ * {@link RequestId} bytes appear only at the Compact boundary (state
632
+ * readers, compiled-circuit calls); the moment an id crosses that boundary it
633
+ * becomes this type. Branded (the TS analogue of Compact's `new type`) so an
634
+ * arbitrary string cannot pose as a request id: mint one with
635
+ * {@link requestIdHex} (from ledger bytes) or {@link parseRequestIdHex}
636
+ * (from user input), and go back to bytes with {@link requestIdBytes}.
637
+ */
638
+ export type RequestIdHex = string & {
639
+ readonly [requestIdHexBrand]: true;
640
+ };
641
+
642
+ /** Plain-JS index parsed out of the ledger, keyed by hex request id. */
643
+ export type SignBidirectionalRequestIndex = Map<
644
+ RequestIdHex,
645
+ SignBidirectionalRequest
646
+ >;
647
+
648
+ /**
649
+ * Render bytes as a lowercase hex string, no `0x` prefix.
650
+ *
651
+ * @param bytes - The bytes to render.
652
+ * @returns Lowercase hex, two chars per byte.
653
+ */
654
+ export function bytesToHex(bytes: Uint8Array): string {
655
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
656
+ }
657
+
658
+ /**
659
+ * Render a request id in its canonical TS form (see
660
+ * {@link RequestIdHex}) — also usable as a JS `Map` key, which raw
661
+ * `Uint8Array` ids are not (they compare by reference).
662
+ *
663
+ * @param requestId - 32-byte request id.
664
+ * @returns The branded 64-char lowercase hex string, no `0x` prefix.
665
+ */
666
+ export function requestIdHex(requestId: RequestId): RequestIdHex {
667
+ return bytesToHex(requestId) as RequestIdHex;
668
+ }
669
+
670
+ /**
671
+ * Validate and normalize an untrusted string (CLI argument, config value)
672
+ * into a {@link RequestIdHex}: an optional `0x` prefix is stripped and
673
+ * the digits lowercased before validation.
674
+ *
675
+ * @param value - The candidate request id string.
676
+ * @returns The branded, normalized request id hex.
677
+ * @throws Error if the value is not 64 hex chars after normalization.
678
+ */
679
+ export function parseRequestIdHex(value: string): RequestIdHex {
680
+ const hex = value.replace(/^0x/i, "").toLowerCase();
681
+ if (!/^[0-9a-f]{64}$/.test(hex)) {
682
+ throw new Error(`not a 32-byte request id in hex: "${value}"`);
683
+ }
684
+ return hex as RequestIdHex;
685
+ }
686
+
687
+ /**
688
+ * Decode a request id back to its 32 raw bytes for the Compact boundary
689
+ * (compiled-circuit calls, ledger lookups).
690
+ *
691
+ * @param id - The request id in canonical hex form.
692
+ * @returns The 32-byte request id.
693
+ */
694
+ export function requestIdBytes(id: RequestIdHex): RequestId {
695
+ const bytes = new Uint8Array(32);
696
+ for (let i = 0; i < 32; i++) {
697
+ bytes[i] = Number.parseInt(id.slice(2 * i, 2 * i + 2), 16);
698
+ }
699
+ return bytes;
700
+ }
701
+
702
+ /** Byte width of the path field (Compact `Bytes<256>`). */
703
+ export const PATH_BYTES = 256;
704
+
705
+ /**
706
+ * Build the canonical MPC derivation path for an identity commitment: the
707
+ * lowercase hex of the commitment as ASCII, zero-padded to {@link PATH_BYTES}
708
+ * — exactly what the contract's `assertPathCommitment` accepts. Use this to
709
+ * populate {@link SignBidirectionalRequest.path} when constructing requests.
710
+ *
711
+ * @param commitment - 32-byte identity commitment.
712
+ * @returns The 256-byte path field value.
713
+ */
714
+ export function signetPathOfCommitment(commitment: Uint8Array): Uint8Array {
715
+ const path = new Uint8Array(PATH_BYTES);
716
+ path.set(new TextEncoder().encode(bytesToHex(commitment)));
717
+ return path;
718
+ }
719
+
720
+ /**
721
+ * Parse the on-ledger request map into a plain-JS index keyed by hex
722
+ * request id.
723
+ *
724
+ * @param ledgerIndex - Iterable of `[requestId, request]` entries — e.g. a
725
+ * contract's `ledger(state).signetRequestsIndex` (any
726
+ * {@link SignBidirectionalRequestLedgerIndex}).
727
+ * @returns A new `Map` from {@link requestIdHex} key to request record.
728
+ */
729
+ export function toSignBidirectionalRequestIndex(
730
+ ledgerIndex: Iterable<[RequestId, SignBidirectionalRequest]>,
731
+ ): SignBidirectionalRequestIndex {
732
+ const index: SignBidirectionalRequestIndex = new Map();
733
+ for (const [requestId, request] of ledgerIndex) {
734
+ index.set(requestIdHex(requestId), request);
735
+ }
736
+ return index;
737
+ }