ox 0.14.36 → 0.14.38

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