ox 1.7.0 → 1.7.2

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 (126) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/core/Hash.js +1 -1
  3. package/dist/core/Hash.js.map +1 -1
  4. package/dist/core/Siwe.d.ts.map +1 -1
  5. package/dist/core/Siwe.js +45 -6
  6. package/dist/core/Siwe.js.map +1 -1
  7. package/dist/tempo/KeyAuthorization.d.ts +1 -1
  8. package/dist/tempo/KeyAuthorization.d.ts.map +1 -1
  9. package/dist/tempo/MultisigConfig.d.ts +151 -83
  10. package/dist/tempo/MultisigConfig.d.ts.map +1 -1
  11. package/dist/tempo/MultisigConfig.js +164 -86
  12. package/dist/tempo/MultisigConfig.js.map +1 -1
  13. package/dist/tempo/MultisigOperation.d.ts +324 -0
  14. package/dist/tempo/MultisigOperation.d.ts.map +1 -0
  15. package/dist/tempo/MultisigOperation.js +809 -0
  16. package/dist/tempo/MultisigOperation.js.map +1 -0
  17. package/dist/tempo/MultisigWitness.d.ts +106 -0
  18. package/dist/tempo/MultisigWitness.d.ts.map +1 -0
  19. package/dist/tempo/MultisigWitness.js +118 -0
  20. package/dist/tempo/MultisigWitness.js.map +1 -0
  21. package/dist/tempo/RpcSchemaTempo.d.ts +35 -0
  22. package/dist/tempo/RpcSchemaTempo.d.ts.map +1 -1
  23. package/dist/tempo/SignatureEnvelope.d.ts +60 -80
  24. package/dist/tempo/SignatureEnvelope.d.ts.map +1 -1
  25. package/dist/tempo/SignatureEnvelope.js +87 -146
  26. package/dist/tempo/SignatureEnvelope.js.map +1 -1
  27. package/dist/tempo/TransactionRequest.d.ts +9 -17
  28. package/dist/tempo/TransactionRequest.d.ts.map +1 -1
  29. package/dist/tempo/TransactionRequest.js +7 -7
  30. package/dist/tempo/TransactionRequest.js.map +1 -1
  31. package/dist/tempo/TxEnvelopeTempo.d.ts +3 -2
  32. package/dist/tempo/TxEnvelopeTempo.d.ts.map +1 -1
  33. package/dist/tempo/TxEnvelopeTempo.js +3 -2
  34. package/dist/tempo/TxEnvelopeTempo.js.map +1 -1
  35. package/dist/tempo/index.d.ts +22 -2
  36. package/dist/tempo/index.d.ts.map +1 -1
  37. package/dist/tempo/index.js +22 -2
  38. package/dist/tempo/index.js.map +1 -1
  39. package/dist/zod/tempo/AuthorizationTempo.d.ts +110 -110
  40. package/dist/zod/tempo/AuthorizationTempo.d.ts.map +1 -1
  41. package/dist/zod/tempo/KeyAuthorization.d.ts +90 -83
  42. package/dist/zod/tempo/KeyAuthorization.d.ts.map +1 -1
  43. package/dist/zod/tempo/MultisigConfig.d.ts +31 -2
  44. package/dist/zod/tempo/MultisigConfig.d.ts.map +1 -1
  45. package/dist/zod/tempo/MultisigConfig.js +26 -3
  46. package/dist/zod/tempo/MultisigConfig.js.map +1 -1
  47. package/dist/zod/tempo/MultisigOperation.d.ts +168 -0
  48. package/dist/zod/tempo/MultisigOperation.d.ts.map +1 -0
  49. package/dist/zod/tempo/MultisigOperation.js +65 -0
  50. package/dist/zod/tempo/MultisigOperation.js.map +1 -0
  51. package/dist/zod/tempo/MultisigWitness.d.ts +152 -0
  52. package/dist/zod/tempo/MultisigWitness.d.ts.map +1 -0
  53. package/dist/zod/tempo/MultisigWitness.js +76 -0
  54. package/dist/zod/tempo/MultisigWitness.js.map +1 -0
  55. package/dist/zod/tempo/RpcSchemaTempo.d.ts +607 -102
  56. package/dist/zod/tempo/RpcSchemaTempo.d.ts.map +1 -1
  57. package/dist/zod/tempo/RpcSchemaTempo.js +38 -0
  58. package/dist/zod/tempo/RpcSchemaTempo.js.map +1 -1
  59. package/dist/zod/tempo/SignatureEnvelope.d.ts +33 -33
  60. package/dist/zod/tempo/SignatureEnvelope.d.ts.map +1 -1
  61. package/dist/zod/tempo/SignatureEnvelope.js +9 -16
  62. package/dist/zod/tempo/SignatureEnvelope.js.map +1 -1
  63. package/dist/zod/tempo/Transaction.d.ts +228 -222
  64. package/dist/zod/tempo/Transaction.d.ts.map +1 -1
  65. package/dist/zod/tempo/TransactionRequest.d.ts +379 -176
  66. package/dist/zod/tempo/TransactionRequest.d.ts.map +1 -1
  67. package/dist/zod/tempo/TransactionRequest.js +11 -22
  68. package/dist/zod/tempo/TransactionRequest.js.map +1 -1
  69. package/dist/zod/tempo/TxEnvelopeTempo.d.ts +60 -48
  70. package/dist/zod/tempo/TxEnvelopeTempo.d.ts.map +1 -1
  71. package/dist/zod/tempo/ZoneRpcAuthentication.d.ts +15 -12
  72. package/dist/zod/tempo/ZoneRpcAuthentication.d.ts.map +1 -1
  73. package/dist/zod/tempo/z.d.ts +2 -0
  74. package/dist/zod/tempo/z.d.ts.map +1 -1
  75. package/dist/zod/tempo/z.js +2 -0
  76. package/dist/zod/tempo/z.js.map +1 -1
  77. package/package.json +21 -1
  78. package/src/core/Hash.ts +1 -1
  79. package/src/core/Siwe.ts +45 -5
  80. package/src/core/_test/Hash.test.ts +15 -0
  81. package/src/core/_test/Siwe.test.ts +98 -0
  82. package/src/tempo/KeyAuthorization.test-d.ts +13 -1
  83. package/src/tempo/KeyAuthorization.test.ts +65 -0
  84. package/src/tempo/KeyAuthorization.ts +1 -1
  85. package/src/tempo/MultisigConfig.test-d.ts +52 -0
  86. package/src/tempo/MultisigConfig.test.ts +288 -227
  87. package/src/tempo/MultisigConfig.ts +275 -104
  88. package/src/tempo/MultisigOperation.test-d.ts +77 -0
  89. package/src/tempo/MultisigOperation.test.ts +1883 -0
  90. package/src/tempo/MultisigOperation.ts +1254 -0
  91. package/src/tempo/MultisigWitness.test-d.ts +42 -0
  92. package/src/tempo/MultisigWitness.test.ts +288 -0
  93. package/src/tempo/MultisigWitness.ts +210 -0
  94. package/src/tempo/RpcSchemaTempo.test-d.ts +56 -0
  95. package/src/tempo/RpcSchemaTempo.ts +37 -0
  96. package/src/tempo/SignatureEnvelope.test-d.ts +63 -46
  97. package/src/tempo/SignatureEnvelope.test.ts +523 -500
  98. package/src/tempo/SignatureEnvelope.ts +172 -242
  99. package/src/tempo/TransactionRequest.test-d.ts +11 -0
  100. package/src/tempo/TransactionRequest.test.ts +285 -33
  101. package/src/tempo/TransactionRequest.ts +15 -20
  102. package/src/tempo/TxEnvelopeTempo.test-d.ts +7 -0
  103. package/src/tempo/TxEnvelopeTempo.test.ts +25 -0
  104. package/src/tempo/TxEnvelopeTempo.ts +5 -3
  105. package/src/tempo/index.ts +22 -2
  106. package/src/tempo/multisig.e2e.test.ts +113 -86
  107. package/src/version.ts +1 -1
  108. package/src/zod/tempo/MultisigConfig.ts +29 -3
  109. package/src/zod/tempo/MultisigOperation.ts +69 -0
  110. package/src/zod/tempo/MultisigWitness.ts +101 -0
  111. package/src/zod/tempo/RpcSchemaTempo.ts +43 -0
  112. package/src/zod/tempo/SignatureEnvelope.ts +20 -38
  113. package/src/zod/tempo/TransactionRequest.ts +17 -26
  114. package/src/zod/tempo/_test/KeyAuthorization.test.ts +11 -0
  115. package/src/zod/tempo/_test/MultisigConfig.test-d.ts +13 -0
  116. package/src/zod/tempo/_test/MultisigConfig.test.ts +13 -2
  117. package/src/zod/tempo/_test/MultisigOperation.test-d.ts +27 -0
  118. package/src/zod/tempo/_test/MultisigOperation.test.ts +68 -0
  119. package/src/zod/tempo/_test/MultisigWitness.test-d.ts +13 -0
  120. package/src/zod/tempo/_test/MultisigWitness.test.ts +149 -0
  121. package/src/zod/tempo/_test/RpcSchemaTempo.test-d.ts +31 -0
  122. package/src/zod/tempo/_test/RpcSchemaTempo.test.ts +41 -0
  123. package/src/zod/tempo/_test/SignatureEnvelope.test-d.ts +1 -1
  124. package/src/zod/tempo/_test/SignatureEnvelope.test.ts +25 -34
  125. package/src/zod/tempo/_test/TransactionRequest.test.ts +176 -8
  126. package/src/zod/tempo/z.ts +2 -0
