ox 1.7.1 → 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 (121) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/core/Hash.js +1 -1
  3. package/dist/core/Hash.js.map +1 -1
  4. package/dist/tempo/KeyAuthorization.d.ts +1 -1
  5. package/dist/tempo/KeyAuthorization.d.ts.map +1 -1
  6. package/dist/tempo/MultisigConfig.d.ts +151 -83
  7. package/dist/tempo/MultisigConfig.d.ts.map +1 -1
  8. package/dist/tempo/MultisigConfig.js +164 -86
  9. package/dist/tempo/MultisigConfig.js.map +1 -1
  10. package/dist/tempo/MultisigOperation.d.ts +324 -0
  11. package/dist/tempo/MultisigOperation.d.ts.map +1 -0
  12. package/dist/tempo/MultisigOperation.js +809 -0
  13. package/dist/tempo/MultisigOperation.js.map +1 -0
  14. package/dist/tempo/MultisigWitness.d.ts +106 -0
  15. package/dist/tempo/MultisigWitness.d.ts.map +1 -0
  16. package/dist/tempo/MultisigWitness.js +118 -0
  17. package/dist/tempo/MultisigWitness.js.map +1 -0
  18. package/dist/tempo/RpcSchemaTempo.d.ts +35 -0
  19. package/dist/tempo/RpcSchemaTempo.d.ts.map +1 -1
  20. package/dist/tempo/SignatureEnvelope.d.ts +60 -80
  21. package/dist/tempo/SignatureEnvelope.d.ts.map +1 -1
  22. package/dist/tempo/SignatureEnvelope.js +87 -146
  23. package/dist/tempo/SignatureEnvelope.js.map +1 -1
  24. package/dist/tempo/TransactionRequest.d.ts +9 -17
  25. package/dist/tempo/TransactionRequest.d.ts.map +1 -1
  26. package/dist/tempo/TransactionRequest.js +7 -7
  27. package/dist/tempo/TransactionRequest.js.map +1 -1
  28. package/dist/tempo/TxEnvelopeTempo.d.ts +3 -2
  29. package/dist/tempo/TxEnvelopeTempo.d.ts.map +1 -1
  30. package/dist/tempo/TxEnvelopeTempo.js +3 -2
  31. package/dist/tempo/TxEnvelopeTempo.js.map +1 -1
  32. package/dist/tempo/index.d.ts +22 -2
  33. package/dist/tempo/index.d.ts.map +1 -1
  34. package/dist/tempo/index.js +22 -2
  35. package/dist/tempo/index.js.map +1 -1
  36. package/dist/zod/tempo/AuthorizationTempo.d.ts +110 -110
  37. package/dist/zod/tempo/AuthorizationTempo.d.ts.map +1 -1
  38. package/dist/zod/tempo/KeyAuthorization.d.ts +90 -83
  39. package/dist/zod/tempo/KeyAuthorization.d.ts.map +1 -1
  40. package/dist/zod/tempo/MultisigConfig.d.ts +31 -2
  41. package/dist/zod/tempo/MultisigConfig.d.ts.map +1 -1
  42. package/dist/zod/tempo/MultisigConfig.js +26 -3
  43. package/dist/zod/tempo/MultisigConfig.js.map +1 -1
  44. package/dist/zod/tempo/MultisigOperation.d.ts +168 -0
  45. package/dist/zod/tempo/MultisigOperation.d.ts.map +1 -0
  46. package/dist/zod/tempo/MultisigOperation.js +65 -0
  47. package/dist/zod/tempo/MultisigOperation.js.map +1 -0
  48. package/dist/zod/tempo/MultisigWitness.d.ts +152 -0
  49. package/dist/zod/tempo/MultisigWitness.d.ts.map +1 -0
  50. package/dist/zod/tempo/MultisigWitness.js +76 -0
  51. package/dist/zod/tempo/MultisigWitness.js.map +1 -0
  52. package/dist/zod/tempo/RpcSchemaTempo.d.ts +607 -102
  53. package/dist/zod/tempo/RpcSchemaTempo.d.ts.map +1 -1
  54. package/dist/zod/tempo/RpcSchemaTempo.js +38 -0
  55. package/dist/zod/tempo/RpcSchemaTempo.js.map +1 -1
  56. package/dist/zod/tempo/SignatureEnvelope.d.ts +33 -33
  57. package/dist/zod/tempo/SignatureEnvelope.d.ts.map +1 -1
  58. package/dist/zod/tempo/SignatureEnvelope.js +9 -16
  59. package/dist/zod/tempo/SignatureEnvelope.js.map +1 -1
  60. package/dist/zod/tempo/Transaction.d.ts +228 -222
  61. package/dist/zod/tempo/Transaction.d.ts.map +1 -1
  62. package/dist/zod/tempo/TransactionRequest.d.ts +379 -176
  63. package/dist/zod/tempo/TransactionRequest.d.ts.map +1 -1
  64. package/dist/zod/tempo/TransactionRequest.js +11 -22
  65. package/dist/zod/tempo/TransactionRequest.js.map +1 -1
  66. package/dist/zod/tempo/TxEnvelopeTempo.d.ts +60 -48
  67. package/dist/zod/tempo/TxEnvelopeTempo.d.ts.map +1 -1
  68. package/dist/zod/tempo/ZoneRpcAuthentication.d.ts +15 -12
  69. package/dist/zod/tempo/ZoneRpcAuthentication.d.ts.map +1 -1
  70. package/dist/zod/tempo/z.d.ts +2 -0
  71. package/dist/zod/tempo/z.d.ts.map +1 -1
  72. package/dist/zod/tempo/z.js +2 -0
  73. package/dist/zod/tempo/z.js.map +1 -1
  74. package/package.json +21 -1
  75. package/src/core/Hash.ts +1 -1
  76. package/src/core/_test/Hash.test.ts +15 -0
  77. package/src/tempo/KeyAuthorization.test-d.ts +13 -1
  78. package/src/tempo/KeyAuthorization.test.ts +65 -0
  79. package/src/tempo/KeyAuthorization.ts +1 -1
  80. package/src/tempo/MultisigConfig.test-d.ts +52 -0
  81. package/src/tempo/MultisigConfig.test.ts +288 -227
  82. package/src/tempo/MultisigConfig.ts +275 -104
  83. package/src/tempo/MultisigOperation.test-d.ts +77 -0
  84. package/src/tempo/MultisigOperation.test.ts +1883 -0
  85. package/src/tempo/MultisigOperation.ts +1254 -0
  86. package/src/tempo/MultisigWitness.test-d.ts +42 -0
  87. package/src/tempo/MultisigWitness.test.ts +288 -0
  88. package/src/tempo/MultisigWitness.ts +210 -0
  89. package/src/tempo/RpcSchemaTempo.test-d.ts +56 -0
  90. package/src/tempo/RpcSchemaTempo.ts +37 -0
  91. package/src/tempo/SignatureEnvelope.test-d.ts +63 -46
  92. package/src/tempo/SignatureEnvelope.test.ts +523 -500
  93. package/src/tempo/SignatureEnvelope.ts +172 -242
  94. package/src/tempo/TransactionRequest.test-d.ts +11 -0
  95. package/src/tempo/TransactionRequest.test.ts +285 -33
  96. package/src/tempo/TransactionRequest.ts +15 -20
  97. package/src/tempo/TxEnvelopeTempo.test-d.ts +7 -0
  98. package/src/tempo/TxEnvelopeTempo.test.ts +25 -0
  99. package/src/tempo/TxEnvelopeTempo.ts +5 -3
  100. package/src/tempo/index.ts +22 -2
  101. package/src/tempo/multisig.e2e.test.ts +113 -86
  102. package/src/version.ts +1 -1
  103. package/src/zod/tempo/MultisigConfig.ts +29 -3
  104. package/src/zod/tempo/MultisigOperation.ts +69 -0
  105. package/src/zod/tempo/MultisigWitness.ts +101 -0
  106. package/src/zod/tempo/RpcSchemaTempo.ts +43 -0
  107. package/src/zod/tempo/SignatureEnvelope.ts +20 -38
  108. package/src/zod/tempo/TransactionRequest.ts +17 -26
  109. package/src/zod/tempo/_test/KeyAuthorization.test.ts +11 -0
  110. package/src/zod/tempo/_test/MultisigConfig.test-d.ts +13 -0
  111. package/src/zod/tempo/_test/MultisigConfig.test.ts +13 -2
  112. package/src/zod/tempo/_test/MultisigOperation.test-d.ts +27 -0
  113. package/src/zod/tempo/_test/MultisigOperation.test.ts +68 -0
  114. package/src/zod/tempo/_test/MultisigWitness.test-d.ts +13 -0
  115. package/src/zod/tempo/_test/MultisigWitness.test.ts +149 -0
  116. package/src/zod/tempo/_test/RpcSchemaTempo.test-d.ts +31 -0
  117. package/src/zod/tempo/_test/RpcSchemaTempo.test.ts +41 -0
  118. package/src/zod/tempo/_test/SignatureEnvelope.test-d.ts +1 -1
  119. package/src/zod/tempo/_test/SignatureEnvelope.test.ts +25 -34
  120. package/src/zod/tempo/_test/TransactionRequest.test.ts +176 -8
  121. package/src/zod/tempo/z.ts +2 -0
