accounts 0.18.5 → 0.19.0

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 (46) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/core/AccessKey.d.ts +5 -1
  3. package/dist/core/AccessKey.d.ts.map +1 -1
  4. package/dist/core/AccessKey.js +2 -0
  5. package/dist/core/AccessKey.js.map +1 -1
  6. package/dist/core/ExecutionError.d.ts.map +1 -1
  7. package/dist/core/ExecutionError.js +38 -3
  8. package/dist/core/ExecutionError.js.map +1 -1
  9. package/dist/core/Schema.d.ts +15 -0
  10. package/dist/core/Schema.d.ts.map +1 -1
  11. package/dist/core/zod/rpc.d.ts +1 -0
  12. package/dist/core/zod/rpc.d.ts.map +1 -1
  13. package/dist/core/zod/rpc.js +1 -1
  14. package/dist/core/zod/rpc.js.map +1 -1
  15. package/dist/server/CliAuth.d.ts.map +1 -1
  16. package/dist/server/CliAuth.js +6 -4
  17. package/dist/server/CliAuth.js.map +1 -1
  18. package/dist/server/internal/handlers/relay.d.ts +0 -7
  19. package/dist/server/internal/handlers/relay.d.ts.map +1 -1
  20. package/dist/server/internal/handlers/relay.js +0 -46
  21. package/dist/server/internal/handlers/relay.js.map +1 -1
  22. package/dist/server/internal/handlers/sponsorship.d.ts +0 -2
  23. package/dist/server/internal/handlers/sponsorship.d.ts.map +1 -1
  24. package/dist/server/internal/handlers/sponsorship.js +1 -2
  25. package/dist/server/internal/handlers/sponsorship.js.map +1 -1
  26. package/package.json +6 -6
  27. package/src/cli/Provider.localnet.test.ts +3 -3
  28. package/src/core/AccessKey.permissions.test.ts +73 -0
  29. package/src/core/AccessKey.test.ts +29 -27
  30. package/src/core/AccessKey.ts +7 -1
  31. package/src/core/ExecutionError.ts +39 -3
  32. package/src/core/Provider.localnet.test.ts +2 -1
  33. package/src/core/adapters/deviceCode/deviceCode.localnet.test.ts +4 -1
  34. package/src/core/adapters/privy.test.ts +1 -1
  35. package/src/core/zod/rpc.ts +2 -1
  36. package/src/server/CliAuth.test.ts +5 -3
  37. package/src/server/CliAuth.ts +6 -4
  38. package/src/server/internal/handlers/relay.ts +0 -56
  39. package/src/server/internal/handlers/sponsorship.ts +1 -4
  40. package/dist/server/internal/handlers/multisig.d.ts +0 -214
  41. package/dist/server/internal/handlers/multisig.d.ts.map +0 -1
  42. package/dist/server/internal/handlers/multisig.js +0 -505
  43. package/dist/server/internal/handlers/multisig.js.map +0 -1
  44. package/src/server/internal/handlers/multisig.localnet.test.ts +0 -94
  45. package/src/server/internal/handlers/multisig.test.ts +0 -743
  46. package/src/server/internal/handlers/multisig.ts +0 -774