@@ -0,0 +1,809 @@
1
+ import * as Address from '../core/Address.js';
2
+ import * as Errors from '../core/Errors.js';
3
+ import * as Hash from '../core/Hash.js';
4
+ import * as Hex from '../core/Hex.js';
5
+ import * as KeyAuthorization_ from './KeyAuthorization.js';
6
+ import * as MultisigConfig from './MultisigConfig.js';
7
+ import * as SignatureEnvelope from './SignatureEnvelope.js';
8
+ import * as TxEnvelopeTempo from './TxEnvelopeTempo.js';
9
+ /** Maximum supported multisig configuration version. */
10
+ const maxConfigVersion = 2n ** 64n - 1n;
11
+ /**
12
+ * Derives the deterministic hash for a multisig operation.
13
+ *
14
+ * @example
15
+ * ```ts twoslash
16
+ * // @noErrors
17
+ * import { MultisigOperation } from 'ox/tempo'
18
+ *
19
+ * const hash = MultisigOperation.getHash({
20
+ * account,
21
+ * configVersion: 1n,
22
+ * transaction,
23
+ * type: 'transaction'
24
+ * })
25
+ * ```
26
+ *
27
+ * @param options - Operation payload and multisig identity.
28
+ * @returns The operation hash signed by each owner.
29
+ */
30
+ export function getHash(options) {
31
+ const { account, configVersion } = options;
32
+ const payload = options.type === 'transaction'
33
+ ? TxEnvelopeTempo.getSignPayload(TxEnvelopeTempo.deserialize(options.transaction))
34
+ : KeyAuthorization_.getSignPayload(KeyAuthorization_.deserialize(options.keyAuthorization));
35
+ return MultisigConfig.getSignPayload({
36
+ account,
37
+ config: { version: configVersion },
38
+ payload,
39
+ });
40
+ }
41
+ /**
42
+ * Validates, deduplicates, and selects owner approvals for an operation.
43
+ *
44
+ * The function retains one canonical approval per owner. It selects the
45
+ * smallest deterministic quorum by owner weight, then orders the selected
46
+ * approvals by owner address for serialization.
47
+ *
48
+ * @example
49
+ * ```ts twoslash
50
+ * // @noErrors
51
+ * import { MultisigOperation } from 'ox/tempo'
52
+ *
53
+ * const selection = await MultisigOperation.selectApprovals({
54
+ * account,
55
+ * approvals,
56
+ * config,
57
+ * hash,
58
+ * resolveConfig
59
+ * })
60
+ * ```
61
+ *
62
+ * @param options - Approval selection parameters.
63
+ * @returns The retained approvals and deterministic quorum selection.
64
+ */
65
+ export async function selectApprovals(options) {
66
+ const { account, approvals, hash, resolveConfig } = options;
67
+ if (!Address.validate(account) || Hex.toBigInt(account) === 0n)
68
+ throw new InvalidApprovalError({ reason: 'account is invalid' });
69
+ if (!Hash.validate(hash))
70
+ throw new InvalidApprovalError({ reason: 'hash is invalid' });
71
+ return selectApprovals_internal({
72
+ account,
73
+ approvals,
74
+ config: MultisigConfig.from(options.config),
75
+ hash,
76
+ resolveConfig,
77
+ }, [account.toLowerCase()]);
78
+ }
79
+ /**
80
+ * Serializes a multisig transaction operation with selected owner approvals.
81
+ *
82
+ * @example
83
+ * ```ts twoslash
84
+ * // @noErrors
85
+ * import { MultisigOperation } from 'ox/tempo'
86
+ *
87
+ * const transaction = MultisigOperation.serializeTransaction(
88
+ * operation,
89
+ * {
90
+ * approvals: selection.selectedApprovals
91
+ * }
92
+ * )
93
+ * ```
94
+ *
95
+ * @param operation - Multisig transaction operation.
96
+ * @param options - Transaction serialization options.
97
+ * @returns The signed serialized Tempo transaction.
98
+ */
99
+ export function serializeTransaction(operation, options) {
100
+ const value = from(operation);
101
+ const envelope = TxEnvelopeTempo.deserialize(value.transaction);
102
+ const approvals = options.approvals.map((approval) => SignatureEnvelope.from(approval));
103
+ assertRetainedApprovals(value, approvals);
104
+ const signatures = SignatureEnvelope.sortMultisigApprovals({
105
+ account: value.account,
106
+ config: value.config,
107
+ payload: TxEnvelopeTempo.getSignPayload(envelope),
108
+ signatures: approvals,
109
+ });
110
+ const signature = SignatureEnvelope.from({
111
+ account: value.account,
112
+ config: value.config,
113
+ signatures,
114
+ });
115
+ return TxEnvelopeTempo.serialize(envelope, value.transaction.startsWith(TxEnvelopeTempo.feePayerMagic)
116
+ ? {
117
+ format: 'feePayer',
118
+ sender: envelope.from,
119
+ signature,
120
+ }
121
+ : { signature });
122
+ }
123
+ /**
124
+ * Validates and normalizes a multisig operation.
125
+ *
126
+ * @example
127
+ * ```ts twoslash
128
+ * // @noErrors
129
+ * import { MultisigOperation } from 'ox/tempo'
130
+ *
131
+ * const operation = MultisigOperation.from(value)
132
+ * ```
133
+ *
134
+ * @param operation - Multisig operation.
135
+ * @returns The validated operation.
136
+ */
137
+ export function from(operation) {
138
+ try {
139
+ const config = MultisigConfig.from(operation.config);
140
+ if (config.version !== operation.configVersion)
141
+ throw new InvalidOperationError({
142
+ reason: 'config.version must equal configVersion',
143
+ });
144
+ if (typeof config.threshold !== 'number' ||
145
+ config.owners.some((owner) => typeof owner.weight !== 'number'))
146
+ throw new InvalidOperationError({
147
+ reason: 'config threshold and owner weights must be numbers',
148
+ });
149
+ const value = { ...operation, config };
150
+ assertBase(value, config);
151
+ if (value.type === 'transaction')
152
+ assertTransaction(value);
153
+ else if (value.type === 'keyAuthorization')
154
+ assertKeyAuthorization(value, config);
155
+ else
156
+ throw new InvalidOperationError({ reason: 'unknown operation type' });
157
+ return value;
158
+ }
159
+ catch (cause) {
160
+ if (cause instanceof InvalidOperationError)
161
+ throw cause;
162
+ throw new InvalidOperationError({ cause });
163
+ }
164
+ }
165
+ /**
166
+ * Converts a JSON-RPC multisig operation to its domain representation.
167
+ *
168
+ * @example
169
+ * ```ts twoslash
170
+ * // @noErrors
171
+ * import { MultisigOperation } from 'ox/tempo'
172
+ *
173
+ * const operation = MultisigOperation.fromRpc(value)
174
+ * ```
175
+ *
176
+ * @param operation - JSON-RPC multisig operation.
177
+ * @returns The validated operation.
178
+ */
179
+ export function fromRpc(operation) {
180
+ try {
181
+ if (typeof operation.configVersion !== 'string' ||
182
+ !Hex.validate(operation.configVersion))
183
+ throw new InvalidOperationError({
184
+ reason: 'configVersion must be a hexadecimal quantity',
185
+ });
186
+ const configVersion = Hex.toBigInt(operation.configVersion);
187
+ if (Hex.fromNumber(configVersion) !== operation.configVersion)
188
+ throw new InvalidOperationError({
189
+ reason: 'configVersion must use canonical quantity encoding',
190
+ });
191
+ return from({
192
+ ...operation,
193
+ config: MultisigConfig.fromRpc(operation.config),
194
+ configVersion,
195
+ });
196
+ }
197
+ catch (cause) {
198
+ if (cause instanceof InvalidOperationError)
199
+ throw cause;
200
+ throw new InvalidOperationError({ cause });
201
+ }
202
+ }
203
+ /**
204
+ * Converts a multisig operation to its JSON-RPC representation.
205
+ *
206
+ * @example
207
+ * ```ts twoslash
208
+ * // @noErrors
209
+ * import { MultisigOperation } from 'ox/tempo'
210
+ *
211
+ * const operationRpc = MultisigOperation.toRpc(operation)
212
+ * ```
213
+ *
214
+ * @param operation - Multisig operation.
215
+ * @returns The JSON-RPC operation.
216
+ */
217
+ export function toRpc(operation) {
218
+ const value = from(operation);
219
+ return {
220
+ ...value,
221
+ config: MultisigConfig.toRpc(value.config),
222
+ configVersion: Hex.fromNumber(value.configVersion),
223
+ };
224
+ }
225
+ /**
226
+ * Validates and selects approvals recursively.
227
+ *
228
+ * @internal
229
+ */
230
+ async function selectApprovals_internal(options, path) {
231
+ const owners = new Map(options.config.owners.map((owner) => [
232
+ owner.owner.toLowerCase(),
233
+ { address: owner.owner, weight: Number(owner.weight) },
234
+ ]));
235
+ const groups = new Map();
236
+ for (const serialized of options.approvals) {
237
+ const signature = SignatureEnvelope.from(serialized);
238
+ if (signature.type === 'keychain')
239
+ throw new InvalidApprovalError({
240
+ reason: 'keychain signatures cannot approve a multisig operation',
241
+ });
242
+ const address = signature.type === 'multisig'
243
+ ? signature.account
244
+ : SignatureEnvelope.extractAddress({
245
+ payload: options.hash,
246
+ signature,
247
+ });
248
+ const owner = owners.get(address.toLowerCase());
249
+ if (!owner)
250
+ throw new InvalidApprovalError({
251
+ reason: `signature is from non-owner ${address}`,
252
+ });
253
+ const key = address.toLowerCase();
254
+ const group = groups.get(key);
255
+ if (group)
256
+ group.signatures.push(signature);
257
+ else
258
+ groups.set(key, {
259
+ address: owner.address,
260
+ signatures: [signature],
261
+ weight: owner.weight,
262
+ });
263
+ }
264
+ const valid = [];
265
+ const retained = [];
266
+ for (const group of groups.values()) {
267
+ const nested = group.signatures.filter((signature) => signature.type === 'multisig');
268
+ if (nested.length > 0) {
269
+ if (nested.length !== group.signatures.length)
270
+ throw new InvalidApprovalError({
271
+ reason: `owner ${group.address} has conflicting signature types`,
272
+ });
273
+ if (path.length >= MultisigConfig.maxNestingDepth ||
274
+ path.includes(group.address.toLowerCase()))
275
+ throw new InvalidApprovalError({
276
+ reason: `nested multisig owner ${group.address} is invalid`,
277
+ });
278
+ if (!options.resolveConfig)
279
+ throw new InvalidApprovalError({
280
+ reason: `nested multisig owner ${group.address} requires a config resolver`,
281
+ });
282
+ const resolved = await options.resolveConfig({ account: group.address });
283
+ const config = MultisigConfig.from(resolved.config);
284
+ if (config.version !== resolved.version)
285
+ throw new InvalidApprovalError({
286
+ reason: `resolved config.version must equal version for nested multisig owner ${group.address}`,
287
+ });
288
+ const selected = await selectApprovals_internal({
289
+ account: group.address,
290
+ approvals: nested.flatMap((signature) => signature.signatures.map((approval) => SignatureEnvelope.serialize(approval))),
291
+ config,
292
+ hash: MultisigConfig.getSignPayload({
293
+ account: group.address,
294
+ config,
295
+ payload: options.hash,
296
+ }),
297
+ resolveConfig: options.resolveConfig,
298
+ }, [...path, group.address.toLowerCase()]);
299
+ retained.push({
300
+ address: group.address,
301
+ signature: SignatureEnvelope.serialize(SignatureEnvelope.from({
302
+ account: group.address,
303
+ config,
304
+ signatures: selected.approvals.map((approval) => SignatureEnvelope.from(approval)),
305
+ })),
306
+ });
307
+ if (selected.weight >= selected.threshold)
308
+ valid.push({
309
+ address: group.address,
310
+ signature: SignatureEnvelope.serialize(SignatureEnvelope.from({
311
+ account: group.address,
312
+ config,
313
+ signatures: selected.selectedApprovals.map((approval) => SignatureEnvelope.from(approval)),
314
+ })),
315
+ weight: group.weight,
316
+ });
317
+ continue;
318
+ }
319
+ const signatures = group.signatures.map((signature) => {
320
+ if (!SignatureEnvelope.verify(signature, {
321
+ address: group.address,
322
+ payload: options.hash,
323
+ }))
324
+ throw new InvalidApprovalError({
325
+ reason: `signature from owner ${group.address} is invalid`,
326
+ });
327
+ return SignatureEnvelope.serialize(signature);
328
+ });
329
+ const signature = signatures.sort(compareHex)[0];
330
+ valid.push({
331
+ address: group.address,
332
+ signature,
333
+ weight: group.weight,
334
+ });
335
+ retained.push({ address: group.address, signature });
336
+ }
337
+ const ranked = valid.sort((a, b) => b.weight - a.weight || compareApprovalAddress(a, b));
338
+ const selected = [];
339
+ let weight = 0;
340
+ for (const approval of ranked.slice(0, MultisigConfig.maxSignatures)) {
341
+ if (weight >= Number(options.config.threshold))
342
+ break;
343
+ selected.push(approval);
344
+ weight += approval.weight;
345
+ }
346
+ selected.sort(compareApprovalAddress);
347
+ return {
348
+ approvals: retained
349
+ .sort(compareApprovalAddress)
350
+ .map((approval) => approval.signature),
351
+ selectedApprovals: selected.map((approval) => approval.signature),
352
+ signatureCount: selected.length,
353
+ threshold: Number(options.config.threshold),
354
+ weight,
355
+ };
356
+ }
357
+ /**
358
+ * Orders approval records by owner address.
359
+ *
360
+ * @internal
361
+ */
362
+ function compareApprovalAddress(a, b) {
363
+ const addressA = Hex.toBigInt(a.address);
364
+ const addressB = Hex.toBigInt(b.address);
365
+ return addressA < addressB ? -1 : addressA > addressB ? 1 : 0;
366
+ }
367
+ /**
368
+ * Orders hexadecimal data bytewise.
369
+ *
370
+ * @internal
371
+ */
372
+ function compareHex(a, b) {
373
+ const hexA = a.toLowerCase();
374
+ const hexB = b.toLowerCase();
375
+ return hexA < hexB ? -1 : hexA > hexB ? 1 : 0;
376
+ }
377
+ /**
378
+ * Validates fields shared by every operation.
379
+ *
380
+ * @internal
381
+ */
382
+ function assertBase(operation, config) {
383
+ if (!Address.validate(operation.account))
384
+ throw new InvalidOperationError({ reason: 'account is invalid' });
385
+ if (Hex.toBigInt(operation.account) === 0n)
386
+ throw new InvalidOperationError({ reason: 'account cannot be zero' });
387
+ if (!Hash.validate(operation.hash))
388
+ throw new InvalidOperationError({ reason: 'hash is invalid' });
389
+ if (typeof operation.init !== 'boolean')
390
+ throw new InvalidOperationError({ reason: 'init must be a boolean' });
391
+ if (typeof operation.configVersion !== 'bigint' ||
392
+ operation.configVersion < 0n ||
393
+ operation.configVersion > maxConfigVersion)
394
+ throw new InvalidOperationError({
395
+ reason: 'configVersion must be an unsigned 64-bit integer',
396
+ });
397
+ assertInteger(operation.createdAt, 'createdAt');
398
+ assertInteger(operation.updatedAt, 'updatedAt');
399
+ if (operation.updatedAt < operation.createdAt)
400
+ throw new InvalidOperationError({
401
+ reason: 'updatedAt cannot precede createdAt',
402
+ });
403
+ assertInteger(operation.signatureCount, 'signatureCount');
404
+ assertInteger(operation.threshold, 'threshold');
405
+ assertInteger(operation.weight, 'weight');
406
+ if (operation.threshold !== Number(config.threshold))
407
+ throw new InvalidOperationError({
408
+ reason: 'threshold must equal config.threshold',
409
+ });
410
+ if (operation.weight > 0xff)
411
+ throw new InvalidOperationError({ reason: 'weight exceeds u8 max' });
412
+ if (operation.signatureCount > MultisigConfig.maxSignatures)
413
+ throw new InvalidOperationError({ reason: 'too many selected signatures' });
414
+ if (!Array.isArray(operation.approvals))
415
+ throw new InvalidOperationError({ reason: 'approvals must be an array' });
416
+ if (operation.approvals.length > config.owners.length)
417
+ throw new InvalidOperationError({ reason: 'too many retained approvals' });
418
+ if (operation.signatureCount > operation.approvals.length)
419
+ throw new InvalidOperationError({
420
+ reason: 'signatureCount exceeds retained approvals',
421
+ });
422
+ if ((operation.signatureCount === 0) !== (operation.weight === 0))
423
+ throw new InvalidOperationError({
424
+ reason: 'signatureCount and weight must both be zero or nonzero',
425
+ });
426
+ const owners = new Map(config.owners.map((owner) => [
427
+ owner.owner.toLowerCase(),
428
+ Number(owner.weight),
429
+ ]));
430
+ const approvalWeights = [];
431
+ const seen = new Set();
432
+ for (const approval of operation.approvals) {
433
+ if (typeof approval !== 'string' ||
434
+ !Hex.validate(approval, { strict: true }))
435
+ throw new InvalidOperationError({ reason: 'approval is invalid' });
436
+ const signature = assertApproval(operation.account, approval, config);
437
+ const address = SignatureEnvelope.extractAddress({
438
+ payload: operation.hash,
439
+ signature,
440
+ });
441
+ const key = address.toLowerCase();
442
+ const weight = owners.get(key);
443
+ if (weight === undefined)
444
+ throw new InvalidOperationError({
445
+ reason: 'approval is from a non-owner',
446
+ });
447
+ if (seen.has(key))
448
+ throw new InvalidOperationError({
449
+ reason: operation.type === 'keyAuthorization'
450
+ ? 'key authorization contains duplicate owner approvals'
451
+ : 'duplicate owner approval',
452
+ });
453
+ seen.add(key);
454
+ approvalWeights.push(weight);
455
+ }
456
+ if (!isWeightReachable(approvalWeights, operation.signatureCount, operation.weight))
457
+ throw new InvalidOperationError({
458
+ reason: 'weight is not reachable by signatureCount retained owner approvals',
459
+ });
460
+ if (operation.init) {
461
+ if (operation.configVersion !== 0n)
462
+ throw new InvalidOperationError({
463
+ reason: 'bootstrap operations must use config version zero',
464
+ });
465
+ if (MultisigConfig.getAddress(config).toLowerCase() !==
466
+ operation.account.toLowerCase())
467
+ throw new InvalidOperationError({
468
+ reason: 'bootstrap config does not derive the operation account',
469
+ });
470
+ }
471
+ }
472
+ /**
473
+ * Validates a transaction operation and its state-specific fields.
474
+ *
475
+ * @internal
476
+ */
477
+ function assertTransaction(operation) {
478
+ if ('keyAuthorization' in operation &&
479
+ operation.keyAuthorization !== undefined)
480
+ throw new InvalidOperationError({
481
+ reason: 'transaction operations cannot contain keyAuthorization',
482
+ });
483
+ const expiresAt = operation.expiresAt;
484
+ const submissionId = operation.submissionId;
485
+ const transactionHash = operation.transactionHash;
486
+ if (operation.status === 'pending') {
487
+ if (expiresAt !== undefined ||
488
+ submissionId !== undefined ||
489
+ transactionHash !== undefined)
490
+ throw new InvalidOperationError({
491
+ reason: 'pending transactions cannot contain submission fields',
492
+ });
493
+ }
494
+ else if (operation.status === 'submitting') {
495
+ assertInteger(expiresAt, 'expiresAt');
496
+ if (!Hash.validate(submissionId ?? ''))
497
+ throw new InvalidOperationError({ reason: 'submissionId is invalid' });
498
+ if (submissionId.toLowerCase() === operation.hash.toLowerCase())
499
+ throw new InvalidOperationError({
500
+ reason: 'submissionId must differ from the operation hash',
501
+ });
502
+ if (transactionHash !== undefined)
503
+ throw new InvalidOperationError({
504
+ reason: 'submitting transactions cannot contain transactionHash',
505
+ });
506
+ }
507
+ else if (operation.status === 'success') {
508
+ if (!Hash.validate(transactionHash ?? ''))
509
+ throw new InvalidOperationError({ reason: 'transactionHash is invalid' });
510
+ if (expiresAt !== undefined || submissionId !== undefined)
511
+ throw new InvalidOperationError({
512
+ reason: 'successful transactions cannot contain submission fields',
513
+ });
514
+ }
515
+ else
516
+ throw new InvalidOperationError({ reason: 'invalid transaction status' });
517
+ if (operation.status !== 'pending' &&
518
+ (operation.weight < operation.threshold || operation.signatureCount === 0))
519
+ throw new InvalidOperationError({
520
+ reason: 'submitted transactions must have quorum',
521
+ });
522
+ if (typeof operation.transaction !== 'string')
523
+ throw new InvalidOperationError({ reason: 'transaction is invalid' });
524
+ const feePayer = operation.transaction.startsWith(TxEnvelopeTempo.feePayerMagic);
525
+ const transaction = TxEnvelopeTempo.deserialize(operation.transaction);
526
+ if (transaction.signature)
527
+ throw new InvalidOperationError({
528
+ reason: 'transaction must not contain an outer sender signature',
529
+ });
530
+ if (transaction.from &&
531
+ transaction.from.toLowerCase() !== operation.account.toLowerCase())
532
+ throw new InvalidOperationError({
533
+ reason: 'transaction sender does not match the operation account',
534
+ });
535
+ assertOperationHash(operation, TxEnvelopeTempo.getSignPayload(transaction));
536
+ const normalized = TxEnvelopeTempo.serialize(transaction, feePayer
537
+ ? transaction.from
538
+ ? { format: 'feePayer', sender: transaction.from }
539
+ : { format: 'feePayer' }
540
+ : {});
541
+ if (normalized.toLowerCase() !== operation.transaction.toLowerCase())
542
+ throw new InvalidOperationError({
543
+ reason: 'transaction is not canonically serialized',
544
+ });
545
+ }
546
+ /**
547
+ * Validates a key authorization operation and its serialized payload.
548
+ *
549
+ * @internal
550
+ */
551
+ function assertKeyAuthorization(operation, config) {
552
+ const transactionFields = operation;
553
+ if (transactionFields.expiresAt !== undefined ||
554
+ transactionFields.submissionId !== undefined ||
555
+ transactionFields.transaction !== undefined ||
556
+ transactionFields.transactionHash !== undefined)
557
+ throw new InvalidOperationError({
558
+ reason: 'key authorization operations cannot contain transaction fields',
559
+ });
560
+ if (operation.status !== 'pending' && operation.status !== 'success')
561
+ throw new InvalidOperationError({
562
+ reason: 'invalid key authorization status',
563
+ });
564
+ if (operation.status === 'success' &&
565
+ (operation.weight < operation.threshold || operation.signatureCount === 0))
566
+ throw new InvalidOperationError({
567
+ reason: 'successful key authorizations must have quorum',
568
+ });
569
+ if (operation.status === 'pending' && operation.weight >= operation.threshold)
570
+ throw new InvalidOperationError({
571
+ reason: 'pending key authorizations cannot have quorum',
572
+ });
573
+ if (typeof operation.keyAuthorization !== 'string')
574
+ throw new InvalidOperationError({ reason: 'keyAuthorization is invalid' });
575
+ const authorization = KeyAuthorization_.deserialize(operation.keyAuthorization);
576
+ if (!authorization.account ||
577
+ authorization.account.toLowerCase() !== operation.account.toLowerCase())
578
+ throw new InvalidOperationError({
579
+ reason: 'key authorization account does not match the operation account',
580
+ });
581
+ const signature = authorization.signature;
582
+ if (operation.status === 'pending' && signature)
583
+ throw new InvalidOperationError({
584
+ reason: 'pending key authorizations must be unsigned',
585
+ });
586
+ if (operation.status === 'success') {
587
+ if (signature?.type !== 'multisig')
588
+ throw new InvalidOperationError({
589
+ reason: 'successful key authorizations require a multisig signature',
590
+ });
591
+ if (signature.account.toLowerCase() !== operation.account.toLowerCase())
592
+ throw new InvalidOperationError({
593
+ reason: 'key authorization signature account does not match',
594
+ });
595
+ if (signature.signatures.length !== operation.signatureCount)
596
+ throw new InvalidOperationError({
597
+ reason: 'key authorization signatureCount does not match its signature',
598
+ });
599
+ assertSelectedApprovals(operation, signature.signatures, authorization);
600
+ if (!sameConfig(signature.config, config))
601
+ throw new InvalidOperationError({
602
+ reason: 'key authorization config does not match',
603
+ });
604
+ }
605
+ assertOperationHash(operation, KeyAuthorization_.getSignPayload(authorization));
606
+ if (KeyAuthorization_.serialize(authorization).toLowerCase() !==
607
+ operation.keyAuthorization.toLowerCase())
608
+ throw new InvalidOperationError({
609
+ reason: 'keyAuthorization is not canonically serialized',
610
+ });
611
+ }
612
+ /**
613
+ * Validates a retained signature in the root owner's approval context.
614
+ *
615
+ * @internal
616
+ */
617
+ function assertApproval(account, serialized, config) {
618
+ const approval = SignatureEnvelope.deserialize(serialized);
619
+ SignatureEnvelope.assert({
620
+ account,
621
+ config,
622
+ signatures: [approval],
623
+ type: 'multisig',
624
+ });
625
+ if (SignatureEnvelope.serialize(approval).toLowerCase() !==
626
+ serialized.toLowerCase())
627
+ throw new InvalidOperationError({ reason: 'approval is not canonical' });
628
+ return approval;
629
+ }
630
+ /**
631
+ * Checks that selected transaction approvals are retained by the operation.
632
+ *
633
+ * @internal
634
+ */
635
+ function assertRetainedApprovals(operation, selected) {
636
+ const retained = operation.approvals.map((approval) => SignatureEnvelope.deserialize(approval));
637
+ for (const approval of selected) {
638
+ const index = retained.findIndex((candidate) => includesApproval(candidate, approval));
639
+ if (index === -1)
640
+ throw new InvalidOperationError({
641
+ reason: 'transaction signature is not a retained approval',
642
+ });
643
+ retained.splice(index, 1);
644
+ }
645
+ }
646
+ /**
647
+ * Checks that a successful key authorization uses retained approvals in canonical order.
648
+ *
649
+ * @internal
650
+ */
651
+ function assertSelectedApprovals(operation, selected, authorization) {
652
+ const retained = operation.approvals.map((approval) => SignatureEnvelope.deserialize(approval));
653
+ for (const approval of selected) {
654
+ const index = retained.findIndex((candidate) => includesApproval(candidate, approval));
655
+ if (index === -1)
656
+ throw new InvalidOperationError({
657
+ reason: 'key authorization signature is not a retained approval',
658
+ });
659
+ retained.splice(index, 1);
660
+ }
661
+ const digest = MultisigConfig.getSignPayload({
662
+ account: operation.account,
663
+ config: operation.config,
664
+ payload: KeyAuthorization_.getSignPayload(authorization),
665
+ });
666
+ const addresses = selected.map((signature) => SignatureEnvelope.extractAddress({ payload: digest, signature }));
667
+ for (let index = 1; index < addresses.length; index++) {
668
+ const previous = Hex.toBigInt(addresses[index - 1]);
669
+ const current = Hex.toBigInt(addresses[index]);
670
+ if (previous === current)
671
+ throw new InvalidOperationError({
672
+ reason: 'key authorization contains duplicate owner approvals',
673
+ });
674
+ if (previous > current)
675
+ throw new InvalidOperationError({
676
+ reason: 'key authorization approvals are not canonically ordered',
677
+ });
678
+ }
679
+ }
680
+ /**
681
+ * Checks whether a selected approval is contained in a retained approval tree.
682
+ *
683
+ * @internal
684
+ */
685
+ function includesApproval(retained, selected) {
686
+ if (retained.type !== 'multisig' || selected.type !== 'multisig')
687
+ return (SignatureEnvelope.serialize(retained).toLowerCase() ===
688
+ SignatureEnvelope.serialize(selected).toLowerCase());
689
+ if (retained.account.toLowerCase() !== selected.account.toLowerCase())
690
+ return false;
691
+ if (!sameConfig(retained.config, selected.config))
692
+ return false;
693
+ let index = 0;
694
+ for (const approval of selected.signatures) {
695
+ while (index < retained.signatures.length &&
696
+ !includesApproval(retained.signatures[index], approval))
697
+ index++;
698
+ if (index === retained.signatures.length)
699
+ return false;
700
+ index++;
701
+ }
702
+ return true;
703
+ }
704
+ /**
705
+ * Checks whether exactly `signatureCount` retained owners can produce `weight`.
706
+ *
707
+ * @internal
708
+ */
709
+ function isWeightReachable(weights, signatureCount, weight) {
710
+ const reachable = Array.from({ length: signatureCount + 1 }, () => new Set());
711
+ reachable[0].add(0);
712
+ for (const ownerWeight of weights)
713
+ for (let count = signatureCount; count > 0; count--)
714
+ for (const current of reachable[count - 1])
715
+ reachable[count].add(current + ownerWeight);
716
+ return reachable[signatureCount].has(weight);
717
+ }
718
+ /**
719
+ * Validates the deterministic operation hash.
720
+ *
721
+ * @internal
722
+ */
723
+ function assertOperationHash(operation, payload) {
724
+ const hash = MultisigConfig.getSignPayload({
725
+ account: operation.account,
726
+ config: operation.config,
727
+ payload,
728
+ });
729
+ if (hash.toLowerCase() !== operation.hash.toLowerCase())
730
+ throw new InvalidOperationError({
731
+ reason: 'hash does not match the operation payload',
732
+ });
733
+ }
734
+ /**
735
+ * Validates a nonnegative safe integer field.
736
+ *
737
+ * @internal
738
+ */
739
+ function assertInteger(value, field) {
740
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
741
+ throw new InvalidOperationError({
742
+ reason: `${field} must be a nonnegative safe integer`,
743
+ });
744
+ }
745
+ /**
746
+ * Compares normalized multisig configurations.
747
+ *
748
+ * @internal
749
+ */
750
+ function sameConfig(a, b) {
751
+ const configA = MultisigConfig.from(a);
752
+ const configB = MultisigConfig.from(b);
753
+ return (Hex.isEqual(configA.salt ?? MultisigConfig.zeroSalt, configB.salt ?? MultisigConfig.zeroSalt) &&
754
+ configA.threshold === configB.threshold &&
755
+ configA.version === configB.version &&
756
+ configA.owners.length === configB.owners.length &&
757
+ configA.owners.every((owner, index) => {
758
+ const other = configB.owners[index];
759
+ return (Address.isEqual(owner.owner, other.owner) &&
760
+ owner.weight === other.weight);
761
+ }));
762
+ }
763
+ /** Thrown when a multisig owner approval is invalid. */
764
+ export class InvalidApprovalError extends Errors.BaseError {
765
+ name = 'MultisigOperation.InvalidApprovalError';
766
+ /**
767
+ * Creates an invalid multisig approval error.
768
+ *
769
+ * @example
770
+ * ```ts twoslash
771
+ * import { MultisigOperation } from 'ox/tempo'
772
+ *
773
+ * throw new MultisigOperation.InvalidApprovalError({
774
+ * reason: 'signature is from a non-owner'
775
+ * })
776
+ * ```
777
+ *
778
+ * @param options - Error options.
779
+ */
780
+ constructor(options = {}) {
781
+ super(options.reason
782
+ ? `Invalid multisig approval: ${options.reason}.`
783
+ : 'Invalid multisig approval.', { cause: options.cause });
784
+ }
785
+ }
786
+ /** Thrown when a multisig operation is malformed or internally inconsistent. */
787
+ export class InvalidOperationError extends Errors.BaseError {
788
+ name = 'MultisigOperation.InvalidOperationError';
789
+ /**
790
+ * Creates an invalid multisig operation error.
791
+ *
792
+ * @example
793
+ * ```ts twoslash
794
+ * import { MultisigOperation } from 'ox/tempo'
795
+ *
796
+ * throw new MultisigOperation.InvalidOperationError({
797
+ * reason: 'hash does not match the operation payload'
798
+ * })
799
+ * ```
800
+ *
801
+ * @param options - Error options.
802
+ */
803
+ constructor(options = {}) {
804
+ super(options.reason
805
+ ? `Invalid multisig operation: ${options.reason}.`
806
+ : 'Invalid multisig operation.', { cause: options.cause });
807
+ }
808
+ }
809
+ //# sourceMappingURL=MultisigOperation.js.map