ox 0.14.27 → 0.14.29

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,501 @@
1
+ import * as Address from '../core/Address.js'
2
+ import type * as Bytes from '../core/Bytes.js'
3
+ import * as Errors from '../core/Errors.js'
4
+ import * as Hash from '../core/Hash.js'
5
+ import * as Hex from '../core/Hex.js'
6
+ import type { Compute, OneOf } from '../core/internal/types.js'
7
+
8
+ /** Maximum number of owners allowed in a native multisig config. */
9
+ export const maxOwners = 10
10
+
11
+ /** Maximum encoded byte length for one primitive owner approval. */
12
+ export const maxOwnerSignatureBytes = 2049
13
+
14
+ /** Tempo signature type byte for native multisig signatures. */
15
+ export const signatureTypeByte = '0x05' as const
16
+
17
+ /** Zero 32-byte salt (the default when no salt is provided). */
18
+ export const zeroSalt = `0x${'00'.repeat(32)}` as const
19
+
20
+ /** Domain prefix for the native multisig account address derivation. */
21
+ const accountDomain = 'tempo:multisig:account'
22
+
23
+ /** Domain prefix for the native multisig config ID derivation. */
24
+ const configDomain = 'tempo:multisig:config'
25
+
26
+ /** Domain prefix for native multisig owner approvals. */
27
+ const signatureDomain = 'tempo:multisig:signature'
28
+
29
+ /**
30
+ * Native multisig configuration. Determines the permanent config ID and the
31
+ * stable multisig account address.
32
+ */
33
+ export type Config<numberType = number> = Compute<{
34
+ /**
35
+ * Caller-chosen 32-byte salt mixed into the permanent config ID. Defaults to
36
+ * the zero salt (`MultisigConfig.zeroSalt`) when omitted.
37
+ */
38
+ salt?: Hex.Hex | undefined
39
+ /** Minimum total owner weight required to authorize a transaction. */
40
+ threshold: numberType
41
+ /** Weighted owner list (strictly ascending by `owner` address). */
42
+ owners: readonly Owner<numberType>[]
43
+ }>
44
+
45
+ /** Native multisig owner entry. */
46
+ export type Owner<numberType = number> = {
47
+ /** Owner address (recovered from the owner's primitive signature). */
48
+ owner: Address.Address
49
+ /** Nonzero owner weight. */
50
+ weight: numberType
51
+ }
52
+
53
+ /** RLP tuple representation of a {@link ox#MultisigConfig.Config}. */
54
+ export type Tuple = readonly [
55
+ salt: Hex.Hex,
56
+ threshold: Hex.Hex,
57
+ owners: readonly Hex.Hex[][],
58
+ ]
59
+
60
+ /**
61
+ * Asserts that a native multisig {@link ox#MultisigConfig.Config} is valid.
62
+ *
63
+ * Mirrors the Tempo `validate_multisig_config` rules: owners non-empty and
64
+ * `<= maxOwners`, strictly ascending unique nonzero owner addresses, nonzero
65
+ * owner weights, `threshold >= 1`, total weight `<= u32::MAX`, and
66
+ * `threshold <= total weight`.
67
+ *
68
+ * @example
69
+ * ```ts twoslash
70
+ * import { MultisigConfig } from 'ox/tempo'
71
+ *
72
+ * MultisigConfig.assert({
73
+ * threshold: 1,
74
+ * owners: [
75
+ * { owner: '0x1111111111111111111111111111111111111111', weight: 1 },
76
+ * ],
77
+ * })
78
+ * ```
79
+ *
80
+ * @param config - The multisig config.
81
+ */
82
+ export function assert<numberType = number>(config: Config<numberType>): void {
83
+ const { salt, threshold, owners } = config
84
+
85
+ if (typeof salt !== 'undefined' && Hex.size(salt) !== 32)
86
+ throw new InvalidConfigError({ reason: 'salt must be 32 bytes' })
87
+ if (owners.length === 0)
88
+ throw new InvalidConfigError({ reason: 'owners cannot be empty' })
89
+ if (owners.length > maxOwners)
90
+ throw new InvalidConfigError({ reason: 'too many owners' })
91
+ if (Number(threshold) < 1)
92
+ throw new InvalidConfigError({ reason: 'threshold cannot be zero' })
93
+
94
+ let totalWeight = 0
95
+ let previous: bigint | undefined
96
+ for (const owner of owners) {
97
+ if (!Address.validate(owner.owner) || Hex.toBigInt(owner.owner) === 0n)
98
+ throw new InvalidConfigError({ reason: 'owner cannot be zero' })
99
+ if (Number(owner.weight) < 1)
100
+ throw new InvalidConfigError({ reason: 'owner weight cannot be zero' })
101
+
102
+ const current = Hex.toBigInt(owner.owner)
103
+ if (typeof previous !== 'undefined' && previous >= current)
104
+ throw new InvalidConfigError({
105
+ reason: 'owners must be strictly ascending',
106
+ })
107
+ previous = current
108
+
109
+ totalWeight += Number(owner.weight)
110
+ }
111
+
112
+ if (totalWeight > 0xffffffff)
113
+ throw new InvalidConfigError({
114
+ reason: 'total owner weight exceeds u32 max',
115
+ })
116
+ if (Number(threshold) > totalWeight)
117
+ throw new InvalidConfigError({
118
+ reason: 'threshold exceeds total owner weight',
119
+ })
120
+ }
121
+
122
+ export declare namespace assert {
123
+ type ErrorType = InvalidConfigError | Errors.GlobalErrorType
124
+ }
125
+
126
+ /**
127
+ * Normalizes a native multisig {@link ox#MultisigConfig.Config}.
128
+ *
129
+ * Sorts owners into strictly ascending `owner` address order (the canonical
130
+ * form required for config ID derivation) and asserts the config is valid.
131
+ *
132
+ * @example
133
+ * ```ts twoslash
134
+ * import { MultisigConfig } from 'ox/tempo'
135
+ *
136
+ * const config = MultisigConfig.from({
137
+ * threshold: 2,
138
+ * owners: [
139
+ * { owner: '0x2222222222222222222222222222222222222222', weight: 1 },
140
+ * { owner: '0x1111111111111111111111111111111111111111', weight: 1 },
141
+ * ],
142
+ * })
143
+ * // owners are now sorted ascending by address
144
+ * ```
145
+ *
146
+ * @param config - The multisig config.
147
+ * @returns The normalized multisig config.
148
+ */
149
+ export function from<numberType = number>(
150
+ config: Config<numberType>,
151
+ ): Config<numberType> {
152
+ const owners = [...config.owners].sort((a, b) =>
153
+ Hex.toBigInt(a.owner) < Hex.toBigInt(b.owner) ? -1 : 1,
154
+ )
155
+ const normalized = {
156
+ salt: config.salt ? Hex.padLeft(config.salt, 32) : zeroSalt,
157
+ threshold: config.threshold,
158
+ owners,
159
+ } as Config<numberType>
160
+ assert(normalized)
161
+ return normalized
162
+ }
163
+
164
+ /**
165
+ * Converts an RLP {@link ox#MultisigConfig.Tuple} back to a
166
+ * {@link ox#MultisigConfig.Config}.
167
+ *
168
+ * @example
169
+ * ```ts twoslash
170
+ * import { MultisigConfig } from 'ox/tempo'
171
+ *
172
+ * const config = MultisigConfig.fromTuple([
173
+ * `0x${'00'.repeat(32)}`,
174
+ * '0x01',
175
+ * [['0x1111111111111111111111111111111111111111', '0x01']],
176
+ * ])
177
+ * ```
178
+ *
179
+ * @param tuple - The RLP tuple.
180
+ * @returns The multisig config.
181
+ */
182
+ export function fromTuple(tuple: Tuple): Config {
183
+ const [salt, threshold, owners] = tuple
184
+ return {
185
+ salt: salt && salt !== '0x' ? Hex.padLeft(salt, 32) : zeroSalt,
186
+ threshold: threshold === '0x' ? 0 : Hex.toNumber(threshold),
187
+ owners: owners.map((owner) => {
188
+ const [ownerAddress, weight] = owner as readonly Hex.Hex[]
189
+ return {
190
+ owner: ownerAddress as Address.Address,
191
+ weight: !weight || weight === '0x' ? 0 : Hex.toNumber(weight),
192
+ }
193
+ }),
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Derives the stable native multisig account address.
199
+ *
200
+ * `keccak256("tempo:multisig:account" || config_id)[12:32]`.
201
+ *
202
+ * @example
203
+ * ```ts twoslash
204
+ * import { MultisigConfig } from 'ox/tempo'
205
+ *
206
+ * const genesisConfig = MultisigConfig.from({
207
+ * threshold: 1,
208
+ * owners: [
209
+ * { owner: '0x1111111111111111111111111111111111111111', weight: 1 },
210
+ * ],
211
+ * })
212
+ *
213
+ * const address = MultisigConfig.getAddress(genesisConfig)
214
+ * ```
215
+ *
216
+ * @example
217
+ * ### From an genesis config ID
218
+ *
219
+ * If you already have the permanent `genesisConfigId`, pass it directly:
220
+ *
221
+ * ```ts twoslash
222
+ * import { MultisigConfig } from 'ox/tempo'
223
+ *
224
+ * const genesisConfigId =
225
+ * `0x${'00'.repeat(32)}` as const
226
+ *
227
+ * const address = MultisigConfig.getAddress({ genesisConfigId })
228
+ * ```
229
+ *
230
+ * @param value - The genesis config (positional) or `{ genesisConfigId }`.
231
+ * @returns The multisig account address.
232
+ */
233
+ export function getAddress(value: getAddress.Value): Address.Address {
234
+ const id =
235
+ typeof value === 'object' && 'genesisConfigId' in value
236
+ ? value.genesisConfigId
237
+ : toId(value)
238
+ const hash = Hash.keccak256(Hex.concat(Hex.fromString(accountDomain), id))
239
+ return Address.from(Hex.slice(hash, 12, 32))
240
+ }
241
+
242
+ export declare namespace getAddress {
243
+ type Value =
244
+ | Config
245
+ | {
246
+ /**
247
+ * The permanent genesis config ID (`MultisigConfig.toId(genesisConfig)`).
248
+ * Config updates never change this value, so it identifies the
249
+ * account permanently.
250
+ */
251
+ genesisConfigId: Hex.Hex
252
+ }
253
+
254
+ type ErrorType =
255
+ | toId.ErrorType
256
+ | Address.from.ErrorType
257
+ | Hash.keccak256.ErrorType
258
+ | Hex.concat.ErrorType
259
+ | Hex.slice.ErrorType
260
+ | Errors.GlobalErrorType
261
+ }
262
+
263
+ /**
264
+ * Computes the digest a native multisig owner approves (signs).
265
+ *
266
+ * `keccak256("tempo:multisig:signature" || inner_digest || account || config_id)`,
267
+ * where `inner_digest` is the transaction sign payload
268
+ * ({@link ox#TxEnvelopeTempo.(getSignPayload:function)}).
269
+ *
270
+ * The digest is always keyed on the permanent `account`/`genesisConfigId`
271
+ * derived from the genesis (bootstrap) config — config updates never change
272
+ * these values, so the genesis config is the correct input even for
273
+ * post-update transactions.
274
+ *
275
+ * @example
276
+ * ```ts twoslash
277
+ * import { MultisigConfig, TxEnvelopeTempo } from 'ox/tempo'
278
+ *
279
+ * const genesisConfig = MultisigConfig.from({
280
+ * threshold: 1,
281
+ * owners: [
282
+ * { owner: '0x1111111111111111111111111111111111111111', weight: 1 },
283
+ * ],
284
+ * })
285
+ *
286
+ * const envelope = TxEnvelopeTempo.from({
287
+ * chainId: 1,
288
+ * calls: [],
289
+ * })
290
+ *
291
+ * const digest = MultisigConfig.getSignPayload({
292
+ * payload: TxEnvelopeTempo.getSignPayload(envelope),
293
+ * genesisConfig,
294
+ * })
295
+ * ```
296
+ *
297
+ * @example
298
+ * ### From `account` + `genesisConfigId`
299
+ *
300
+ * If you already have the permanent `account` and `genesisConfigId` (for
301
+ * example, recovered from a stored envelope), pass them directly:
302
+ *
303
+ * ```ts twoslash
304
+ * import { MultisigConfig, TxEnvelopeTempo } from 'ox/tempo'
305
+ *
306
+ * const genesisConfig = MultisigConfig.from({
307
+ * threshold: 1,
308
+ * owners: [
309
+ * { owner: '0x1111111111111111111111111111111111111111', weight: 1 },
310
+ * ],
311
+ * })
312
+ * const genesisConfigId = MultisigConfig.toId(genesisConfig)
313
+ * const account = MultisigConfig.getAddress(genesisConfig)
314
+ *
315
+ * const envelope = TxEnvelopeTempo.from({ chainId: 1, calls: [] })
316
+ *
317
+ * const digest = MultisigConfig.getSignPayload({
318
+ * payload: TxEnvelopeTempo.getSignPayload(envelope),
319
+ * account,
320
+ * genesisConfigId,
321
+ * })
322
+ * ```
323
+ *
324
+ * @param value - The digest derivation parameters.
325
+ * @returns The owner approval digest.
326
+ */
327
+ export function getSignPayload(value: getSignPayload.Value): Hex.Hex {
328
+ const { payload } = value
329
+ const account =
330
+ 'account' in value && value.account
331
+ ? value.account
332
+ : getAddress((value as { genesisConfig: Config }).genesisConfig)
333
+ const genesisConfigId =
334
+ 'genesisConfigId' in value && value.genesisConfigId
335
+ ? value.genesisConfigId
336
+ : toId((value as { genesisConfig: Config }).genesisConfig)
337
+ return Hash.keccak256(
338
+ Hex.concat(
339
+ Hex.fromString(signatureDomain),
340
+ Hex.from(payload),
341
+ account,
342
+ genesisConfigId,
343
+ ),
344
+ )
345
+ }
346
+
347
+ export declare namespace getSignPayload {
348
+ type Value = {
349
+ /** The inner transaction sign payload (`tx.signature_hash()`). */
350
+ payload: Hex.Hex | Bytes.Bytes
351
+ } & OneOf<
352
+ | {
353
+ /** The native multisig account address. */
354
+ account: Address.Address
355
+ /** The permanent config ID. */
356
+ genesisConfigId: Hex.Hex
357
+ }
358
+ | {
359
+ /**
360
+ * The initial multisig config (the bootstrap config that derived the
361
+ * permanent `account` and `genesisConfigId`). Used to derive both values
362
+ * automatically. Config updates never change `account`/`genesisConfigId`,
363
+ * so the genesis config is also the correct input for post-update
364
+ * transactions.
365
+ */
366
+ genesisConfig: Config
367
+ }
368
+ >
369
+
370
+ type ErrorType =
371
+ | getAddress.ErrorType
372
+ | toId.ErrorType
373
+ | Hash.keccak256.ErrorType
374
+ | Hex.concat.ErrorType
375
+ | Hex.from.ErrorType
376
+ | Errors.GlobalErrorType
377
+ }
378
+
379
+ /**
380
+ * Derives the permanent config ID for a native multisig
381
+ * {@link ox#MultisigConfig.Config}.
382
+ *
383
+ * Preimage (fixed-width big-endian, **not** RLP):
384
+ * `keccak256("tempo:multisig:config" || salt || be_u32(threshold) || be_u32(owners.length) || (owner || be_u32(weight)) for each owner)`.
385
+ *
386
+ * @example
387
+ * ```ts twoslash
388
+ * import { MultisigConfig } from 'ox/tempo'
389
+ *
390
+ * const config = MultisigConfig.from({
391
+ * threshold: 1,
392
+ * owners: [
393
+ * { owner: '0x1111111111111111111111111111111111111111', weight: 1 },
394
+ * ],
395
+ * })
396
+ *
397
+ * const genesisConfigId = MultisigConfig.toId(config)
398
+ * ```
399
+ *
400
+ * @param config - The multisig config.
401
+ * @returns The 32-byte config ID.
402
+ */
403
+ export function toId(config: Config): Hex.Hex {
404
+ assert(config)
405
+ const id = Hash.keccak256(
406
+ Hex.concat(
407
+ Hex.fromString(configDomain),
408
+ Hex.padLeft(config.salt ?? zeroSalt, 32),
409
+ Hex.fromNumber(config.threshold, { size: 4 }),
410
+ Hex.fromNumber(config.owners.length, { size: 4 }),
411
+ ...config.owners.flatMap((owner) => [
412
+ owner.owner,
413
+ Hex.fromNumber(owner.weight, { size: 4 }),
414
+ ]),
415
+ ),
416
+ )
417
+ if (Hex.toBigInt(id) === 0n)
418
+ throw new InvalidConfigError({ reason: 'config ID cannot be zero' })
419
+ return id
420
+ }
421
+
422
+ export declare namespace toId {
423
+ type ErrorType =
424
+ | assert.ErrorType
425
+ | Hash.keccak256.ErrorType
426
+ | Hex.concat.ErrorType
427
+ | Hex.fromNumber.ErrorType
428
+ | Hex.fromString.ErrorType
429
+ | Errors.GlobalErrorType
430
+ }
431
+
432
+ /**
433
+ * Converts a {@link ox#MultisigConfig.Config} to its RLP tuple form (carried
434
+ * by the multisig signature `init`).
435
+ *
436
+ * Tuple shape: `[salt, threshold, [[owner, weight], ...]]`. The
437
+ * 32-byte `salt` encodes as a full fixed-width string; other integers use
438
+ * canonical RLP encoding (zero values encode as `0x`).
439
+ *
440
+ * @example
441
+ * ```ts twoslash
442
+ * import { MultisigConfig } from 'ox/tempo'
443
+ *
444
+ * const tuple = MultisigConfig.toTuple({
445
+ * threshold: 1,
446
+ * owners: [
447
+ * { owner: '0x1111111111111111111111111111111111111111', weight: 1 },
448
+ * ],
449
+ * })
450
+ * ```
451
+ *
452
+ * @param config - The multisig config.
453
+ * @returns The RLP tuple.
454
+ */
455
+ export function toTuple(config: Config): Tuple {
456
+ assert(config)
457
+ const owners = config.owners.map(
458
+ (owner) => [owner.owner, Hex.fromNumber(owner.weight)] as Hex.Hex[],
459
+ )
460
+ // `salt` is a fixed 32-byte value: it RLP-encodes as a full 32-byte string
461
+ // (including the zero salt), never trimmed like an integer.
462
+ const salt = config.salt ? Hex.padLeft(config.salt, 32) : zeroSalt
463
+ return [salt, Hex.fromNumber(config.threshold), owners] as const
464
+ }
465
+
466
+ /**
467
+ * Validates a native multisig {@link ox#MultisigConfig.Config}. Returns `true`
468
+ * if valid, `false` otherwise.
469
+ *
470
+ * @example
471
+ * ```ts twoslash
472
+ * import { MultisigConfig } from 'ox/tempo'
473
+ *
474
+ * const valid = MultisigConfig.validate({
475
+ * threshold: 1,
476
+ * owners: [
477
+ * { owner: '0x1111111111111111111111111111111111111111', weight: 1 },
478
+ * ],
479
+ * })
480
+ * // @log: true
481
+ * ```
482
+ *
483
+ * @param config - The multisig config.
484
+ * @returns Whether the config is valid.
485
+ */
486
+ export function validate(config: Config): boolean {
487
+ try {
488
+ assert(config)
489
+ return true
490
+ } catch {
491
+ return false
492
+ }
493
+ }
494
+
495
+ /** Thrown when a native multisig config is invalid. */
496
+ export class InvalidConfigError extends Errors.BaseError {
497
+ override readonly name = 'MultisigConfig.InvalidConfigError'
498
+ constructor({ reason }: { reason: string }) {
499
+ super(`Invalid native multisig config: ${reason}.`)
500
+ }
501
+ }