@@ -1,774 +0,0 @@
1
- import { Hex, RpcResponse, Signature } from 'ox'
2
- import { MultisigConfig, SignatureEnvelope, TxEnvelopeTempo } from 'ox/tempo'
3
- import type { Address, Client } from 'viem'
4
- import type { LocalAccount } from 'viem/accounts'
5
- import { Transaction } from 'viem/tempo'
6
-
7
- import * as Sponsorship from './sponsorship.js'
8
- import * as Utils from './utils.js'
9
-
10
- /** Default submission-claim TTL in milliseconds. */
11
- export const defaultClaimTtl = 30_000
12
-
13
- /** Returns whether a raw transaction carries a native multisig signature. */
14
- export function isMultisigTransaction(serialized: Hex.Hex) {
15
- if (!Utils.isSerializedTempoTransaction(serialized)) return false
16
- try {
17
- const transaction = Transaction.deserialize(serialized as never)
18
- return isMultisigSignature((transaction as { signature?: unknown }).signature)
19
- } catch {
20
- return false
21
- }
22
- }
23
-
24
- /** Handles a native multisig raw transaction submission. */
25
- export async function handleRawTransaction(
26
- options: handleRawTransaction.Options,
27
- ): Promise<handleRawTransaction.ReturnType> {
28
- const result = await collect(options)
29
- if (result.status.status === 'pending' || result.status.status === 'submitting')
30
- return result.status.operation.id
31
- if (result.status.status === 'submitted')
32
- return result.status.operation.submittedHash ?? result.status.operation.id
33
- if (options.method === 'eth_sendRawTransactionSync') return result.broadcastResult
34
- return result.status.operation.submittedHash!
35
- }
36
-
37
- export declare namespace handleRawTransaction {
38
- /** Options for handling a raw multisig transaction submission. */
39
- type Options = collect.Options
40
-
41
- /** Raw transaction handler return value. */
42
- type ReturnType = Hex.Hex | unknown
43
- }
44
-
45
- async function collect(options: collect.Options): Promise<collect.ReturnType> {
46
- const {
47
- claimTtl = defaultClaimTtl,
48
- finalize = 'sync',
49
- getClient,
50
- method,
51
- request,
52
- resolveConfig,
53
- sponsor,
54
- store,
55
- } = options
56
- const serialized = request.params?.[0]
57
- if (!Utils.isSerializedTempoTransaction(serialized))
58
- throw new RpcResponse.InvalidParamsError({
59
- message: 'Only Tempo (0x76/0x78) transactions are supported.',
60
- })
61
-
62
- const input = parse(serialized)
63
- const pending = await store.get(input.id)
64
- const config = await resolveValidatedConfig({
65
- account: input.account,
66
- chainId: input.chainId,
67
- init: input.init,
68
- pending,
69
- resolveConfig,
70
- })
71
- if (!config)
72
- throw new RpcResponse.InvalidParamsError({
73
- message:
74
- 'Multisig config is required to collect approvals. Provide it in the bootstrap transaction or configure `multisig.resolveConfig`.',
75
- })
76
- const initConfig = resolveInitConfig({
77
- config,
78
- init: input.init,
79
- nonce: input.nonce,
80
- pending,
81
- })
82
-
83
- const now = Date.now()
84
- let operation: Operation = {
85
- account: input.account,
86
- chainId: input.chainId,
87
- claimExpiresAt: pending?.claimExpiresAt,
88
- config,
89
- createdAt: pending?.createdAt ?? now,
90
- id: input.id,
91
- init: pending?.init || !!initConfig,
92
- initConfig,
93
- payload: input.payload,
94
- signatures: mergeSignatures([...(pending?.signatures ?? []), ...input.signatures]),
95
- status: pending?.status === 'submitted' ? 'submitted' : 'pending',
96
- submittedHash: pending?.submittedHash,
97
- transaction: serialized as Hex.Hex,
98
- updatedAt: now,
99
- }
100
-
101
- let approvals = getApprovals({
102
- account: input.account,
103
- config,
104
- payload: input.payload,
105
- signatures: operation.signatures,
106
- })
107
- if (operation.status === 'submitted')
108
- return {
109
- broadcastResult: operation.submittedHash,
110
- status: { operation, status: 'submitted' },
111
- }
112
-
113
- if (approvals.weight < approvals.threshold) {
114
- operation = await store.savePending(operation)
115
- approvals = getApprovals({
116
- account: operation.account,
117
- config,
118
- payload: operation.payload,
119
- signatures: operation.signatures,
120
- })
121
- if (approvals.weight < approvals.threshold)
122
- return { status: { operation, status: operation.status } }
123
- }
124
-
125
- const claim = await store.claimSubmission(operation, { ttl: claimTtl })
126
- if (claim.status !== 'claimed') return { status: claim }
127
-
128
- operation = claim.operation
129
- approvals = getApprovals({
130
- account: operation.account,
131
- config,
132
- payload: operation.payload,
133
- signatures: operation.signatures,
134
- })
135
- const client = getClient(operation.chainId)
136
- const final = await serializeFinal({
137
- account: operation.account,
138
- init: operation.initConfig ?? initConfig,
139
- signatures: approvals.signatures,
140
- transaction: input.transaction,
141
- })
142
- const broadcastMethod =
143
- method === 'eth_sendRawTransaction' && finalize === 'sync'
144
- ? 'eth_sendRawTransactionSync'
145
- : method
146
- const feePayerState = (() => {
147
- try {
148
- const transaction = Transaction.deserialize(final as never) as Record<string, unknown>
149
- // No fee-payer field means finalized transaction does not request sponsorship.
150
- if (!('feePayerSignature' in transaction)) return {}
151
- // Preserve fee-token/signature marker for sponsorship decision below.
152
- return {
153
- feeToken:
154
- typeof transaction.feeToken === 'string' ? (transaction.feeToken as Address) : undefined,
155
- signature: transaction.feePayerSignature,
156
- }
157
- } catch {
158
- // Decode failure falls back to direct broadcast.
159
- return {}
160
- }
161
- })()
162
- const sponsorFeeToken = await (async () => {
163
- // No sponsor configured, so finalized multisig transaction broadcasts as-is.
164
- if (!sponsor) return undefined
165
- // Already fee-payer signed transactions must not be rewritten by this relay.
166
- if (feePayerState.signature !== null) return undefined
167
- // Explicit relay fee token wins when the transaction requests sponsorship.
168
- if (sponsor.feeToken) return sponsor.feeToken
169
- // `null` requests relay-added fee-payer signature.
170
- return await sponsor.resolveFeeToken?.(operation.chainId)
171
- })()
172
- const shouldSponsor = (() => {
173
- // No sponsor configured, so no sponsorship path to take.
174
- if (!sponsor) return false
175
- // `null` requests relay-added fee-payer signature.
176
- if (feePayerState.signature === null) return true
177
- // Missing or already-present fee-payer signatures broadcast unchanged.
178
- return false
179
- })()
180
- const result = await (async () => {
181
- // Sponsorship enabled, so sponsor adds/signs fee-payer fields.
182
- if (shouldSponsor && sponsor)
183
- return await Sponsorship.handleRawTransaction({
184
- account: sponsor.account,
185
- feeToken: sponsorFeeToken,
186
- getFeeToken: sponsor.resolveFeeToken
187
- ? async (chainId) => await sponsor.resolveFeeToken?.(chainId)
188
- : undefined,
189
- getClient,
190
- method: broadcastMethod,
191
- request: { params: [final] },
192
- sender: operation.account,
193
- validate: sponsor.validate,
194
- })
195
- // Otherwise, multisig transaction is final and can broadcast directly.
196
- return await client.request({
197
- method: broadcastMethod,
198
- params: [final],
199
- } as never)
200
- })()
201
- const submittedHash = (() => {
202
- if (typeof result === 'string') return result as Hex.Hex
203
- if (result && typeof result === 'object' && 'transactionHash' in result) {
204
- const response = result as { transactionHash?: unknown }
205
- if (typeof response.transactionHash === 'string') return response.transactionHash as Hex.Hex
206
- }
207
- throw new Error('Expected transaction hash in multisig broadcast result.')
208
- })()
209
- const submitted = await store.setSubmitted(operation.id, submittedHash)
210
-
211
- return {
212
- broadcastResult: result,
213
- status: { operation: submitted, status: 'claimed' },
214
- }
215
- }
216
-
217
- /** Resolves a multisig operation id for standard transaction lookup methods. */
218
- export async function handleGetTransaction(
219
- options: handleGetTransaction.Options,
220
- ): Promise<handleGetTransaction.ReturnType> {
221
- const id = options.request.params?.[0]
222
- if (typeof id !== 'string') return undefined
223
-
224
- const operation = await options.store.get(id as Hex.Hex)
225
- if (!operation) return undefined
226
- if (operation.status !== 'submitted' || !operation.submittedHash) return { result: null }
227
-
228
- const result = await options.getClient(operation.chainId).request({
229
- method: options.method,
230
- params: [operation.submittedHash],
231
- } as never)
232
- return { result }
233
- }
234
-
235
- export declare namespace handleGetTransaction {
236
- /** Options for resolving a multisig operation id through transaction lookup methods. */
237
- type Options = {
238
- /** Client resolver keyed by transaction `chainId`. */
239
- getClient: (chainId?: number | undefined) => Client
240
- /** Standard transaction lookup method to handle. */
241
- method: 'eth_getTransactionByHash' | 'eth_getTransactionReceipt'
242
- /** Incoming JSON-RPC request. */
243
- request: { params?: readonly unknown[] | undefined }
244
- /** Pending multisig operation store. */
245
- store: Store
246
- }
247
-
248
- /** Transaction lookup result wrapper. */
249
- type ReturnType = { result: unknown } | undefined
250
- }
251
-
252
- declare namespace collect {
253
- type Options = {
254
- /** Submission claim TTL in milliseconds. @default 30000 */
255
- claimTtl?: number | undefined
256
- /** How to broadcast once quorum is met. @default 'sync' */
257
- finalize?: 'submitted' | 'sync' | undefined
258
- /** Client resolver keyed by transaction `chainId`. */
259
- getClient: (chainId?: number | undefined) => Client
260
- /** Raw transaction method to handle. */
261
- method: 'eth_sendRawTransaction' | 'eth_sendRawTransactionSync'
262
- /** Incoming JSON-RPC request. */
263
- request: { params?: readonly unknown[] | undefined }
264
- /** Resolves the genesis multisig config for quorum checks. */
265
- resolveConfig?: ResolveConfig | undefined
266
- /** Optional fee payer used to sponsor finalized multisig transactions. */
267
- sponsor?: Sponsor | undefined
268
- /** Pending multisig operation store. */
269
- store: Store
270
- }
271
-
272
- type ReturnType = {
273
- /** Raw broadcast result once quorum is met and this caller claimed submission. */
274
- broadcastResult?: unknown
275
- /** Structured operation claim status. */
276
- status: ClaimSubmissionResult | { operation: Operation; status: 'claimed' }
277
- }
278
- }
279
-
280
- /** Returns a stored native multisig operation status. */
281
- export async function getStatus(options: getStatus.Options): Promise<Status | null> {
282
- const operation = await options.store.get(options.id)
283
- if (!operation) return null
284
- const config = await resolveValidatedConfig({
285
- account: operation.account,
286
- chainId: operation.chainId,
287
- pending: operation,
288
- resolveConfig: options.resolveConfig,
289
- })
290
- if (!config)
291
- return {
292
- account: operation.account,
293
- chainId: operation.chainId,
294
- id: operation.id,
295
- signatures: operation.signatures.length,
296
- status: operation.status,
297
- submittedHash: operation.submittedHash,
298
- }
299
- const approvals = getApprovals({
300
- account: operation.account,
301
- config,
302
- payload: operation.payload,
303
- signatures: operation.signatures,
304
- })
305
- return toStatus({ approvals, operation })
306
- }
307
-
308
- export declare namespace getStatus {
309
- /** Options for reading one multisig operation status. */
310
- type Options = {
311
- /** Operation id returned by a pending multisig submission. */
312
- id: Hex.Hex
313
- /** Resolves the genesis multisig config for quorum status. */
314
- resolveConfig?: ResolveConfig | undefined
315
- /** Pending multisig operation store. */
316
- store: Store
317
- }
318
- }
319
-
320
- /** Returns pending native multisig operation statuses for an account. */
321
- export async function listStatuses(options: listStatuses.Options): Promise<readonly Status[]> {
322
- const operations = await options.store.listPendingByAddress(options.account)
323
- return await Promise.all(
324
- operations.map(async (operation) => {
325
- const config = await resolveValidatedConfig({
326
- account: operation.account,
327
- chainId: operation.chainId,
328
- pending: operation,
329
- resolveConfig: options.resolveConfig,
330
- })
331
- if (!config)
332
- return {
333
- account: operation.account,
334
- chainId: operation.chainId,
335
- id: operation.id,
336
- signatures: operation.signatures.length,
337
- status: operation.status,
338
- submittedHash: operation.submittedHash,
339
- }
340
- const approvals = getApprovals({
341
- account: operation.account,
342
- config,
343
- payload: operation.payload,
344
- signatures: operation.signatures,
345
- })
346
- return toStatus({ approvals, operation })
347
- }),
348
- )
349
- }
350
-
351
- export declare namespace listStatuses {
352
- /** Options for listing multisig operation statuses. */
353
- type Options = {
354
- /** Native multisig account address. */
355
- account: Address
356
- /** Resolves the genesis multisig config for quorum status. */
357
- resolveConfig?: ResolveConfig | undefined
358
- /** Pending multisig operation store. */
359
- store: Store
360
- }
361
- }
362
-
363
- /** Creates an in-memory multisig operation store for development and tests only. */
364
- export function memoryStore(): Store {
365
- const operations = new Map<string, Operation>()
366
- return {
367
- async claimSubmission(operation, options) {
368
- const now = Date.now()
369
- const existing = operations.get(operation.id)
370
- if (existing?.status === 'submitted') return { operation: existing, status: 'submitted' }
371
- if (existing?.status === 'submitting' && (existing.claimExpiresAt ?? 0) > now)
372
- return { operation: existing, status: 'submitting' }
373
- const claimed = mergeOperation(existing, operation, {
374
- claimExpiresAt: now + options.ttl,
375
- status: 'submitting',
376
- updatedAt: now,
377
- })
378
- operations.set(operation.id, claimed)
379
- return { operation: claimed, status: 'claimed' }
380
- },
381
- async get(id) {
382
- return operations.get(id)
383
- },
384
- async listPendingByAddress(address) {
385
- return [...operations.values()].filter(
386
- (operation) =>
387
- operation.account.toLowerCase() === address.toLowerCase() &&
388
- operation.status !== 'submitted',
389
- )
390
- },
391
- async savePending(operation) {
392
- const now = Date.now()
393
- const existing = operations.get(operation.id)
394
- if (existing?.status === 'submitted') return existing
395
- const pending = mergeOperation(existing, operation, {
396
- status:
397
- existing?.status === 'submitting' && (existing.claimExpiresAt ?? 0) > now
398
- ? 'submitting'
399
- : 'pending',
400
- updatedAt: now,
401
- })
402
- operations.set(operation.id, pending)
403
- return pending
404
- },
405
- async setSubmitted(id, submittedHash) {
406
- const existing = operations.get(id)
407
- if (!existing) throw new Error('Cannot mark an unknown multisig operation submitted.')
408
- const submitted = {
409
- ...existing,
410
- claimExpiresAt: undefined,
411
- status: 'submitted',
412
- submittedHash,
413
- updatedAt: Date.now(),
414
- } satisfies Operation
415
- operations.set(id, submitted)
416
- return submitted
417
- },
418
- }
419
- }
420
-
421
- /** Native multisig relay options. */
422
- export type Options = {
423
- /** Submission claim TTL in milliseconds. @default 30000 */
424
- claimTtl?: number | undefined
425
- /** How to broadcast once quorum is met. @default 'sync' */
426
- finalize?: 'submitted' | 'sync' | undefined
427
- /** Resolves the genesis multisig config for quorum checks. */
428
- resolveConfig?: ResolveConfig | undefined
429
- /** Pending multisig operation store. */
430
- store: Store
431
- }
432
-
433
- /** Resolves the genesis multisig config for quorum checks. */
434
- export type ResolveConfig = (request: {
435
- /** Native multisig account address. */
436
- account: Address
437
- /** Transaction chain id. */
438
- chainId: number
439
- /** Bootstrap config carried by the transaction, when present. */
440
- init?: MultisigConfig.Config | undefined
441
- }) => MultisigConfig.Config | Promise<MultisigConfig.Config | undefined> | undefined
442
-
443
- /** Optional fee payer used to sponsor finalized multisig transactions. */
444
- export type Sponsor = {
445
- /** Account used as the fee payer. */
446
- account: LocalAccount
447
- /** Fee token to set before fee payer signing. */
448
- feeToken?: Address | undefined
449
- /** Resolves the default fee token for raw sponsorship. */
450
- resolveFeeToken?:
451
- | ((chainId: number) => Address | Promise<Address | undefined> | undefined)
452
- | undefined
453
- /** Optional sponsorship approval callback. */
454
- validate?: Sponsorship.handleRawTransaction.Options['validate']
455
- }
456
-
457
- /** Storage for native multisig operation approvals and submission claims. */
458
- export type Store = {
459
- /** Atomically claims submission for a quorum-ready operation. Only a `claimed` result may broadcast. */
460
- claimSubmission: (
461
- operation: Operation,
462
- options: claimSubmission.Options,
463
- ) => Promise<ClaimSubmissionResult>
464
- /** Reads a stored operation. */
465
- get: (id: Hex.Hex) => Promise<Operation | undefined>
466
- /** Lists non-submitted operations for a native multisig account address. */
467
- listPendingByAddress: (address: Address) => Promise<readonly Operation[]>
468
- /** Saves a pending operation, preserving already-stored approvals. */
469
- savePending: (operation: Operation) => Promise<Operation>
470
- /** Marks a claimed operation submitted with its real transaction hash. */
471
- setSubmitted: (id: Hex.Hex, submittedHash: Hex.Hex) => Promise<Operation>
472
- }
473
-
474
- /** `Store.claimSubmission` types. */
475
- export declare namespace claimSubmission {
476
- /** Options for claiming submission. */
477
- type Options = {
478
- /** Claim TTL in milliseconds. */
479
- ttl: number
480
- }
481
- }
482
-
483
- /** Result of atomically claiming a multisig operation for submission. */
484
- export type ClaimSubmissionResult =
485
- | {
486
- /** Operation this caller may broadcast. */
487
- operation: Operation
488
- /** Claim status. */
489
- status: 'claimed'
490
- }
491
- | {
492
- /** Current stored operation. */
493
- operation: Operation
494
- /** Current non-claimed status. */
495
- status: 'pending' | 'submitting' | 'submitted'
496
- }
497
-
498
- /** Stored native multisig operation. */
499
- export type Operation = {
500
- /** Native multisig account address. */
501
- account: Address
502
- /** Transaction chain id. */
503
- chainId: number
504
- /** Submission claim expiry timestamp in milliseconds. */
505
- claimExpiresAt?: number | undefined
506
- /** Resolved genesis config used for approval checks. */
507
- config?: MultisigConfig.Config | undefined
508
- /** Creation timestamp in milliseconds. */
509
- createdAt: number
510
- /** Deterministic operation id. */
511
- id: Hex.Hex
512
- /** Whether the finalized transaction must carry the genesis init config. */
513
- init?: boolean | undefined
514
- /** Genesis init config to attach when finalizing a bootstrap transaction. */
515
- initConfig?: MultisigConfig.Config | undefined
516
- /** Unsigned Tempo transaction sign payload. */
517
- payload: Hex.Hex
518
- /** Collected owner approval signatures. */
519
- signatures: readonly Hex.Hex[]
520
- /** Operation state. */
521
- status: 'pending' | 'submitting' | 'submitted'
522
- /** Transaction hash once submitted. */
523
- submittedHash?: Hex.Hex | undefined
524
- /** Last submitted serialized transaction carrying this operation. */
525
- transaction: Hex.Hex
526
- /** Last update timestamp in milliseconds. */
527
- updatedAt: number
528
- }
529
-
530
- /** Native multisig operation status. */
531
- export type Status = {
532
- /** Native multisig account address. */
533
- account: Address
534
- /** Transaction chain id. */
535
- chainId: number
536
- /** Deterministic operation id. */
537
- id: Hex.Hex
538
- /** Number of collected owner approvals. */
539
- signatures: number
540
- /** Operation state. */
541
- status: Operation['status']
542
- /** Submitted transaction hash. */
543
- submittedHash?: Hex.Hex | undefined
544
- /** Required owner weight. */
545
- threshold?: number | undefined
546
- /** Collected owner weight. */
547
- weight?: number | undefined
548
- }
549
-
550
- function parse(serialized: Hex.Hex) {
551
- const transaction = Transaction.deserialize(serialized as never) as Record<string, unknown>
552
- const signature = transaction.signature
553
- if (!isMultisigSignature(signature))
554
- throw new RpcResponse.InvalidParamsError({
555
- message: 'Transaction does not contain a native multisig signature.',
556
- })
557
-
558
- const { signature: _, ...unsigned } = transaction
559
- const payload = TxEnvelopeTempo.getSignPayload(TxEnvelopeTempo.from(unsigned as never))
560
- const chainId = Number(transaction.chainId)
561
- const id = MultisigConfig.getSignPayload({
562
- account: signature.account,
563
- payload,
564
- })
565
- const init = signature.init ? MultisigConfig.from(signature.init) : undefined
566
- const nonce = typeof transaction.nonce === 'number' ? transaction.nonce : undefined
567
-
568
- return {
569
- account: signature.account,
570
- chainId,
571
- id,
572
- init,
573
- nonce,
574
- payload,
575
- signatures: signature.signatures.map((value) => SignatureEnvelope.serialize(value)),
576
- transaction,
577
- }
578
- }
579
-
580
- function isMultisigSignature(value: unknown): value is SignatureEnvelope.Multisig {
581
- return (
582
- typeof value === 'object' &&
583
- value !== null &&
584
- (value as { type?: unknown }).type === 'multisig' &&
585
- typeof (value as { account?: unknown }).account === 'string' &&
586
- Array.isArray((value as { signatures?: unknown }).signatures)
587
- )
588
- }
589
-
590
- async function resolveValidatedConfig(options: {
591
- account: Address
592
- chainId: number
593
- init?: MultisigConfig.Config | undefined
594
- pending?: Operation | undefined
595
- resolveConfig?: ResolveConfig | undefined
596
- }) {
597
- const { account, chainId, init, pending, resolveConfig } = options
598
- const config = (await resolveConfig?.({ account, chainId, init })) ?? pending?.config ?? init
599
- if (!config) return undefined
600
-
601
- const normalized = MultisigConfig.from(config)
602
- // The multisig account address derives from the genesis config, so a
603
- // bootstrap init config must derive the transaction's account.
604
- if (
605
- init &&
606
- MultisigConfig.getAddress(MultisigConfig.from(init)).toLowerCase() !== account.toLowerCase()
607
- )
608
- throw new RpcResponse.InvalidParamsError({
609
- message: 'Bootstrap multisig init config does not match the multisig account.',
610
- })
611
- return normalized
612
- }
613
-
614
- function resolveInitConfig(options: {
615
- config: MultisigConfig.Config
616
- init?: MultisigConfig.Config | undefined
617
- nonce?: number | undefined
618
- pending?: Operation | undefined
619
- }) {
620
- const { config, init, nonce, pending } = options
621
- if (pending?.initConfig) return pending.initConfig
622
- if (pending?.init && pending.config) return pending.config
623
- if (init) return init
624
- if (nonce === 0) return config
625
- return undefined
626
- }
627
-
628
- function mergeSignatures(signatures: readonly Hex.Hex[]) {
629
- const seen = new Set<string>()
630
- const out: Hex.Hex[] = []
631
- for (const signature of signatures) {
632
- const key = signature.toLowerCase()
633
- if (seen.has(key)) continue
634
- seen.add(key)
635
- out.push(signature)
636
- }
637
- return out
638
- }
639
-
640
- function getApprovals(options: {
641
- account: Address
642
- config: MultisigConfig.Config
643
- payload: Hex.Hex
644
- signatures: readonly Hex.Hex[]
645
- }) {
646
- const { account, config, payload } = options
647
- const digest = MultisigConfig.getSignPayload({ account, payload })
648
- const owners = new Map(
649
- config.owners.map((owner) => [
650
- owner.owner.toLowerCase(),
651
- { address: owner.owner, weight: Number(owner.weight) },
652
- ]),
653
- )
654
- const seen = new Set<string>()
655
- const signatures: Hex.Hex[] = []
656
- let weight = 0
657
-
658
- for (const value of options.signatures) {
659
- const signature = SignatureEnvelope.from(value)
660
- const owner = SignatureEnvelope.extractAddress({ payload: digest, signature })
661
- const key = owner.toLowerCase()
662
- const configured = owners.get(key)
663
- if (!configured)
664
- throw new RpcResponse.InvalidParamsError({ message: `Signature from non-owner ${owner}.` })
665
- if (seen.has(key)) continue
666
- const valid = (() => {
667
- try {
668
- return SignatureEnvelope.verify(signature, { payload: digest, address: configured.address })
669
- } catch {
670
- return false
671
- }
672
- })()
673
- if (!valid)
674
- throw new RpcResponse.InvalidParamsError({
675
- message: `Invalid signature from owner ${configured.address}.`,
676
- })
677
- seen.add(key)
678
- signatures.push(SignatureEnvelope.serialize(signature))
679
- weight += configured.weight
680
- }
681
-
682
- return { signatures, threshold: Number(config.threshold), weight }
683
- }
684
-
685
- async function serializeFinal(options: {
686
- account: Address
687
- init?: MultisigConfig.Config | undefined
688
- signatures: readonly Hex.Hex[]
689
- transaction: Record<string, unknown>
690
- }) {
691
- const { signature: _, ...transaction } = options.transaction
692
- const envelope = TxEnvelopeTempo.from({
693
- ...transaction,
694
- feePayerSignature: (() => {
695
- const value = transaction.feePayerSignature
696
- // Preserve missing/null fee-payer markers so sponsorship can add signature later.
697
- if (!value) return value
698
- // Normalize RPC-shaped signatures before rebuilding final transaction envelope.
699
- if (typeof value === 'object' && 'r' in value && 's' in value) {
700
- const signature = value as {
701
- r: bigint | number | string
702
- s: bigint | number | string
703
- v?: bigint | number | string | undefined
704
- yParity?: bigint | number | string | undefined
705
- }
706
- const yParity = (() => {
707
- const value = signature.yParity ?? signature.v
708
- // Some signature shapes omit parity until later normalization.
709
- if (typeof value === 'undefined') return undefined
710
- const number = Number(value)
711
- // RPC signatures may carry Ethereum 27/28 `v`; `ox` expects 0/1 parity.
712
- if (number === 27 || number === 28) return number - 27
713
- return number
714
- })()
715
- if (typeof yParity === 'number')
716
- return Signature.from({ r: BigInt(signature.r), s: BigInt(signature.s), yParity })
717
- }
718
- // Fall back to `ox` for already-normalized signature inputs.
719
- return Signature.from(value as never)
720
- })(),
721
- } as never)
722
- const payload = TxEnvelopeTempo.getSignPayload(envelope)
723
- const signatures = options.signatures.map((approval) => SignatureEnvelope.from(approval))
724
- const sorted = SignatureEnvelope.sortMultisigApprovals({
725
- account: options.account,
726
- payload,
727
- signatures,
728
- })
729
- const signature = SignatureEnvelope.from({
730
- account: options.account,
731
- signatures: sorted,
732
- ...(options.init ? { init: options.init } : {}),
733
- })
734
- return TxEnvelopeTempo.serialize(envelope, {
735
- ...('feePayerSignature' in transaction
736
- ? { feePayerSignature: transaction.feePayerSignature as never }
737
- : {}),
738
- signature,
739
- })
740
- }
741
-
742
- function mergeOperation(
743
- existing: Operation | undefined,
744
- operation: Operation,
745
- patch: Partial<Operation>,
746
- ) {
747
- return {
748
- ...operation,
749
- ...existing,
750
- ...patch,
751
- config: operation.config ?? existing?.config,
752
- init: existing?.init || operation.init,
753
- initConfig: existing?.initConfig ?? operation.initConfig,
754
- signatures: mergeSignatures([...(existing?.signatures ?? []), ...operation.signatures]),
755
- transaction: operation.transaction,
756
- } satisfies Operation
757
- }
758
-
759
- function toStatus(options: {
760
- approvals: { signatures: readonly Hex.Hex[]; threshold: number; weight: number }
761
- operation: Operation
762
- }): Status {
763
- const { approvals, operation } = options
764
- return {
765
- account: operation.account,
766
- chainId: operation.chainId,
767
- id: operation.id,
768
- signatures: approvals.signatures.length,
769
- status: operation.status,
770
- submittedHash: operation.submittedHash,
771
- threshold: approvals.threshold,
772
- weight: approvals.weight,
773
- }
774
- }