@@ -0,0 +1,1254 @@
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
+
10
+ /** Fields shared by every multisig operation. */
11
+ export type Base<quantity = bigint> = {
12
+ /** Root multisig account. */
13
+ account: Address.Address
14
+ /** Every retained serialized owner approval. */
15
+ approvals: readonly Hex.Hex[]
16
+ /** Root configuration used to verify approvals. */
17
+ config: MultisigConfig.Config<quantity>
18
+ /** Root configuration version. */
19
+ configVersion: quantity
20
+ /** Unix creation time in milliseconds. */
21
+ createdAt: number
22
+ /** Deterministic multisig operation hash. */
23
+ hash: Hex.Hex
24
+ /** Whether the operation initializes the root multisig account. */
25
+ init: boolean
26
+ /** Number of approvals selected for quorum evaluation. */
27
+ signatureCount: number
28
+ /** Required root owner weight. */
29
+ threshold: number
30
+ /** Unix time of the last update in milliseconds. */
31
+ updatedAt: number
32
+ /** Root owner weight reached by the selected approvals. */
33
+ weight: number
34
+ }
35
+
36
+ /** Multisig transaction approval operation. */
37
+ export type TransactionOperation<quantity = bigint> = Base<quantity> & {
38
+ /** Time when another relay may reclaim the submission lease. */
39
+ expiresAt?: number | undefined
40
+ /** Current operation state. */
41
+ status: 'pending' | 'submitting' | 'success'
42
+ /** Fencing token owned by the current submitter. */
43
+ submissionId?: Hex.Hex | undefined
44
+ /** Canonical serialized Tempo envelope without its outer sender signature. */
45
+ transaction: Hex.Hex
46
+ /** Hash returned after the downstream submitter accepts the transaction. */
47
+ transactionHash?: Hex.Hex | undefined
48
+ /** Operation kind. */
49
+ type: 'transaction'
50
+ }
51
+
52
+ /** Multisig key authorization approval operation. */
53
+ export type KeyAuthorizationOperation<quantity = bigint> = Base<quantity> & {
54
+ /** Canonical serialized key authorization. */
55
+ keyAuthorization: Hex.Hex
56
+ /** Current operation state. */
57
+ status: 'pending' | 'success'
58
+ /** Operation kind. */
59
+ type: 'keyAuthorization'
60
+ }
61
+
62
+ /** Transaction or key authorization multisig operation. */
63
+ export type Operation<quantity = bigint> =
64
+ | TransactionOperation<quantity>
65
+ | KeyAuthorizationOperation<quantity>
66
+
67
+ /** JSON-RPC multisig transaction operation. */
68
+ export type TransactionRpc = TransactionOperation<Hex.Hex>
69
+
70
+ /** JSON-RPC multisig key authorization operation. */
71
+ export type KeyAuthorizationRpc = KeyAuthorizationOperation<Hex.Hex>
72
+
73
+ /** JSON-RPC multisig operation. */
74
+ export type Rpc = Operation<Hex.Hex>
75
+
76
+ /** Maximum supported multisig configuration version. */
77
+ const maxConfigVersion = 2n ** 64n - 1n
78
+
79
+ /**
80
+ * Derives the deterministic hash for a multisig operation.
81
+ *
82
+ * @example
83
+ * ```ts twoslash
84
+ * // @noErrors
85
+ * import { MultisigOperation } from 'ox/tempo'
86
+ *
87
+ * const hash = MultisigOperation.getHash({
88
+ * account,
89
+ * configVersion: 1n,
90
+ * transaction,
91
+ * type: 'transaction'
92
+ * })
93
+ * ```
94
+ *
95
+ * @param options - Operation payload and multisig identity.
96
+ * @returns The operation hash signed by each owner.
97
+ */
98
+ export function getHash(options: getHash.Options): Hex.Hex {
99
+ const { account, configVersion } = options
100
+ const payload =
101
+ options.type === 'transaction'
102
+ ? TxEnvelopeTempo.getSignPayload(
103
+ TxEnvelopeTempo.deserialize(options.transaction),
104
+ )
105
+ : KeyAuthorization_.getSignPayload(
106
+ KeyAuthorization_.deserialize(options.keyAuthorization),
107
+ )
108
+ return MultisigConfig.getSignPayload({
109
+ account,
110
+ config: { version: configVersion },
111
+ payload,
112
+ })
113
+ }
114
+
115
+ export declare namespace getHash {
116
+ /** Parameters for `getHash`. */
117
+ export type Options = {
118
+ /** Root multisig account. */
119
+ account: Address.Address
120
+ /** Root configuration version. */
121
+ configVersion: bigint
122
+ } & (
123
+ | {
124
+ /** Canonical serialized key authorization. */
125
+ keyAuthorization: Hex.Hex
126
+ /** Operation kind. */
127
+ type: 'keyAuthorization'
128
+ }
129
+ | {
130
+ /** Canonical serialized Tempo envelope without its outer sender signature. */
131
+ transaction: TxEnvelopeTempo.Serialized
132
+ /** Operation kind. */
133
+ type: 'transaction'
134
+ }
135
+ )
136
+
137
+ /** Error type for `getHash`. */
138
+ export type ErrorType =
139
+ | KeyAuthorization_.deserialize.ErrorType
140
+ | KeyAuthorization_.getSignPayload.ErrorType
141
+ | MultisigConfig.getSignPayload.ErrorType
142
+ | TxEnvelopeTempo.deserialize.ErrorType
143
+ | TxEnvelopeTempo.getSignPayload.ErrorType
144
+ | Errors.GlobalErrorType
145
+ }
146
+
147
+ /**
148
+ * Validates, deduplicates, and selects owner approvals for an operation.
149
+ *
150
+ * The function retains one canonical approval per owner. It selects the
151
+ * smallest deterministic quorum by owner weight, then orders the selected
152
+ * approvals by owner address for serialization.
153
+ *
154
+ * @example
155
+ * ```ts twoslash
156
+ * // @noErrors
157
+ * import { MultisigOperation } from 'ox/tempo'
158
+ *
159
+ * const selection = await MultisigOperation.selectApprovals({
160
+ * account,
161
+ * approvals,
162
+ * config,
163
+ * hash,
164
+ * resolveConfig
165
+ * })
166
+ * ```
167
+ *
168
+ * @param options - Approval selection parameters.
169
+ * @returns The retained approvals and deterministic quorum selection.
170
+ */
171
+ export async function selectApprovals(
172
+ options: selectApprovals.Options,
173
+ ): Promise<selectApprovals.ReturnValue> {
174
+ const { account, approvals, hash, resolveConfig } = options
175
+ if (!Address.validate(account) || Hex.toBigInt(account) === 0n)
176
+ throw new InvalidApprovalError({ reason: 'account is invalid' })
177
+ if (!Hash.validate(hash))
178
+ throw new InvalidApprovalError({ reason: 'hash is invalid' })
179
+ return selectApprovals_internal(
180
+ {
181
+ account,
182
+ approvals,
183
+ config: MultisigConfig.from(options.config),
184
+ hash,
185
+ resolveConfig,
186
+ },
187
+ [account.toLowerCase()],
188
+ )
189
+ }
190
+
191
+ export declare namespace selectApprovals {
192
+ /** Parameters for `selectApprovals`. */
193
+ export type Options = {
194
+ /** Root multisig account. */
195
+ account: Address.Address
196
+ /** Serialized primitive or nested owner approvals. */
197
+ approvals: readonly SignatureEnvelope.Serialized[]
198
+ /** Current root multisig configuration. */
199
+ config: MultisigConfig.Config
200
+ /** Deterministic operation hash approved by root owners. */
201
+ hash: Hex.Hex
202
+ /** Resolves the current configuration of a nested multisig owner. */
203
+ resolveConfig?: ResolveConfig | undefined
204
+ }
205
+
206
+ /** Resolves an initialized nested multisig configuration. */
207
+ export type ResolveConfig = (
208
+ options: ResolveConfigOptions,
209
+ ) => ResolvedConfig | Promise<ResolvedConfig>
210
+
211
+ /** Nested multisig configuration lookup parameters. */
212
+ export type ResolveConfigOptions = {
213
+ /** Nested multisig account. */
214
+ account: Address.Address
215
+ }
216
+
217
+ /** Resolved nested multisig configuration. */
218
+ export type ResolvedConfig = {
219
+ /** Current nested multisig configuration. */
220
+ config: MultisigConfig.Config
221
+ /** Current nested multisig configuration version. */
222
+ version: bigint
223
+ }
224
+
225
+ /** Result of validating and selecting approvals. */
226
+ export type ReturnValue = {
227
+ /** Every retained approval, ordered by owner address. */
228
+ approvals: readonly SignatureEnvelope.Serialized[]
229
+ /** Number of approvals selected for quorum evaluation. */
230
+ signatureCount: number
231
+ /** Approvals selected for serialization, ordered by owner address. */
232
+ selectedApprovals: readonly SignatureEnvelope.Serialized[]
233
+ /** Required owner weight. */
234
+ threshold: number
235
+ /** Owner weight reached by the selected approvals. */
236
+ weight: number
237
+ }
238
+
239
+ /** Error type for `selectApprovals`. */
240
+ export type ErrorType =
241
+ | InvalidApprovalError
242
+ | MultisigConfig.assert.ErrorType
243
+ | MultisigConfig.getSignPayload.ErrorType
244
+ | SignatureEnvelope.CoercionError
245
+ | SignatureEnvelope.extractAddress.ErrorType
246
+ | SignatureEnvelope.serialize.ErrorType
247
+ | SignatureEnvelope.VerificationError
248
+ | Errors.GlobalErrorType
249
+ }
250
+
251
+ /**
252
+ * Serializes a multisig transaction operation with selected owner approvals.
253
+ *
254
+ * @example
255
+ * ```ts twoslash
256
+ * // @noErrors
257
+ * import { MultisigOperation } from 'ox/tempo'
258
+ *
259
+ * const transaction = MultisigOperation.serializeTransaction(
260
+ * operation,
261
+ * {
262
+ * approvals: selection.selectedApprovals
263
+ * }
264
+ * )
265
+ * ```
266
+ *
267
+ * @param operation - Multisig transaction operation.
268
+ * @param options - Transaction serialization options.
269
+ * @returns The signed serialized Tempo transaction.
270
+ */
271
+ export function serializeTransaction(
272
+ operation: TransactionOperation,
273
+ options: serializeTransaction.Options,
274
+ ): TxEnvelopeTempo.Serialized {
275
+ const value = from(operation)
276
+ const envelope = TxEnvelopeTempo.deserialize(
277
+ value.transaction as TxEnvelopeTempo.Serialized,
278
+ )
279
+ const approvals = options.approvals.map((approval) =>
280
+ SignatureEnvelope.from(approval),
281
+ )
282
+ assertRetainedApprovals(value, approvals)
283
+ const signatures = SignatureEnvelope.sortMultisigApprovals({
284
+ account: value.account,
285
+ config: value.config,
286
+ payload: TxEnvelopeTempo.getSignPayload(envelope),
287
+ signatures: approvals,
288
+ })
289
+ const signature = SignatureEnvelope.from({
290
+ account: value.account,
291
+ config: value.config,
292
+ signatures,
293
+ })
294
+ return TxEnvelopeTempo.serialize(
295
+ envelope,
296
+ value.transaction.startsWith(TxEnvelopeTempo.feePayerMagic)
297
+ ? {
298
+ format: 'feePayer',
299
+ sender: envelope.from,
300
+ signature,
301
+ }
302
+ : { signature },
303
+ )
304
+ }
305
+
306
+ export declare namespace serializeTransaction {
307
+ /** Options for `serializeTransaction`. */
308
+ export type Options = {
309
+ /** Selected retained approvals to attach to the transaction. */
310
+ approvals: readonly SignatureEnvelope.Serialized[]
311
+ }
312
+
313
+ /** Error type for `serializeTransaction`. */
314
+ export type ErrorType =
315
+ | from.ErrorType
316
+ | InvalidOperationError
317
+ | SignatureEnvelope.sortMultisigApprovals.ErrorType
318
+ | TxEnvelopeTempo.deserialize.ErrorType
319
+ | TxEnvelopeTempo.getSignPayload.ErrorType
320
+ | TxEnvelopeTempo.serialize.ErrorType
321
+ | Errors.GlobalErrorType
322
+ }
323
+
324
+ /**
325
+ * Validates and normalizes a multisig operation.
326
+ *
327
+ * @example
328
+ * ```ts twoslash
329
+ * // @noErrors
330
+ * import { MultisigOperation } from 'ox/tempo'
331
+ *
332
+ * const operation = MultisigOperation.from(value)
333
+ * ```
334
+ *
335
+ * @param operation - Multisig operation.
336
+ * @returns The validated operation.
337
+ */
338
+ export function from<const operation extends Operation>(
339
+ operation: operation,
340
+ ): from.ReturnValue<operation> {
341
+ try {
342
+ const config = MultisigConfig.from(operation.config)
343
+ if (config.version !== operation.configVersion)
344
+ throw new InvalidOperationError({
345
+ reason: 'config.version must equal configVersion',
346
+ })
347
+ if (
348
+ typeof config.threshold !== 'number' ||
349
+ config.owners.some((owner) => typeof owner.weight !== 'number')
350
+ )
351
+ throw new InvalidOperationError({
352
+ reason: 'config threshold and owner weights must be numbers',
353
+ })
354
+ const value = { ...operation, config } as Operation
355
+ assertBase(value, config)
356
+ if (value.type === 'transaction') assertTransaction(value)
357
+ else if (value.type === 'keyAuthorization')
358
+ assertKeyAuthorization(value, config)
359
+ else throw new InvalidOperationError({ reason: 'unknown operation type' })
360
+ return value as never
361
+ } catch (cause) {
362
+ if (cause instanceof InvalidOperationError) throw cause
363
+ throw new InvalidOperationError({ cause })
364
+ }
365
+ }
366
+
367
+ export declare namespace from {
368
+ /** Return type for `from`. */
369
+ export type ReturnValue<operation extends Operation> =
370
+ operation extends TransactionOperation
371
+ ? TransactionOperation
372
+ : KeyAuthorizationOperation
373
+
374
+ /** Error type for `from`. */
375
+ export type ErrorType = InvalidOperationError | Errors.GlobalErrorType
376
+ }
377
+
378
+ /**
379
+ * Converts a JSON-RPC multisig operation to its domain representation.
380
+ *
381
+ * @example
382
+ * ```ts twoslash
383
+ * // @noErrors
384
+ * import { MultisigOperation } from 'ox/tempo'
385
+ *
386
+ * const operation = MultisigOperation.fromRpc(value)
387
+ * ```
388
+ *
389
+ * @param operation - JSON-RPC multisig operation.
390
+ * @returns The validated operation.
391
+ */
392
+ export function fromRpc<const operation extends Rpc>(
393
+ operation: operation,
394
+ ): fromRpc.ReturnValue<operation> {
395
+ try {
396
+ if (
397
+ typeof operation.configVersion !== 'string' ||
398
+ !Hex.validate(operation.configVersion)
399
+ )
400
+ throw new InvalidOperationError({
401
+ reason: 'configVersion must be a hexadecimal quantity',
402
+ })
403
+ const configVersion = Hex.toBigInt(operation.configVersion)
404
+ if (Hex.fromNumber(configVersion) !== operation.configVersion)
405
+ throw new InvalidOperationError({
406
+ reason: 'configVersion must use canonical quantity encoding',
407
+ })
408
+ return from({
409
+ ...operation,
410
+ config: MultisigConfig.fromRpc(operation.config),
411
+ configVersion,
412
+ } as Operation) as never
413
+ } catch (cause) {
414
+ if (cause instanceof InvalidOperationError) throw cause
415
+ throw new InvalidOperationError({ cause })
416
+ }
417
+ }
418
+
419
+ export declare namespace fromRpc {
420
+ /** Return type for `fromRpc`. */
421
+ export type ReturnValue<operation extends Rpc> =
422
+ operation extends TransactionRpc
423
+ ? TransactionOperation
424
+ : KeyAuthorizationOperation
425
+
426
+ /** Error type for `fromRpc`. */
427
+ export type ErrorType = InvalidOperationError | Errors.GlobalErrorType
428
+ }
429
+
430
+ /**
431
+ * Converts a multisig operation to its JSON-RPC representation.
432
+ *
433
+ * @example
434
+ * ```ts twoslash
435
+ * // @noErrors
436
+ * import { MultisigOperation } from 'ox/tempo'
437
+ *
438
+ * const operationRpc = MultisigOperation.toRpc(operation)
439
+ * ```
440
+ *
441
+ * @param operation - Multisig operation.
442
+ * @returns The JSON-RPC operation.
443
+ */
444
+ export function toRpc<const operation extends Operation>(
445
+ operation: operation,
446
+ ): toRpc.ReturnValue<operation> {
447
+ const value = from(operation)
448
+ return {
449
+ ...value,
450
+ config: MultisigConfig.toRpc(value.config),
451
+ configVersion: Hex.fromNumber(value.configVersion),
452
+ } as never
453
+ }
454
+
455
+ export declare namespace toRpc {
456
+ /** Return type for `toRpc`. */
457
+ export type ReturnValue<operation extends Operation> =
458
+ operation extends TransactionOperation
459
+ ? TransactionRpc
460
+ : KeyAuthorizationRpc
461
+
462
+ /** Error type for `toRpc`. */
463
+ export type ErrorType = from.ErrorType | Hex.fromNumber.ErrorType
464
+ }
465
+
466
+ /**
467
+ * Validates and selects approvals recursively.
468
+ *
469
+ * @internal
470
+ */
471
+ async function selectApprovals_internal(
472
+ options: selectApprovals.Options,
473
+ path: readonly string[],
474
+ ): Promise<selectApprovals.ReturnValue> {
475
+ const owners = new Map(
476
+ options.config.owners.map((owner) => [
477
+ owner.owner.toLowerCase(),
478
+ { address: owner.owner, weight: Number(owner.weight) },
479
+ ]),
480
+ )
481
+ const groups = new Map<string, ApprovalGroup>()
482
+ for (const serialized of options.approvals) {
483
+ const signature = SignatureEnvelope.from(serialized)
484
+ if (signature.type === 'keychain')
485
+ throw new InvalidApprovalError({
486
+ reason: 'keychain signatures cannot approve a multisig operation',
487
+ })
488
+ const address =
489
+ signature.type === 'multisig'
490
+ ? signature.account
491
+ : SignatureEnvelope.extractAddress({
492
+ payload: options.hash,
493
+ signature,
494
+ })
495
+ const owner = owners.get(address.toLowerCase())
496
+ if (!owner)
497
+ throw new InvalidApprovalError({
498
+ reason: `signature is from non-owner ${address}`,
499
+ })
500
+ const key = address.toLowerCase()
501
+ const group = groups.get(key)
502
+ if (group) group.signatures.push(signature)
503
+ else
504
+ groups.set(key, {
505
+ address: owner.address,
506
+ signatures: [signature],
507
+ weight: owner.weight,
508
+ })
509
+ }
510
+
511
+ const valid: SelectedApproval[] = []
512
+ const retained: RetainedApproval[] = []
513
+ for (const group of groups.values()) {
514
+ const nested = group.signatures.filter(
515
+ (signature) => signature.type === 'multisig',
516
+ )
517
+ if (nested.length > 0) {
518
+ if (nested.length !== group.signatures.length)
519
+ throw new InvalidApprovalError({
520
+ reason: `owner ${group.address} has conflicting signature types`,
521
+ })
522
+ if (
523
+ path.length >= MultisigConfig.maxNestingDepth ||
524
+ path.includes(group.address.toLowerCase())
525
+ )
526
+ throw new InvalidApprovalError({
527
+ reason: `nested multisig owner ${group.address} is invalid`,
528
+ })
529
+ if (!options.resolveConfig)
530
+ throw new InvalidApprovalError({
531
+ reason: `nested multisig owner ${group.address} requires a config resolver`,
532
+ })
533
+ const resolved = await options.resolveConfig({ account: group.address })
534
+ const config = MultisigConfig.from(resolved.config)
535
+ if (config.version !== resolved.version)
536
+ throw new InvalidApprovalError({
537
+ reason: `resolved config.version must equal version for nested multisig owner ${group.address}`,
538
+ })
539
+ const selected = await selectApprovals_internal(
540
+ {
541
+ account: group.address,
542
+ approvals: nested.flatMap((signature) =>
543
+ signature.signatures.map((approval) =>
544
+ SignatureEnvelope.serialize(approval),
545
+ ),
546
+ ),
547
+ config,
548
+ hash: MultisigConfig.getSignPayload({
549
+ account: group.address,
550
+ config,
551
+ payload: options.hash,
552
+ }),
553
+ resolveConfig: options.resolveConfig,
554
+ },
555
+ [...path, group.address.toLowerCase()],
556
+ )
557
+ retained.push({
558
+ address: group.address,
559
+ signature: SignatureEnvelope.serialize(
560
+ SignatureEnvelope.from({
561
+ account: group.address,
562
+ config,
563
+ signatures: selected.approvals.map((approval) =>
564
+ SignatureEnvelope.from(approval),
565
+ ),
566
+ }),
567
+ ),
568
+ })
569
+ if (selected.weight >= selected.threshold)
570
+ valid.push({
571
+ address: group.address,
572
+ signature: SignatureEnvelope.serialize(
573
+ SignatureEnvelope.from({
574
+ account: group.address,
575
+ config,
576
+ signatures: selected.selectedApprovals.map((approval) =>
577
+ SignatureEnvelope.from(approval),
578
+ ),
579
+ }),
580
+ ),
581
+ weight: group.weight,
582
+ })
583
+ continue
584
+ }
585
+
586
+ const signatures = group.signatures.map((signature) => {
587
+ if (
588
+ !SignatureEnvelope.verify(signature, {
589
+ address: group.address,
590
+ payload: options.hash,
591
+ })
592
+ )
593
+ throw new InvalidApprovalError({
594
+ reason: `signature from owner ${group.address} is invalid`,
595
+ })
596
+ return SignatureEnvelope.serialize(signature)
597
+ })
598
+ const signature = signatures.sort(compareHex)[0]!
599
+ valid.push({
600
+ address: group.address,
601
+ signature,
602
+ weight: group.weight,
603
+ })
604
+ retained.push({ address: group.address, signature })
605
+ }
606
+
607
+ const ranked = valid.sort(
608
+ (a, b) => b.weight - a.weight || compareApprovalAddress(a, b),
609
+ )
610
+ const selected: typeof ranked = []
611
+ let weight = 0
612
+ for (const approval of ranked.slice(0, MultisigConfig.maxSignatures)) {
613
+ if (weight >= Number(options.config.threshold)) break
614
+ selected.push(approval)
615
+ weight += approval.weight
616
+ }
617
+ selected.sort(compareApprovalAddress)
618
+
619
+ return {
620
+ approvals: retained
621
+ .sort(compareApprovalAddress)
622
+ .map((approval) => approval.signature),
623
+ selectedApprovals: selected.map((approval) => approval.signature),
624
+ signatureCount: selected.length,
625
+ threshold: Number(options.config.threshold),
626
+ weight,
627
+ }
628
+ }
629
+
630
+ /** Approval selected for quorum evaluation. @internal */
631
+ type SelectedApproval = {
632
+ /** Configured owner address. */
633
+ address: Address.Address
634
+ /** Serialized owner signature. */
635
+ signature: SignatureEnvelope.Serialized
636
+ /** Configured owner weight. */
637
+ weight: number
638
+ }
639
+
640
+ /** Approvals submitted for one configured owner. @internal */
641
+ type ApprovalGroup = {
642
+ /** Configured owner address. */
643
+ address: Address.Address
644
+ /** Submitted signatures that resolve to the owner. */
645
+ signatures: SignatureEnvelope.SignatureEnvelope[]
646
+ /** Configured owner weight. */
647
+ weight: number
648
+ }
649
+
650
+ /** Approval retained in operation storage. @internal */
651
+ type RetainedApproval = {
652
+ /** Configured owner address. */
653
+ address: Address.Address
654
+ /** Serialized primitive or normalized nested approval. */
655
+ signature: SignatureEnvelope.Serialized
656
+ }
657
+
658
+ /**
659
+ * Orders approval records by owner address.
660
+ *
661
+ * @internal
662
+ */
663
+ function compareApprovalAddress(
664
+ a: SelectedApproval | RetainedApproval,
665
+ b: SelectedApproval | RetainedApproval,
666
+ ) {
667
+ const addressA = Hex.toBigInt(a.address)
668
+ const addressB = Hex.toBigInt(b.address)
669
+ return addressA < addressB ? -1 : addressA > addressB ? 1 : 0
670
+ }
671
+
672
+ /**
673
+ * Orders hexadecimal data bytewise.
674
+ *
675
+ * @internal
676
+ */
677
+ function compareHex(a: Hex.Hex, b: Hex.Hex) {
678
+ const hexA = a.toLowerCase()
679
+ const hexB = b.toLowerCase()
680
+ return hexA < hexB ? -1 : hexA > hexB ? 1 : 0
681
+ }
682
+
683
+ /**
684
+ * Validates fields shared by every operation.
685
+ *
686
+ * @internal
687
+ */
688
+ function assertBase(operation: Operation, config: MultisigConfig.Config): void {
689
+ if (!Address.validate(operation.account))
690
+ throw new InvalidOperationError({ reason: 'account is invalid' })
691
+ if (Hex.toBigInt(operation.account) === 0n)
692
+ throw new InvalidOperationError({ reason: 'account cannot be zero' })
693
+ if (!Hash.validate(operation.hash))
694
+ throw new InvalidOperationError({ reason: 'hash is invalid' })
695
+ if (typeof operation.init !== 'boolean')
696
+ throw new InvalidOperationError({ reason: 'init must be a boolean' })
697
+ if (
698
+ typeof operation.configVersion !== 'bigint' ||
699
+ operation.configVersion < 0n ||
700
+ operation.configVersion > maxConfigVersion
701
+ )
702
+ throw new InvalidOperationError({
703
+ reason: 'configVersion must be an unsigned 64-bit integer',
704
+ })
705
+ assertInteger(operation.createdAt, 'createdAt')
706
+ assertInteger(operation.updatedAt, 'updatedAt')
707
+ if (operation.updatedAt < operation.createdAt)
708
+ throw new InvalidOperationError({
709
+ reason: 'updatedAt cannot precede createdAt',
710
+ })
711
+ assertInteger(operation.signatureCount, 'signatureCount')
712
+ assertInteger(operation.threshold, 'threshold')
713
+ assertInteger(operation.weight, 'weight')
714
+ if (operation.threshold !== Number(config.threshold))
715
+ throw new InvalidOperationError({
716
+ reason: 'threshold must equal config.threshold',
717
+ })
718
+ if (operation.weight > 0xff)
719
+ throw new InvalidOperationError({ reason: 'weight exceeds u8 max' })
720
+ if (operation.signatureCount > MultisigConfig.maxSignatures)
721
+ throw new InvalidOperationError({ reason: 'too many selected signatures' })
722
+ if (!Array.isArray(operation.approvals))
723
+ throw new InvalidOperationError({ reason: 'approvals must be an array' })
724
+ if (operation.approvals.length > config.owners.length)
725
+ throw new InvalidOperationError({ reason: 'too many retained approvals' })
726
+ if (operation.signatureCount > operation.approvals.length)
727
+ throw new InvalidOperationError({
728
+ reason: 'signatureCount exceeds retained approvals',
729
+ })
730
+ if ((operation.signatureCount === 0) !== (operation.weight === 0))
731
+ throw new InvalidOperationError({
732
+ reason: 'signatureCount and weight must both be zero or nonzero',
733
+ })
734
+ const owners = new Map(
735
+ config.owners.map((owner) => [
736
+ owner.owner.toLowerCase(),
737
+ Number(owner.weight),
738
+ ]),
739
+ )
740
+ const approvalWeights: number[] = []
741
+ const seen = new Set<string>()
742
+ for (const approval of operation.approvals) {
743
+ if (
744
+ typeof approval !== 'string' ||
745
+ !Hex.validate(approval, { strict: true })
746
+ )
747
+ throw new InvalidOperationError({ reason: 'approval is invalid' })
748
+ const signature = assertApproval(
749
+ operation.account,
750
+ approval as SignatureEnvelope.Serialized,
751
+ config,
752
+ )
753
+ const address = SignatureEnvelope.extractAddress({
754
+ payload: operation.hash,
755
+ signature,
756
+ })
757
+ const key = address.toLowerCase()
758
+ const weight = owners.get(key)
759
+ if (weight === undefined)
760
+ throw new InvalidOperationError({
761
+ reason: 'approval is from a non-owner',
762
+ })
763
+ if (seen.has(key))
764
+ throw new InvalidOperationError({
765
+ reason:
766
+ operation.type === 'keyAuthorization'
767
+ ? 'key authorization contains duplicate owner approvals'
768
+ : 'duplicate owner approval',
769
+ })
770
+ seen.add(key)
771
+ approvalWeights.push(weight)
772
+ }
773
+ if (
774
+ !isWeightReachable(
775
+ approvalWeights,
776
+ operation.signatureCount,
777
+ operation.weight,
778
+ )
779
+ )
780
+ throw new InvalidOperationError({
781
+ reason:
782
+ 'weight is not reachable by signatureCount retained owner approvals',
783
+ })
784
+ if (operation.init) {
785
+ if (operation.configVersion !== 0n)
786
+ throw new InvalidOperationError({
787
+ reason: 'bootstrap operations must use config version zero',
788
+ })
789
+ if (
790
+ MultisigConfig.getAddress(config).toLowerCase() !==
791
+ operation.account.toLowerCase()
792
+ )
793
+ throw new InvalidOperationError({
794
+ reason: 'bootstrap config does not derive the operation account',
795
+ })
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Validates a transaction operation and its state-specific fields.
801
+ *
802
+ * @internal
803
+ */
804
+ function assertTransaction(operation: TransactionOperation): void {
805
+ if (
806
+ 'keyAuthorization' in operation &&
807
+ operation.keyAuthorization !== undefined
808
+ )
809
+ throw new InvalidOperationError({
810
+ reason: 'transaction operations cannot contain keyAuthorization',
811
+ })
812
+ const expiresAt = operation.expiresAt
813
+ const submissionId = operation.submissionId
814
+ const transactionHash = operation.transactionHash
815
+ if (operation.status === 'pending') {
816
+ if (
817
+ expiresAt !== undefined ||
818
+ submissionId !== undefined ||
819
+ transactionHash !== undefined
820
+ )
821
+ throw new InvalidOperationError({
822
+ reason: 'pending transactions cannot contain submission fields',
823
+ })
824
+ } else if (operation.status === 'submitting') {
825
+ assertInteger(expiresAt, 'expiresAt')
826
+ if (!Hash.validate(submissionId ?? ''))
827
+ throw new InvalidOperationError({ reason: 'submissionId is invalid' })
828
+ if (submissionId!.toLowerCase() === operation.hash.toLowerCase())
829
+ throw new InvalidOperationError({
830
+ reason: 'submissionId must differ from the operation hash',
831
+ })
832
+ if (transactionHash !== undefined)
833
+ throw new InvalidOperationError({
834
+ reason: 'submitting transactions cannot contain transactionHash',
835
+ })
836
+ } else if (operation.status === 'success') {
837
+ if (!Hash.validate(transactionHash ?? ''))
838
+ throw new InvalidOperationError({ reason: 'transactionHash is invalid' })
839
+ if (expiresAt !== undefined || submissionId !== undefined)
840
+ throw new InvalidOperationError({
841
+ reason: 'successful transactions cannot contain submission fields',
842
+ })
843
+ } else
844
+ throw new InvalidOperationError({ reason: 'invalid transaction status' })
845
+ if (
846
+ operation.status !== 'pending' &&
847
+ (operation.weight < operation.threshold || operation.signatureCount === 0)
848
+ )
849
+ throw new InvalidOperationError({
850
+ reason: 'submitted transactions must have quorum',
851
+ })
852
+
853
+ if (typeof operation.transaction !== 'string')
854
+ throw new InvalidOperationError({ reason: 'transaction is invalid' })
855
+ const feePayer = operation.transaction.startsWith(
856
+ TxEnvelopeTempo.feePayerMagic,
857
+ )
858
+ const transaction = TxEnvelopeTempo.deserialize(
859
+ operation.transaction as TxEnvelopeTempo.Serialized,
860
+ )
861
+ if (transaction.signature)
862
+ throw new InvalidOperationError({
863
+ reason: 'transaction must not contain an outer sender signature',
864
+ })
865
+ if (
866
+ transaction.from &&
867
+ transaction.from.toLowerCase() !== operation.account.toLowerCase()
868
+ )
869
+ throw new InvalidOperationError({
870
+ reason: 'transaction sender does not match the operation account',
871
+ })
872
+ assertOperationHash(operation, TxEnvelopeTempo.getSignPayload(transaction))
873
+ const normalized = TxEnvelopeTempo.serialize(
874
+ transaction,
875
+ feePayer
876
+ ? transaction.from
877
+ ? { format: 'feePayer', sender: transaction.from }
878
+ : { format: 'feePayer' }
879
+ : {},
880
+ )
881
+ if (normalized.toLowerCase() !== operation.transaction.toLowerCase())
882
+ throw new InvalidOperationError({
883
+ reason: 'transaction is not canonically serialized',
884
+ })
885
+ }
886
+
887
+ /**
888
+ * Validates a key authorization operation and its serialized payload.
889
+ *
890
+ * @internal
891
+ */
892
+ function assertKeyAuthorization(
893
+ operation: KeyAuthorizationOperation,
894
+ config: MultisigConfig.Config,
895
+ ): void {
896
+ const transactionFields = operation as KeyAuthorizationOperation & {
897
+ expiresAt?: unknown
898
+ submissionId?: unknown
899
+ transaction?: unknown
900
+ transactionHash?: unknown
901
+ }
902
+ if (
903
+ transactionFields.expiresAt !== undefined ||
904
+ transactionFields.submissionId !== undefined ||
905
+ transactionFields.transaction !== undefined ||
906
+ transactionFields.transactionHash !== undefined
907
+ )
908
+ throw new InvalidOperationError({
909
+ reason: 'key authorization operations cannot contain transaction fields',
910
+ })
911
+ if (operation.status !== 'pending' && operation.status !== 'success')
912
+ throw new InvalidOperationError({
913
+ reason: 'invalid key authorization status',
914
+ })
915
+ if (
916
+ operation.status === 'success' &&
917
+ (operation.weight < operation.threshold || operation.signatureCount === 0)
918
+ )
919
+ throw new InvalidOperationError({
920
+ reason: 'successful key authorizations must have quorum',
921
+ })
922
+ if (operation.status === 'pending' && operation.weight >= operation.threshold)
923
+ throw new InvalidOperationError({
924
+ reason: 'pending key authorizations cannot have quorum',
925
+ })
926
+ if (typeof operation.keyAuthorization !== 'string')
927
+ throw new InvalidOperationError({ reason: 'keyAuthorization is invalid' })
928
+ const authorization = KeyAuthorization_.deserialize(
929
+ operation.keyAuthorization,
930
+ )
931
+ if (
932
+ !authorization.account ||
933
+ authorization.account.toLowerCase() !== operation.account.toLowerCase()
934
+ )
935
+ throw new InvalidOperationError({
936
+ reason: 'key authorization account does not match the operation account',
937
+ })
938
+ const signature = authorization.signature
939
+ if (operation.status === 'pending' && signature)
940
+ throw new InvalidOperationError({
941
+ reason: 'pending key authorizations must be unsigned',
942
+ })
943
+ if (operation.status === 'success') {
944
+ if (signature?.type !== 'multisig')
945
+ throw new InvalidOperationError({
946
+ reason: 'successful key authorizations require a multisig signature',
947
+ })
948
+ if (signature.account.toLowerCase() !== operation.account.toLowerCase())
949
+ throw new InvalidOperationError({
950
+ reason: 'key authorization signature account does not match',
951
+ })
952
+ if (signature.signatures.length !== operation.signatureCount)
953
+ throw new InvalidOperationError({
954
+ reason: 'key authorization signatureCount does not match its signature',
955
+ })
956
+ assertSelectedApprovals(operation, signature.signatures, authorization)
957
+ if (!sameConfig(signature.config, config))
958
+ throw new InvalidOperationError({
959
+ reason: 'key authorization config does not match',
960
+ })
961
+ }
962
+ assertOperationHash(
963
+ operation,
964
+ KeyAuthorization_.getSignPayload(authorization),
965
+ )
966
+ if (
967
+ KeyAuthorization_.serialize(authorization).toLowerCase() !==
968
+ operation.keyAuthorization.toLowerCase()
969
+ )
970
+ throw new InvalidOperationError({
971
+ reason: 'keyAuthorization is not canonically serialized',
972
+ })
973
+ }
974
+
975
+ /**
976
+ * Validates a retained signature in the root owner's approval context.
977
+ *
978
+ * @internal
979
+ */
980
+ function assertApproval(
981
+ account: Address.Address,
982
+ serialized: SignatureEnvelope.Serialized,
983
+ config: MultisigConfig.Config,
984
+ ): SignatureEnvelope.SignatureEnvelope {
985
+ const approval = SignatureEnvelope.deserialize(serialized)
986
+ SignatureEnvelope.assert({
987
+ account,
988
+ config,
989
+ signatures: [approval],
990
+ type: 'multisig',
991
+ })
992
+ if (
993
+ SignatureEnvelope.serialize(approval).toLowerCase() !==
994
+ serialized.toLowerCase()
995
+ )
996
+ throw new InvalidOperationError({ reason: 'approval is not canonical' })
997
+ return approval
998
+ }
999
+
1000
+ /**
1001
+ * Checks that selected transaction approvals are retained by the operation.
1002
+ *
1003
+ * @internal
1004
+ */
1005
+ function assertRetainedApprovals(
1006
+ operation: TransactionOperation,
1007
+ selected: readonly SignatureEnvelope.SignatureEnvelope[],
1008
+ ): void {
1009
+ const retained = operation.approvals.map((approval) =>
1010
+ SignatureEnvelope.deserialize(approval),
1011
+ )
1012
+ for (const approval of selected) {
1013
+ const index = retained.findIndex((candidate) =>
1014
+ includesApproval(candidate, approval),
1015
+ )
1016
+ if (index === -1)
1017
+ throw new InvalidOperationError({
1018
+ reason: 'transaction signature is not a retained approval',
1019
+ })
1020
+ retained.splice(index, 1)
1021
+ }
1022
+ }
1023
+
1024
+ /**
1025
+ * Checks that a successful key authorization uses retained approvals in canonical order.
1026
+ *
1027
+ * @internal
1028
+ */
1029
+ function assertSelectedApprovals(
1030
+ operation: KeyAuthorizationOperation,
1031
+ selected: readonly SignatureEnvelope.SignatureEnvelope[],
1032
+ authorization: KeyAuthorization_.KeyAuthorization,
1033
+ ): void {
1034
+ const retained = operation.approvals.map((approval) =>
1035
+ SignatureEnvelope.deserialize(approval),
1036
+ )
1037
+ for (const approval of selected) {
1038
+ const index = retained.findIndex((candidate) =>
1039
+ includesApproval(candidate, approval),
1040
+ )
1041
+ if (index === -1)
1042
+ throw new InvalidOperationError({
1043
+ reason: 'key authorization signature is not a retained approval',
1044
+ })
1045
+ retained.splice(index, 1)
1046
+ }
1047
+
1048
+ const digest = MultisigConfig.getSignPayload({
1049
+ account: operation.account,
1050
+ config: operation.config,
1051
+ payload: KeyAuthorization_.getSignPayload(authorization),
1052
+ })
1053
+ const addresses = selected.map((signature) =>
1054
+ SignatureEnvelope.extractAddress({ payload: digest, signature }),
1055
+ )
1056
+ for (let index = 1; index < addresses.length; index++) {
1057
+ const previous = Hex.toBigInt(addresses[index - 1]!)
1058
+ const current = Hex.toBigInt(addresses[index]!)
1059
+ if (previous === current)
1060
+ throw new InvalidOperationError({
1061
+ reason: 'key authorization contains duplicate owner approvals',
1062
+ })
1063
+ if (previous > current)
1064
+ throw new InvalidOperationError({
1065
+ reason: 'key authorization approvals are not canonically ordered',
1066
+ })
1067
+ }
1068
+ }
1069
+
1070
+ /**
1071
+ * Checks whether a selected approval is contained in a retained approval tree.
1072
+ *
1073
+ * @internal
1074
+ */
1075
+ function includesApproval(
1076
+ retained: SignatureEnvelope.SignatureEnvelope,
1077
+ selected: SignatureEnvelope.SignatureEnvelope,
1078
+ ): boolean {
1079
+ if (retained.type !== 'multisig' || selected.type !== 'multisig')
1080
+ return (
1081
+ SignatureEnvelope.serialize(retained).toLowerCase() ===
1082
+ SignatureEnvelope.serialize(selected).toLowerCase()
1083
+ )
1084
+ if (retained.account.toLowerCase() !== selected.account.toLowerCase())
1085
+ return false
1086
+ if (!sameConfig(retained.config, selected.config)) return false
1087
+ let index = 0
1088
+ for (const approval of selected.signatures) {
1089
+ while (
1090
+ index < retained.signatures.length &&
1091
+ !includesApproval(retained.signatures[index]!, approval)
1092
+ )
1093
+ index++
1094
+ if (index === retained.signatures.length) return false
1095
+ index++
1096
+ }
1097
+ return true
1098
+ }
1099
+
1100
+ /**
1101
+ * Checks whether exactly `signatureCount` retained owners can produce `weight`.
1102
+ *
1103
+ * @internal
1104
+ */
1105
+ function isWeightReachable(
1106
+ weights: readonly number[],
1107
+ signatureCount: number,
1108
+ weight: number,
1109
+ ): boolean {
1110
+ const reachable = Array.from(
1111
+ { length: signatureCount + 1 },
1112
+ () => new Set<number>(),
1113
+ )
1114
+ reachable[0]!.add(0)
1115
+ for (const ownerWeight of weights)
1116
+ for (let count = signatureCount; count > 0; count--)
1117
+ for (const current of reachable[count - 1]!)
1118
+ reachable[count]!.add(current + ownerWeight)
1119
+ return reachable[signatureCount]!.has(weight)
1120
+ }
1121
+
1122
+ /**
1123
+ * Validates the deterministic operation hash.
1124
+ *
1125
+ * @internal
1126
+ */
1127
+ function assertOperationHash(operation: Operation, payload: Hex.Hex): void {
1128
+ const hash = MultisigConfig.getSignPayload({
1129
+ account: operation.account,
1130
+ config: operation.config,
1131
+ payload,
1132
+ })
1133
+ if (hash.toLowerCase() !== operation.hash.toLowerCase())
1134
+ throw new InvalidOperationError({
1135
+ reason: 'hash does not match the operation payload',
1136
+ })
1137
+ }
1138
+
1139
+ /**
1140
+ * Validates a nonnegative safe integer field.
1141
+ *
1142
+ * @internal
1143
+ */
1144
+ function assertInteger(value: unknown, field: string): asserts value is number {
1145
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
1146
+ throw new InvalidOperationError({
1147
+ reason: `${field} must be a nonnegative safe integer`,
1148
+ })
1149
+ }
1150
+
1151
+ /**
1152
+ * Compares normalized multisig configurations.
1153
+ *
1154
+ * @internal
1155
+ */
1156
+ function sameConfig(
1157
+ a: MultisigConfig.Config,
1158
+ b: MultisigConfig.Config,
1159
+ ): boolean {
1160
+ const configA = MultisigConfig.from(a)
1161
+ const configB = MultisigConfig.from(b)
1162
+ return (
1163
+ Hex.isEqual(
1164
+ configA.salt ?? MultisigConfig.zeroSalt,
1165
+ configB.salt ?? MultisigConfig.zeroSalt,
1166
+ ) &&
1167
+ configA.threshold === configB.threshold &&
1168
+ configA.version === configB.version &&
1169
+ configA.owners.length === configB.owners.length &&
1170
+ configA.owners.every((owner, index) => {
1171
+ const other = configB.owners[index]!
1172
+ return (
1173
+ Address.isEqual(owner.owner, other.owner) &&
1174
+ owner.weight === other.weight
1175
+ )
1176
+ })
1177
+ )
1178
+ }
1179
+
1180
+ /** Thrown when a multisig owner approval is invalid. */
1181
+ export class InvalidApprovalError extends Errors.BaseError<Error | undefined> {
1182
+ override readonly name = 'MultisigOperation.InvalidApprovalError'
1183
+
1184
+ /**
1185
+ * Creates an invalid multisig approval error.
1186
+ *
1187
+ * @example
1188
+ * ```ts twoslash
1189
+ * import { MultisigOperation } from 'ox/tempo'
1190
+ *
1191
+ * throw new MultisigOperation.InvalidApprovalError({
1192
+ * reason: 'signature is from a non-owner'
1193
+ * })
1194
+ * ```
1195
+ *
1196
+ * @param options - Error options.
1197
+ */
1198
+ constructor(options: InvalidApprovalError.Options = {}) {
1199
+ super(
1200
+ options.reason
1201
+ ? `Invalid multisig approval: ${options.reason}.`
1202
+ : 'Invalid multisig approval.',
1203
+ { cause: options.cause as Error | undefined },
1204
+ )
1205
+ }
1206
+ }
1207
+
1208
+ export declare namespace InvalidApprovalError {
1209
+ /** Error construction options. */
1210
+ export type Options = {
1211
+ /** Underlying error. */
1212
+ cause?: unknown | undefined
1213
+ /** Validation failure. */
1214
+ reason?: string | undefined
1215
+ }
1216
+ }
1217
+
1218
+ /** Thrown when a multisig operation is malformed or internally inconsistent. */
1219
+ export class InvalidOperationError extends Errors.BaseError<Error | undefined> {
1220
+ override readonly name = 'MultisigOperation.InvalidOperationError'
1221
+
1222
+ /**
1223
+ * Creates an invalid multisig operation error.
1224
+ *
1225
+ * @example
1226
+ * ```ts twoslash
1227
+ * import { MultisigOperation } from 'ox/tempo'
1228
+ *
1229
+ * throw new MultisigOperation.InvalidOperationError({
1230
+ * reason: 'hash does not match the operation payload'
1231
+ * })
1232
+ * ```
1233
+ *
1234
+ * @param options - Error options.
1235
+ */
1236
+ constructor(options: InvalidOperationError.Options = {}) {
1237
+ super(
1238
+ options.reason
1239
+ ? `Invalid multisig operation: ${options.reason}.`
1240
+ : 'Invalid multisig operation.',
1241
+ { cause: options.cause as Error | undefined },
1242
+ )
1243
+ }
1244
+ }
1245
+
1246
+ export declare namespace InvalidOperationError {
1247
+ /** Error construction options. */
1248
+ export type Options = {
1249
+ /** Underlying error. */
1250
+ cause?: unknown | undefined
1251
+ /** Validation failure. */
1252
+ reason?: string | undefined
1253
+ }
1254
+ }