viem 2.56.0 → 2.56.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 (250) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/_cjs/actions/wallet/sendTransaction.js +9 -1
  3. package/_cjs/actions/wallet/sendTransaction.js.map +1 -1
  4. package/_cjs/actions/wallet/sendTransactionSync.js +9 -1
  5. package/_cjs/actions/wallet/sendTransactionSync.js.map +1 -1
  6. package/_cjs/errors/version.js +1 -1
  7. package/_cjs/tempo/Abis.js +11 -23
  8. package/_cjs/tempo/Abis.js.map +1 -1
  9. package/_cjs/tempo/Account.js +66 -61
  10. package/_cjs/tempo/Account.js.map +1 -1
  11. package/_cjs/tempo/Client.js +10 -2
  12. package/_cjs/tempo/Client.js.map +1 -1
  13. package/_cjs/tempo/Decorator.js +2 -1
  14. package/_cjs/tempo/Decorator.js.map +1 -1
  15. package/_cjs/tempo/Formatters.js +29 -9
  16. package/_cjs/tempo/Formatters.js.map +1 -1
  17. package/_cjs/tempo/Multisig.js +990 -0
  18. package/_cjs/tempo/Multisig.js.map +1 -0
  19. package/_cjs/tempo/Selectors.js +2 -3
  20. package/_cjs/tempo/Selectors.js.map +1 -1
  21. package/_cjs/tempo/{Storage.js → Store.js} +34 -9
  22. package/_cjs/tempo/Store.js.map +1 -0
  23. package/_cjs/tempo/Transaction.js +15 -30
  24. package/_cjs/tempo/Transaction.js.map +1 -1
  25. package/_cjs/tempo/Transport.js +51 -5
  26. package/_cjs/tempo/Transport.js.map +1 -1
  27. package/_cjs/tempo/actions/accessKey.js +102 -8
  28. package/_cjs/tempo/actions/accessKey.js.map +1 -1
  29. package/_cjs/tempo/actions/amm.js +6 -0
  30. package/_cjs/tempo/actions/amm.js.map +1 -1
  31. package/_cjs/tempo/actions/channel.js +12 -0
  32. package/_cjs/tempo/actions/channel.js.map +1 -1
  33. package/_cjs/tempo/actions/dex.js +10 -0
  34. package/_cjs/tempo/actions/dex.js.map +1 -1
  35. package/_cjs/tempo/actions/earn/deployment.js +13 -1
  36. package/_cjs/tempo/actions/earn/deployment.js.map +1 -1
  37. package/_cjs/tempo/actions/earn.js +17 -0
  38. package/_cjs/tempo/actions/earn.js.map +1 -1
  39. package/_cjs/tempo/actions/fee.js +4 -0
  40. package/_cjs/tempo/actions/fee.js.map +1 -1
  41. package/_cjs/tempo/actions/multisig.js +86 -28
  42. package/_cjs/tempo/actions/multisig.js.map +1 -1
  43. package/_cjs/tempo/actions/policy.js +8 -0
  44. package/_cjs/tempo/actions/policy.js.map +1 -1
  45. package/_cjs/tempo/actions/receivePolicy.js +6 -0
  46. package/_cjs/tempo/actions/receivePolicy.js.map +1 -1
  47. package/_cjs/tempo/actions/reward.js +4 -0
  48. package/_cjs/tempo/actions/reward.js.map +1 -1
  49. package/_cjs/tempo/actions/token.js +32 -0
  50. package/_cjs/tempo/actions/token.js.map +1 -1
  51. package/_cjs/tempo/actions/virtualAddress.js +2 -0
  52. package/_cjs/tempo/actions/virtualAddress.js.map +1 -1
  53. package/_cjs/tempo/actions/zone.js +7 -5
  54. package/_cjs/tempo/actions/zone.js.map +1 -1
  55. package/_cjs/tempo/chainConfig.js +180 -69
  56. package/_cjs/tempo/chainConfig.js.map +1 -1
  57. package/_cjs/tempo/index.js +5 -2
  58. package/_cjs/tempo/index.js.map +1 -1
  59. package/_cjs/tempo/internal/utils.js +2 -1
  60. package/_cjs/tempo/internal/utils.js.map +1 -1
  61. package/_cjs/tempo/multisig/Config.js +80 -0
  62. package/_cjs/tempo/multisig/Config.js.map +1 -0
  63. package/_cjs/tempo/multisig/Operation.js +163 -0
  64. package/_cjs/tempo/multisig/Operation.js.map +1 -0
  65. package/_cjs/utils/encoding/fromHex.js +1 -1
  66. package/_cjs/utils/encoding/fromHex.js.map +1 -1
  67. package/_cjs/utils/hash/isHash.js +1 -2
  68. package/_cjs/utils/hash/isHash.js.map +1 -1
  69. package/_esm/actions/wallet/sendTransaction.js +9 -1
  70. package/_esm/actions/wallet/sendTransaction.js.map +1 -1
  71. package/_esm/actions/wallet/sendTransactionSync.js +9 -1
  72. package/_esm/actions/wallet/sendTransactionSync.js.map +1 -1
  73. package/_esm/errors/version.js +1 -1
  74. package/_esm/tempo/Abis.js +11 -23
  75. package/_esm/tempo/Abis.js.map +1 -1
  76. package/_esm/tempo/Account.js +66 -61
  77. package/_esm/tempo/Account.js.map +1 -1
  78. package/_esm/tempo/Client.js +22 -3
  79. package/_esm/tempo/Client.js.map +1 -1
  80. package/_esm/tempo/Decorator.js +2 -1
  81. package/_esm/tempo/Decorator.js.map +1 -1
  82. package/_esm/tempo/Formatters.js +32 -11
  83. package/_esm/tempo/Formatters.js.map +1 -1
  84. package/_esm/tempo/Multisig.js +1020 -0
  85. package/_esm/tempo/Multisig.js.map +1 -0
  86. package/_esm/tempo/Selectors.js +2 -3
  87. package/_esm/tempo/Selectors.js.map +1 -1
  88. package/_esm/tempo/{Storage.js → Store.js} +37 -26
  89. package/_esm/tempo/Store.js.map +1 -0
  90. package/_esm/tempo/Transaction.js +16 -31
  91. package/_esm/tempo/Transaction.js.map +1 -1
  92. package/_esm/tempo/Transport.js +71 -6
  93. package/_esm/tempo/Transport.js.map +1 -1
  94. package/_esm/tempo/actions/accessKey.js +104 -20
  95. package/_esm/tempo/actions/accessKey.js.map +1 -1
  96. package/_esm/tempo/actions/amm.js +6 -0
  97. package/_esm/tempo/actions/amm.js.map +1 -1
  98. package/_esm/tempo/actions/channel.js +12 -0
  99. package/_esm/tempo/actions/channel.js.map +1 -1
  100. package/_esm/tempo/actions/dex.js +10 -0
  101. package/_esm/tempo/actions/dex.js.map +1 -1
  102. package/_esm/tempo/actions/earn/deployment.js +13 -1
  103. package/_esm/tempo/actions/earn/deployment.js.map +1 -1
  104. package/_esm/tempo/actions/earn.js +17 -0
  105. package/_esm/tempo/actions/earn.js.map +1 -1
  106. package/_esm/tempo/actions/fee.js +4 -0
  107. package/_esm/tempo/actions/fee.js.map +1 -1
  108. package/_esm/tempo/actions/multisig.js +129 -63
  109. package/_esm/tempo/actions/multisig.js.map +1 -1
  110. package/_esm/tempo/actions/policy.js +8 -0
  111. package/_esm/tempo/actions/policy.js.map +1 -1
  112. package/_esm/tempo/actions/receivePolicy.js +6 -0
  113. package/_esm/tempo/actions/receivePolicy.js.map +1 -1
  114. package/_esm/tempo/actions/reward.js +4 -0
  115. package/_esm/tempo/actions/reward.js.map +1 -1
  116. package/_esm/tempo/actions/token.js +32 -0
  117. package/_esm/tempo/actions/token.js.map +1 -1
  118. package/_esm/tempo/actions/virtualAddress.js +2 -0
  119. package/_esm/tempo/actions/virtualAddress.js.map +1 -1
  120. package/_esm/tempo/actions/zone.js +8 -6
  121. package/_esm/tempo/actions/zone.js.map +1 -1
  122. package/_esm/tempo/chainConfig.js +188 -86
  123. package/_esm/tempo/chainConfig.js.map +1 -1
  124. package/_esm/tempo/index.js +5 -3
  125. package/_esm/tempo/index.js.map +1 -1
  126. package/_esm/tempo/internal/utils.js +2 -1
  127. package/_esm/tempo/internal/utils.js.map +1 -1
  128. package/_esm/tempo/multisig/Config.js +84 -0
  129. package/_esm/tempo/multisig/Config.js.map +1 -0
  130. package/_esm/tempo/multisig/Operation.js +170 -0
  131. package/_esm/tempo/multisig/Operation.js.map +1 -0
  132. package/_esm/utils/encoding/fromHex.js +1 -1
  133. package/_esm/utils/encoding/fromHex.js.map +1 -1
  134. package/_esm/utils/hash/isHash.js +1 -2
  135. package/_esm/utils/hash/isHash.js.map +1 -1
  136. package/_types/actions/wallet/sendTransaction.d.ts.map +1 -1
  137. package/_types/actions/wallet/sendTransactionSync.d.ts.map +1 -1
  138. package/_types/chains/definitions/tempo.d.ts +72 -92
  139. package/_types/chains/definitions/tempo.d.ts.map +1 -1
  140. package/_types/chains/definitions/tempoDevnet.d.ts +72 -92
  141. package/_types/chains/definitions/tempoDevnet.d.ts.map +1 -1
  142. package/_types/chains/definitions/tempoLocalnet.d.ts +72 -92
  143. package/_types/chains/definitions/tempoLocalnet.d.ts.map +1 -1
  144. package/_types/chains/definitions/tempoModerato.d.ts +72 -92
  145. package/_types/chains/definitions/tempoModerato.d.ts.map +1 -1
  146. package/_types/errors/version.d.ts +1 -1
  147. package/_types/tempo/Abis.d.ts +54 -108
  148. package/_types/tempo/Abis.d.ts.map +1 -1
  149. package/_types/tempo/Account.d.ts +47 -20
  150. package/_types/tempo/Account.d.ts.map +1 -1
  151. package/_types/tempo/Client.d.ts +23 -1
  152. package/_types/tempo/Client.d.ts.map +1 -1
  153. package/_types/tempo/Decorator.d.ts +30 -5
  154. package/_types/tempo/Decorator.d.ts.map +1 -1
  155. package/_types/tempo/Formatters.d.ts.map +1 -1
  156. package/_types/tempo/Multisig.d.ts +32 -0
  157. package/_types/tempo/Multisig.d.ts.map +1 -0
  158. package/_types/tempo/Selectors.d.ts +2 -3
  159. package/_types/tempo/Selectors.d.ts.map +1 -1
  160. package/_types/tempo/Store.d.ts +62 -0
  161. package/_types/tempo/Store.d.ts.map +1 -0
  162. package/_types/tempo/Transaction.d.ts +12 -31
  163. package/_types/tempo/Transaction.d.ts.map +1 -1
  164. package/_types/tempo/Transport.d.ts +37 -5
  165. package/_types/tempo/Transport.d.ts.map +1 -1
  166. package/_types/tempo/Zone.d.ts +468 -598
  167. package/_types/tempo/Zone.d.ts.map +1 -1
  168. package/_types/tempo/actions/accessKey.d.ts +38 -8
  169. package/_types/tempo/actions/accessKey.d.ts.map +1 -1
  170. package/_types/tempo/actions/amm.d.ts.map +1 -1
  171. package/_types/tempo/actions/channel.d.ts.map +1 -1
  172. package/_types/tempo/actions/dex.d.ts.map +1 -1
  173. package/_types/tempo/actions/earn/deployment.d.ts +3 -3
  174. package/_types/tempo/actions/earn/deployment.d.ts.map +1 -1
  175. package/_types/tempo/actions/earn.d.ts.map +1 -1
  176. package/_types/tempo/actions/fee.d.ts.map +1 -1
  177. package/_types/tempo/actions/multisig.d.ts +139 -136
  178. package/_types/tempo/actions/multisig.d.ts.map +1 -1
  179. package/_types/tempo/actions/policy.d.ts.map +1 -1
  180. package/_types/tempo/actions/receivePolicy.d.ts.map +1 -1
  181. package/_types/tempo/actions/reward.d.ts.map +1 -1
  182. package/_types/tempo/actions/token.d.ts.map +1 -1
  183. package/_types/tempo/actions/virtualAddress.d.ts.map +1 -1
  184. package/_types/tempo/actions/zone.d.ts +4 -4
  185. package/_types/tempo/actions/zone.d.ts.map +1 -1
  186. package/_types/tempo/chainConfig.d.ts +38 -48
  187. package/_types/tempo/chainConfig.d.ts.map +1 -1
  188. package/_types/tempo/index.d.ts +8 -3
  189. package/_types/tempo/index.d.ts.map +1 -1
  190. package/_types/tempo/internal/types.d.ts +1 -1
  191. package/_types/tempo/internal/types.d.ts.map +1 -1
  192. package/_types/tempo/internal/utils.d.ts +1 -0
  193. package/_types/tempo/internal/utils.d.ts.map +1 -1
  194. package/_types/tempo/multisig/Config.d.ts +42 -0
  195. package/_types/tempo/multisig/Config.d.ts.map +1 -0
  196. package/_types/tempo/multisig/Operation.d.ts +32 -0
  197. package/_types/tempo/multisig/Operation.d.ts.map +1 -0
  198. package/_types/types/chain.d.ts +10 -0
  199. package/_types/types/chain.d.ts.map +1 -1
  200. package/_types/utils/hash/isHash.d.ts +1 -2
  201. package/_types/utils/hash/isHash.d.ts.map +1 -1
  202. package/actions/wallet/sendTransaction.ts +9 -1
  203. package/actions/wallet/sendTransactionSync.ts +9 -1
  204. package/errors/version.ts +1 -1
  205. package/package.json +2 -2
  206. package/tempo/Abis.ts +11 -23
  207. package/tempo/Account.ts +136 -105
  208. package/tempo/Client.ts +46 -3
  209. package/tempo/Decorator.ts +40 -8
  210. package/tempo/Formatters.ts +39 -21
  211. package/tempo/Multisig.ts +1349 -0
  212. package/tempo/Selectors.ts +2 -3
  213. package/tempo/Store.ts +170 -0
  214. package/tempo/Transaction.ts +39 -64
  215. package/tempo/Transport.ts +125 -10
  216. package/tempo/actions/accessKey.ts +210 -23
  217. package/tempo/actions/amm.ts +7 -0
  218. package/tempo/actions/channel.ts +12 -0
  219. package/tempo/actions/dex.ts +10 -0
  220. package/tempo/actions/earn/deployment.ts +16 -3
  221. package/tempo/actions/earn.ts +19 -0
  222. package/tempo/actions/fee.ts +4 -0
  223. package/tempo/actions/multisig.ts +192 -94
  224. package/tempo/actions/policy.ts +8 -0
  225. package/tempo/actions/receivePolicy.ts +6 -0
  226. package/tempo/actions/reward.ts +5 -0
  227. package/tempo/actions/token.ts +33 -0
  228. package/tempo/actions/virtualAddress.ts +2 -0
  229. package/tempo/actions/zone.ts +10 -8
  230. package/tempo/chainConfig.ts +259 -100
  231. package/tempo/index.ts +9 -1
  232. package/tempo/internal/types.ts +3 -2
  233. package/tempo/internal/utils.ts +2 -0
  234. package/tempo/multisig/Config.ts +131 -0
  235. package/tempo/multisig/Operation.ts +211 -0
  236. package/types/chain.ts +14 -0
  237. package/utils/encoding/fromHex.ts +1 -1
  238. package/utils/hash/isHash.ts +2 -3
  239. package/_cjs/tempo/Storage.js.map +0 -1
  240. package/_cjs/tempo/internal/multisig.js +0 -56
  241. package/_cjs/tempo/internal/multisig.js.map +0 -1
  242. package/_esm/tempo/Storage.js.map +0 -1
  243. package/_esm/tempo/internal/multisig.js +0 -56
  244. package/_esm/tempo/internal/multisig.js.map +0 -1
  245. package/_types/tempo/Storage.d.ts +0 -42
  246. package/_types/tempo/Storage.d.ts.map +0 -1
  247. package/_types/tempo/internal/multisig.d.ts +0 -13
  248. package/_types/tempo/internal/multisig.d.ts.map +0 -1
  249. package/tempo/Storage.ts +0 -115
  250. package/tempo/internal/multisig.ts +0 -72
@@ -0,0 +1,1349 @@
1
+ import type { Address } from 'abitype'
2
+ import * as Address_ from 'ox/Address'
3
+ import * as Hash from 'ox/Hash'
4
+ import * as Hex from 'ox/Hex'
5
+ import * as RpcResponse from 'ox/RpcResponse'
6
+ import {
7
+ KeyAuthorization,
8
+ MultisigConfig,
9
+ MultisigOperation,
10
+ Transaction as ox_Transaction,
11
+ SignatureEnvelope,
12
+ TxEnvelopeTempo,
13
+ } from 'ox/tempo'
14
+ import { getBlockNumber } from '../actions/public/getBlockNumber.js'
15
+ import { createClient } from '../clients/createClient.js'
16
+ import { custom } from '../clients/transports/custom.js'
17
+ import type { EIP1193RequestOptions } from '../types/eip1193.js'
18
+ import { decodeFunctionData } from '../utils/abi/decodeFunctionData.js'
19
+ import { isAddressEqual } from '../utils/address/isAddressEqual.js'
20
+ import * as Abis from './Abis.js'
21
+ import * as Addresses from './Addresses.js'
22
+ import { getConfigCommitment } from './actions/multisig.js'
23
+ import * as ConfigStore from './multisig/Config.js'
24
+ import * as OperationStore from './multisig/Operation.js'
25
+ import type * as Store from './Store.js'
26
+ import * as Transaction from './Transaction.js'
27
+
28
+ const submissionTtl = 30_000
29
+ const pollingInterval = 100
30
+
31
+ /**
32
+ * Creates an RPC request handler that coordinates native multisig approvals.
33
+ *
34
+ * @param next - Downstream RPC request handler.
35
+ * @param parameters - Handler parameters.
36
+ * @returns The multisig-aware RPC request handler.
37
+ */
38
+ export function handleRequest(
39
+ next: handleRequest.Handler,
40
+ parameters: handleRequest.Parameters,
41
+ ): handleRequest.Handler {
42
+ if (!parameters.store.compareAndSet)
43
+ throw new RpcResponse.InvalidParamsError({
44
+ message:
45
+ 'Multisig coordination requires a store with atomic `compareAndSet`.',
46
+ })
47
+ const client = createClient({
48
+ transport: custom({
49
+ request: ({ method, params }, options) =>
50
+ next({ method, params }, options),
51
+ }),
52
+ })
53
+
54
+ return async (request, requestOptions) => {
55
+ if (request.method === 'multisig_getConfig') {
56
+ const value = request.params?.[0]
57
+ const address =
58
+ value && typeof value === 'object' && 'address' in value
59
+ ? value.address
60
+ : undefined
61
+ if (
62
+ typeof address !== 'string' ||
63
+ !Address_.validate(address) ||
64
+ Hex.toBigInt(address) === 0n
65
+ )
66
+ throw new RpcResponse.InvalidParamsError({
67
+ message: 'Expected a multisig account address.',
68
+ })
69
+ const blockNumber = await getBlockNumber(client, { cacheTime: 0 })
70
+ const commitment = await getConfigCommitment(client, {
71
+ account: address,
72
+ blockNumber,
73
+ })
74
+ const config = await ConfigStore.read(parameters.store, {
75
+ address,
76
+ commitment,
77
+ })
78
+ if (!config) return null
79
+ return MultisigConfig.toRpc(config)
80
+ }
81
+
82
+ if (request.method === 'multisig_getOperation') {
83
+ const hash = request.params?.[0]
84
+ if (typeof hash !== 'string' || !Hash.validate(hash))
85
+ throw new RpcResponse.InvalidParamsError({
86
+ message: 'Expected a multisig operation hash.',
87
+ })
88
+ const operation = await OperationStore.read(parameters.store, hash)
89
+ return operation ? MultisigOperation.toRpc(operation) : null
90
+ }
91
+
92
+ if (request.method === 'multisig_approveKeyAuthorization')
93
+ return await approveKeyAuthorization({
94
+ client,
95
+ request,
96
+ store: parameters.store,
97
+ })
98
+
99
+ if (
100
+ request.method === 'eth_getTransactionByHash' ||
101
+ request.method === 'eth_getTransactionReceipt'
102
+ ) {
103
+ const hash = request.params?.[0]
104
+ if (typeof hash !== 'string' || !Hash.validate(hash))
105
+ return await next(request, requestOptions)
106
+ const operation = await OperationStore.read(parameters.store, hash)
107
+ if (!operation || operation.type !== 'transaction')
108
+ return await next(request, requestOptions)
109
+ if (request.method === 'eth_getTransactionReceipt') {
110
+ if (operation.status === 'pending') return null
111
+ const transactionHash = await getSubmittedTransactionHash(
112
+ parameters.store,
113
+ operation,
114
+ )
115
+ if (!transactionHash) return null
116
+ const receipt = await next(
117
+ {
118
+ ...request,
119
+ params: [transactionHash],
120
+ },
121
+ requestOptions,
122
+ )
123
+ if (!receipt || typeof receipt !== 'object') return receipt
124
+ const success =
125
+ operation.status === 'submitting'
126
+ ? await completeSubmission(
127
+ parameters.store,
128
+ operation,
129
+ transactionHash,
130
+ )
131
+ : operation
132
+ return {
133
+ ...receipt,
134
+ multisig: MultisigOperation.toRpc(success),
135
+ }
136
+ }
137
+ if (operation.status === 'pending')
138
+ return await toTransaction(client, operation, parameters.store)
139
+ const transactionHash = await getSubmittedTransactionHash(
140
+ parameters.store,
141
+ operation,
142
+ )
143
+ if (!transactionHash)
144
+ return await toTransaction(client, operation, parameters.store)
145
+ const transaction = await next(
146
+ {
147
+ ...request,
148
+ params: [transactionHash],
149
+ },
150
+ requestOptions,
151
+ )
152
+ if (!transaction || typeof transaction !== 'object')
153
+ return await toTransaction(client, operation, parameters.store)
154
+ const success =
155
+ operation.status === 'submitting'
156
+ ? await completeSubmission(
157
+ parameters.store,
158
+ operation,
159
+ transactionHash,
160
+ )
161
+ : operation
162
+ return {
163
+ ...transaction,
164
+ multisig: MultisigOperation.toRpc(success),
165
+ }
166
+ }
167
+
168
+ if (
169
+ request.method !== 'eth_sendRawTransaction' &&
170
+ request.method !== 'eth_sendRawTransactionSync' &&
171
+ request.method !== 'multisig_approveRawTransaction' &&
172
+ request.method !== 'multisig_approveRawTransactionSync'
173
+ )
174
+ return await next(request, requestOptions)
175
+
176
+ const standard =
177
+ request.method === 'eth_sendRawTransaction' ||
178
+ request.method === 'eth_sendRawTransactionSync'
179
+ const serialized = request.params?.[0]
180
+ if (!isSerializedTempoTransaction(serialized)) {
181
+ if (standard) return await next(request, requestOptions)
182
+ throw new RpcResponse.InvalidParamsError({
183
+ message: 'Expected a serialized Tempo multisig transaction.',
184
+ })
185
+ }
186
+
187
+ return await submit({
188
+ client,
189
+ method: request.method,
190
+ next,
191
+ request,
192
+ requestOptions,
193
+ serialized,
194
+ store: parameters.store,
195
+ })
196
+ }
197
+ }
198
+
199
+ export declare namespace handleRequest {
200
+ /** RPC request handler. */
201
+ export type Handler = (
202
+ request: Request,
203
+ options?: EIP1193RequestOptions | undefined,
204
+ ) => Promise<unknown>
205
+
206
+ /** RPC request passed to a handler. */
207
+ export type Request = {
208
+ /** RPC method name. */
209
+ method: string
210
+ /** RPC method parameters. */
211
+ params?: readonly unknown[] | undefined
212
+ }
213
+
214
+ /** Parameters for {@link handleRequest}. */
215
+ export type Parameters = {
216
+ /** Store shared by multisig coordinators. */
217
+ store: Store.Atomic
218
+ }
219
+
220
+ /** Error type for {@link handleRequest}. */
221
+ export type ErrorType =
222
+ | ConfigStore.InvalidStoreValueError
223
+ | OperationStore.InvalidStoreValueError
224
+ | OperationStore.StoreConflictError
225
+ | RpcResponse.InvalidParamsError
226
+ }
227
+
228
+ /** Collects approvals and submits a transaction after quorum. @internal */
229
+ // biome-ignore lint/correctness/noUnusedVariables: _
230
+ async function submit(options: submit.Options) {
231
+ const transaction = (() => {
232
+ try {
233
+ return deserialize(options.serialized)
234
+ } catch (error) {
235
+ if (
236
+ options.method !== 'eth_sendRawTransaction' &&
237
+ options.method !== 'eth_sendRawTransactionSync'
238
+ )
239
+ throw error
240
+ return undefined
241
+ }
242
+ })()
243
+ const signature = transaction?.signature
244
+ if (!transaction || signature?.type !== 'multisig') {
245
+ if (
246
+ options.method === 'eth_sendRawTransaction' ||
247
+ options.method === 'eth_sendRawTransactionSync'
248
+ )
249
+ return await options.next(options.request, options.requestOptions)
250
+ throw new RpcResponse.InvalidParamsError({
251
+ message: 'Expected a multisig transaction signature.',
252
+ })
253
+ }
254
+
255
+ const { signature: _, ...unsigned } = transaction
256
+ const envelope = TxEnvelopeTempo.from(unsigned as never)
257
+ const serializedUnsigned = serializeUnsigned(
258
+ envelope,
259
+ options.serialized.startsWith(TxEnvelopeTempo.feePayerMagic),
260
+ )
261
+ const blockNumber = await getBlockNumber(options.client, { cacheTime: 0 })
262
+ const config = MultisigConfig.from(signature.config)
263
+ const configCommitment = await validateConfig({
264
+ account: signature.account,
265
+ blockNumber,
266
+ client: options.client,
267
+ config,
268
+ })
269
+ const operationHash = MultisigOperation.getHash({
270
+ account: signature.account,
271
+ config,
272
+ transaction: serializedUnsigned,
273
+ type: 'transaction',
274
+ })
275
+ const incoming = signature.signatures.map((signature) =>
276
+ SignatureEnvelope.serialize(signature),
277
+ )
278
+ if (incoming.length === 0)
279
+ throw new RpcResponse.InvalidParamsError({
280
+ message: 'A multisig approval envelope must include a signature.',
281
+ })
282
+ const now = Date.now()
283
+ const expiredSubmissionIds = new Set<Hex.Hex>()
284
+ const operation = await OperationStore.update(
285
+ options.store,
286
+ operationHash,
287
+ async (existing) => {
288
+ if (existing && existing.type !== 'transaction')
289
+ throw new OperationStore.InvalidStoreValueError()
290
+ if (existing?.status === 'success') return existing
291
+ if (existing?.status === 'submitting' && existing.expiresAt! > now)
292
+ return existing
293
+ if (existing?.status === 'submitting')
294
+ expiredSubmissionIds.add(existing.submissionId!)
295
+ const existingApprovals = existing
296
+ ? await selectApprovals({
297
+ account: signature.account,
298
+ client: options.client,
299
+ config,
300
+ discardInvalidNested: true,
301
+ hash: operationHash,
302
+ approvals: existing.approvals,
303
+ blockNumber,
304
+ store: options.store,
305
+ })
306
+ : undefined
307
+ const approvals = await selectApprovals({
308
+ account: signature.account,
309
+ client: options.client,
310
+ config,
311
+ hash: operationHash,
312
+ approvals: [...(existingApprovals?.approvals ?? []), ...incoming],
313
+ blockNumber,
314
+ store: options.store,
315
+ })
316
+ return MultisigOperation.from({
317
+ account: signature.account,
318
+ approvals: approvals.approvals,
319
+ config,
320
+ createdAt: existing?.createdAt ?? now,
321
+ hash: operationHash,
322
+ signatureCount: approvals.signatureCount,
323
+ status: 'pending',
324
+ threshold: approvals.threshold,
325
+ transaction: mergeTransaction(
326
+ existing?.transaction,
327
+ serializedUnsigned,
328
+ ),
329
+ type: 'transaction',
330
+ updatedAt: now,
331
+ weight: approvals.weight,
332
+ })
333
+ },
334
+ )
335
+
336
+ for (const submissionId of expiredSubmissionIds) {
337
+ if (
338
+ operation.status === 'submitting' &&
339
+ operation.submissionId?.toLowerCase() === submissionId.toLowerCase()
340
+ )
341
+ continue
342
+ await removeSettledSubmission(options.store, operationHash, submissionId)
343
+ }
344
+
345
+ await ConfigStore.write(options.store, {
346
+ address: signature.account,
347
+ commitment: configCommitment,
348
+ config,
349
+ })
350
+ await cacheNextConfigs({
351
+ account: signature.account,
352
+ config,
353
+ store: options.store,
354
+ transaction,
355
+ })
356
+
357
+ if (operation.type !== 'transaction')
358
+ throw new OperationStore.InvalidStoreValueError()
359
+ if (operation.status === 'success')
360
+ return await submittedResult(options, operation)
361
+ if (operation.status === 'submitting' && operation.expiresAt! > Date.now())
362
+ return await submittingResult(options, operation)
363
+ if (operation.weight < operation.threshold)
364
+ return pendingResult(options.method, operation)
365
+
366
+ const submissionId = Hex.random(32)
367
+ const timeout = options.request.params?.[1]
368
+ const synchronous =
369
+ options.method === 'eth_sendRawTransactionSync' ||
370
+ options.method === 'multisig_approveRawTransactionSync'
371
+ const leaseTtl =
372
+ synchronous &&
373
+ typeof timeout === 'number' &&
374
+ Number.isSafeInteger(timeout) &&
375
+ timeout >= 0
376
+ ? timeout + submissionTtl
377
+ : submissionTtl
378
+ const claim = await OperationStore.update(
379
+ options.store,
380
+ operationHash,
381
+ (current) => {
382
+ if (!current || current.type !== 'transaction')
383
+ throw new OperationStore.InvalidStoreValueError()
384
+ if (current.status === 'success') return current
385
+ if (current.status === 'submitting' && current.expiresAt! > Date.now())
386
+ return current
387
+ if (current.weight < current.threshold) return current
388
+ const now = Date.now()
389
+ return MultisigOperation.from({
390
+ ...current,
391
+ expiresAt: Math.min(now + leaseTtl, Number.MAX_SAFE_INTEGER),
392
+ status: 'submitting',
393
+ submissionId,
394
+ updatedAt: now,
395
+ })
396
+ },
397
+ )
398
+ if (claim.type !== 'transaction')
399
+ throw new OperationStore.InvalidStoreValueError()
400
+ if (claim.status === 'success') return await submittedResult(options, claim)
401
+ if (claim.status === 'pending') return pendingResult(options.method, claim)
402
+ if (claim.submissionId !== submissionId)
403
+ return await submittingResult(options, claim)
404
+
405
+ const { final, transactionHash: initialTransactionHash } =
406
+ await (async () => {
407
+ try {
408
+ const blockNumber = await getBlockNumber(options.client, {
409
+ cacheTime: 0,
410
+ })
411
+ await validateConfig({
412
+ account: claim.account,
413
+ blockNumber,
414
+ client: options.client,
415
+ config: claim.config,
416
+ })
417
+ const finalApprovals = await selectApprovals({
418
+ account: claim.account,
419
+ blockNumber,
420
+ client: options.client,
421
+ config: claim.config,
422
+ hash: claim.hash,
423
+ approvals: claim.approvals,
424
+ store: options.store,
425
+ })
426
+ const final = MultisigOperation.serializeTransaction(claim, {
427
+ approvals: finalApprovals.selectedApprovals,
428
+ })
429
+ const transactionHash = TxEnvelopeTempo.hash(
430
+ TxEnvelopeTempo.deserialize(final) as TxEnvelopeTempo.Signed,
431
+ )
432
+ await OperationStore.writeSubmission(
433
+ options.store,
434
+ operationHash,
435
+ submissionId,
436
+ final,
437
+ )
438
+ return { final, transactionHash }
439
+ } catch (error) {
440
+ await releaseSubmission(options.store, operationHash, submissionId)
441
+ throw error
442
+ }
443
+ })()
444
+ let transactionHash = initialTransactionHash
445
+
446
+ let result: unknown
447
+ const stopLease = maintainSubmissionLease(
448
+ options.store,
449
+ operationHash,
450
+ submissionId,
451
+ leaseTtl,
452
+ )
453
+ let leaseStopped = false
454
+ const stopLeaseOnce = async () => {
455
+ if (leaseStopped) return
456
+ leaseStopped = true
457
+ await stopLease()
458
+ }
459
+ try {
460
+ try {
461
+ result = await options.next(
462
+ {
463
+ method:
464
+ options.method === 'eth_sendRawTransaction' ||
465
+ options.method === 'multisig_approveRawTransaction'
466
+ ? 'eth_sendRawTransaction'
467
+ : 'eth_sendRawTransactionSync',
468
+ params: [final, ...(options.request.params?.slice(1) ?? [])],
469
+ },
470
+ options.requestOptions,
471
+ )
472
+ const returnedHash = getTransactionHash(result)
473
+ if (returnedHash.toLowerCase() !== transactionHash.toLowerCase())
474
+ transactionHash = returnedHash
475
+ } catch (error) {
476
+ const submittedHash = await OperationStore.readSubmission(
477
+ options.store,
478
+ claim,
479
+ submissionId,
480
+ )
481
+ const transaction = await (async () => {
482
+ if (!submittedHash) return null
483
+ try {
484
+ return await options.next({
485
+ method: 'eth_getTransactionByHash',
486
+ params: [submittedHash],
487
+ })
488
+ } catch {
489
+ return null
490
+ }
491
+ })()
492
+ await stopLeaseOnce()
493
+ if (!submittedHash || !transaction) {
494
+ await releaseSubmission(options.store, operationHash, submissionId)
495
+ throw error
496
+ }
497
+ transactionHash = submittedHash
498
+ }
499
+ } finally {
500
+ await stopLeaseOnce()
501
+ }
502
+ const success = await OperationStore.update(
503
+ options.store,
504
+ operationHash,
505
+ (current) => {
506
+ if (!current || current.type !== 'transaction')
507
+ throw new OperationStore.InvalidStoreValueError()
508
+ if (current.status === 'success') {
509
+ if (
510
+ current.transactionHash?.toLowerCase() !==
511
+ transactionHash.toLowerCase()
512
+ )
513
+ throw new OperationStore.InvalidStoreValueError()
514
+ return current
515
+ }
516
+ if (
517
+ current.status !== 'submitting' ||
518
+ current.submissionId !== submissionId
519
+ )
520
+ throw new OperationStore.InvalidStoreValueError()
521
+ const { expiresAt: _, submissionId: __, ...operation } = current
522
+ return MultisigOperation.from({
523
+ ...operation,
524
+ status: 'success',
525
+ transactionHash,
526
+ updatedAt: Date.now(),
527
+ })
528
+ },
529
+ )
530
+ if (success.type !== 'transaction' || success.status !== 'success')
531
+ throw new OperationStore.InvalidStoreValueError()
532
+ await removeSettledSubmission(options.store, operationHash, submissionId)
533
+ if (
534
+ options.method === 'eth_sendRawTransactionSync' &&
535
+ result &&
536
+ typeof result === 'object'
537
+ )
538
+ return { ...result, multisig: MultisigOperation.toRpc(success) }
539
+ return await submittedResult(options, success)
540
+ }
541
+
542
+ declare namespace submit {
543
+ /** Options for {@link submit}. */
544
+ export type Options = {
545
+ /** Client used to validate configs. */
546
+ client: ReturnType<typeof createClient>
547
+ /** RPC submission method. */
548
+ method:
549
+ | 'eth_sendRawTransaction'
550
+ | 'eth_sendRawTransactionSync'
551
+ | 'multisig_approveRawTransaction'
552
+ | 'multisig_approveRawTransactionSync'
553
+ /** Downstream RPC request handler. */
554
+ next: handleRequest.Handler
555
+ /** Original RPC request. */
556
+ request: handleRequest.Request
557
+ /** Original request overrides. */
558
+ requestOptions?: EIP1193RequestOptions | undefined
559
+ /** Serialized Tempo transaction. */
560
+ serialized: Hex.Hex
561
+ /** Shared multisig store. */
562
+ store: Store.Atomic
563
+ }
564
+ }
565
+
566
+ /** Collects approvals for a multisig key authorization. @internal */
567
+ // biome-ignore lint/correctness/noUnusedVariables: declaration merge
568
+ async function approveKeyAuthorization(
569
+ options: approveKeyAuthorization.Options,
570
+ ) {
571
+ const value = options.request.params?.[0]
572
+ if (!value || typeof value !== 'object')
573
+ throw new RpcResponse.InvalidParamsError({
574
+ message: 'Expected a multisig key authorization approval.',
575
+ })
576
+
577
+ const approval = await (async () => {
578
+ if ('keyAuthorization' in value) {
579
+ const authorization = (() => {
580
+ try {
581
+ return KeyAuthorization.fromRpc(
582
+ value.keyAuthorization as KeyAuthorization.Rpc,
583
+ )
584
+ } catch {
585
+ throw new RpcResponse.InvalidParamsError({
586
+ message: 'Invalid multisig key authorization.',
587
+ })
588
+ }
589
+ })()
590
+ const signature = authorization.signature
591
+ if (signature?.type !== 'multisig')
592
+ throw new RpcResponse.InvalidParamsError({
593
+ message: 'Expected a multisig key authorization signature.',
594
+ })
595
+ if (
596
+ !authorization.account ||
597
+ !isAddressEqual(authorization.account, signature.account)
598
+ )
599
+ throw new RpcResponse.InvalidParamsError({
600
+ message:
601
+ 'Multisig key authorization account does not match its signature.',
602
+ })
603
+ const { signature: _, ...unsigned } = authorization
604
+ const keyAuthorization = KeyAuthorization.serialize(
605
+ KeyAuthorization.from(unsigned),
606
+ )
607
+ const config = MultisigConfig.from(signature.config)
608
+ const hash = MultisigOperation.getHash({
609
+ account: signature.account,
610
+ config,
611
+ keyAuthorization,
612
+ type: 'keyAuthorization',
613
+ })
614
+ return {
615
+ account: signature.account,
616
+ approvals: signature.signatures.map((signature) =>
617
+ SignatureEnvelope.serialize(signature),
618
+ ),
619
+ config,
620
+ hash,
621
+ keyAuthorization,
622
+ }
623
+ }
624
+
625
+ if ('hash' in value && 'signature' in value) {
626
+ if (typeof value.hash !== 'string' || !Hash.validate(value.hash))
627
+ throw new RpcResponse.InvalidParamsError({
628
+ message: 'Expected a multisig operation hash.',
629
+ })
630
+ const operation = await OperationStore.read(options.store, value.hash)
631
+ if (!operation || operation.type !== 'keyAuthorization')
632
+ throw new RpcResponse.InvalidParamsError({
633
+ message: 'Multisig key authorization operation was not found.',
634
+ })
635
+ if (operation.status === 'success') return { operation }
636
+ const signature = (() => {
637
+ try {
638
+ return SignatureEnvelope.serialize(
639
+ SignatureEnvelope.from(value.signature as Hex.Hex),
640
+ )
641
+ } catch {
642
+ throw new RpcResponse.InvalidParamsError({
643
+ message: 'Invalid multisig owner signature.',
644
+ })
645
+ }
646
+ })()
647
+ return {
648
+ account: operation.account,
649
+ approvals: [signature],
650
+ config: operation.config,
651
+ hash: operation.hash,
652
+ keyAuthorization: operation.keyAuthorization,
653
+ }
654
+ }
655
+
656
+ throw new RpcResponse.InvalidParamsError({
657
+ message: 'Expected a multisig key authorization approval.',
658
+ })
659
+ })()
660
+ if ('operation' in approval)
661
+ return MultisigOperation.toRpc(approval.operation)
662
+ if (approval.approvals.length === 0)
663
+ throw new RpcResponse.InvalidParamsError({
664
+ message: 'A multisig approval envelope must include a signature.',
665
+ })
666
+
667
+ const blockNumber = await getBlockNumber(options.client, { cacheTime: 0 })
668
+ const commitment = await validateConfig({
669
+ account: approval.account,
670
+ blockNumber,
671
+ client: options.client,
672
+ config: approval.config,
673
+ })
674
+ const now = Date.now()
675
+ const operation = await OperationStore.update(
676
+ options.store,
677
+ approval.hash,
678
+ async (existing) => {
679
+ if (existing && existing.type !== 'keyAuthorization')
680
+ throw new OperationStore.InvalidStoreValueError()
681
+ if (existing?.status === 'success') return existing
682
+ if (
683
+ existing &&
684
+ (existing.account.toLowerCase() !== approval.account.toLowerCase() ||
685
+ MultisigConfig.getCommitment(existing.config).toLowerCase() !==
686
+ MultisigConfig.getCommitment(approval.config).toLowerCase() ||
687
+ existing.keyAuthorization.toLowerCase() !==
688
+ approval.keyAuthorization.toLowerCase())
689
+ )
690
+ throw new OperationStore.InvalidStoreValueError()
691
+ const existingApprovals = existing
692
+ ? await selectApprovals({
693
+ account: approval.account,
694
+ approvals: existing.approvals,
695
+ blockNumber,
696
+ client: options.client,
697
+ config: approval.config,
698
+ discardInvalidNested: true,
699
+ hash: approval.hash,
700
+ store: options.store,
701
+ })
702
+ : undefined
703
+ const approvals = await selectApprovals({
704
+ account: approval.account,
705
+ approvals: [
706
+ ...(existingApprovals?.approvals ?? []),
707
+ ...approval.approvals,
708
+ ],
709
+ blockNumber,
710
+ client: options.client,
711
+ config: approval.config,
712
+ hash: approval.hash,
713
+ store: options.store,
714
+ })
715
+ if (
716
+ existing &&
717
+ approvals.approvals.length === existing.approvals.length &&
718
+ approvals.approvals.every(
719
+ (approval, index) => approval === existing.approvals[index],
720
+ )
721
+ )
722
+ return existing
723
+ const pending = {
724
+ account: approval.account,
725
+ approvals: approvals.approvals,
726
+ config: approval.config,
727
+ createdAt: existing?.createdAt ?? now,
728
+ hash: approval.hash,
729
+ keyAuthorization: approval.keyAuthorization,
730
+ signatureCount: approvals.signatureCount,
731
+ threshold: approvals.threshold,
732
+ type: 'keyAuthorization',
733
+ updatedAt: now,
734
+ weight: approvals.weight,
735
+ } as const
736
+ if (approvals.weight < approvals.threshold)
737
+ return MultisigOperation.from({ ...pending, status: 'pending' })
738
+ return MultisigOperation.from({
739
+ ...pending,
740
+ keyAuthorization: MultisigOperation.serializeKeyAuthorization(
741
+ approval.keyAuthorization,
742
+ {
743
+ account: approval.account,
744
+ approvals: approvals.selectedApprovals,
745
+ config: approval.config,
746
+ },
747
+ ),
748
+ status: 'success',
749
+ })
750
+ },
751
+ )
752
+ await ConfigStore.write(options.store, {
753
+ address: approval.account,
754
+ commitment,
755
+ config: approval.config,
756
+ })
757
+ if (operation.type !== 'keyAuthorization')
758
+ throw new OperationStore.InvalidStoreValueError()
759
+ return MultisigOperation.toRpc(operation)
760
+ }
761
+
762
+ declare namespace approveKeyAuthorization {
763
+ /** Options for {@link approveKeyAuthorization}. */
764
+ export type Options = {
765
+ /** Client used to validate configs. */
766
+ client: ReturnType<typeof createClient>
767
+ /** Original RPC request. */
768
+ request: handleRequest.Request
769
+ /** Shared multisig store. */
770
+ store: Store.Atomic
771
+ }
772
+ }
773
+
774
+ /** Deserializes a Tempo transaction or throws an RPC parameter error. */
775
+ function deserialize(serialized: Hex.Hex) {
776
+ try {
777
+ return Transaction.deserialize(
778
+ serialized as Transaction.TransactionSerializedTempo,
779
+ )
780
+ } catch {
781
+ throw new RpcResponse.InvalidParamsError({
782
+ message: 'Invalid serialized Tempo transaction.',
783
+ })
784
+ }
785
+ }
786
+
787
+ /** Validates a config against an observed chain commitment. */
788
+ function assertConfig(options: {
789
+ account: `0x${string}`
790
+ commitment: Hex.Hex
791
+ config: MultisigConfig.Config
792
+ }) {
793
+ const { account, commitment, config } = options
794
+ if (
795
+ config.version === 0n &&
796
+ MultisigConfig.getAddress(config).toLowerCase() !== account.toLowerCase()
797
+ )
798
+ throw new RpcResponse.InvalidParamsError({
799
+ message: 'Initial multisig config does not match the multisig account.',
800
+ })
801
+ const expected = (() => {
802
+ if (config.version === 0n) return Hex.fromNumber(0, { size: 32 })
803
+ return MultisigConfig.getCommitment(config)
804
+ })()
805
+ if (commitment.toLowerCase() !== expected.toLowerCase())
806
+ throw new RpcResponse.InvalidParamsError({
807
+ message: `Multisig config does not match account ${account}.`,
808
+ })
809
+ }
810
+
811
+ /** Reads and validates a config commitment at one block. */
812
+ async function validateConfig(options: {
813
+ account: `0x${string}`
814
+ blockNumber: bigint
815
+ client: ReturnType<typeof createClient>
816
+ config: MultisigConfig.Config
817
+ }) {
818
+ const { account, blockNumber, client, config } = options
819
+ const commitment = await getConfigCommitment(client, {
820
+ account,
821
+ blockNumber,
822
+ })
823
+ assertConfig({ account, commitment, config })
824
+ return commitment
825
+ }
826
+
827
+ /** Caches candidate configs from valid native update calls. */
828
+ // biome-ignore lint/correctness/noUnusedVariables: declaration merge
829
+ async function cacheNextConfigs(options: cacheNextConfigs.Options) {
830
+ let currentConfig = options.config
831
+ for (const call of options.transaction.calls) {
832
+ if (
833
+ !call.to ||
834
+ !isAddressEqual(call.to, Addresses.nativeMultisig) ||
835
+ !call.data
836
+ )
837
+ continue
838
+ const decoded = (() => {
839
+ try {
840
+ return decodeFunctionData({ abi: Abis.nativeMultisig, data: call.data })
841
+ } catch {
842
+ return undefined
843
+ }
844
+ })()
845
+ if (decoded?.functionName !== 'updateConfig') continue
846
+ const [current, threshold, owners] = decoded.args
847
+ const suppliedConfig = (() => {
848
+ try {
849
+ return MultisigConfig.from(current)
850
+ } catch {
851
+ return undefined
852
+ }
853
+ })()
854
+ if (
855
+ !suppliedConfig ||
856
+ MultisigConfig.getCommitment(suppliedConfig).toLowerCase() !==
857
+ MultisigConfig.getCommitment(currentConfig).toLowerCase()
858
+ )
859
+ continue
860
+ const config = (() => {
861
+ try {
862
+ return MultisigConfig.from({
863
+ owners,
864
+ salt: suppliedConfig.salt,
865
+ threshold,
866
+ version: suppliedConfig.version + 1n,
867
+ })
868
+ } catch {
869
+ return undefined
870
+ }
871
+ })()
872
+ if (!config) continue
873
+ await ConfigStore.write(options.store, {
874
+ address: options.account,
875
+ commitment: MultisigConfig.getCommitment(config),
876
+ config,
877
+ })
878
+ currentConfig = config
879
+ }
880
+ }
881
+
882
+ declare namespace cacheNextConfigs {
883
+ /** Parameters for {@link cacheNextConfigs}. */
884
+ export type Options = {
885
+ /** Root multisig account. */
886
+ account: Address
887
+ /** Root config used to authorize the transaction. */
888
+ config: MultisigConfig.Config
889
+ /** Shared multisig store. */
890
+ store: Store.Store
891
+ /** Submitted transaction containing potential config updates. */
892
+ transaction: Transaction.TransactionSerializableTempo
893
+ }
894
+ }
895
+
896
+ /** Selects approvals after validating every nested config. */
897
+ // biome-ignore lint/correctness/noUnusedVariables: _
898
+ async function selectApprovals(options: selectApprovals.Options) {
899
+ const validation = new Map<string, Promise<Hex.Hex>>()
900
+ let validationCount = 0
901
+ const select = async (approvals: readonly SignatureEnvelope.Serialized[]) => {
902
+ const result = await MultisigOperation.selectApprovals({
903
+ account: options.account,
904
+ approvals,
905
+ config: options.config,
906
+ hash: options.hash,
907
+ })
908
+ const configs = new Map<
909
+ string,
910
+ { account: Address; config: MultisigConfig.Config }
911
+ >()
912
+ const visit = (signature: SignatureEnvelope.SignatureEnvelope) => {
913
+ if (signature.type !== 'multisig') return
914
+ const config = MultisigConfig.from(signature.config)
915
+ const key = signature.account.toLowerCase()
916
+ configs.set(key, { account: signature.account, config })
917
+ for (const approval of signature.signatures) visit(approval)
918
+ }
919
+ for (const approval of result.approvals)
920
+ visit(SignatureEnvelope.from(approval))
921
+
922
+ for (const { account, config } of configs.values()) {
923
+ const key = `${account.toLowerCase()}:${MultisigConfig.getCommitment(config)}`
924
+ const pending = (() => {
925
+ const existing = validation.get(key)
926
+ if (existing) return existing
927
+ validationCount++
928
+ if (validationCount > MultisigConfig.maxOwners)
929
+ throw new RpcResponse.InvalidParamsError({
930
+ message: 'Multisig approval validation exceeds the owner limit.',
931
+ })
932
+ const pending = validateConfig({
933
+ account,
934
+ blockNumber: options.blockNumber,
935
+ client: options.client,
936
+ config,
937
+ })
938
+ validation.set(key, pending)
939
+ return pending
940
+ })()
941
+ const commitment = await pending
942
+ await ConfigStore.write(options.store, {
943
+ address: account,
944
+ commitment,
945
+ config,
946
+ })
947
+ }
948
+ return result
949
+ }
950
+ try {
951
+ if (!options.discardInvalidNested) return await select(options.approvals)
952
+
953
+ const approvals: SignatureEnvelope.Serialized[] = []
954
+ for (const approval of options.approvals) {
955
+ if (SignatureEnvelope.from(approval).type !== 'multisig') {
956
+ approvals.push(approval)
957
+ continue
958
+ }
959
+ try {
960
+ const retained = (await select([approval])).approvals[0]
961
+ if (retained) approvals.push(retained)
962
+ } catch (error) {
963
+ if (
964
+ error instanceof MultisigOperation.InvalidApprovalError ||
965
+ error instanceof RpcResponse.InvalidParamsError
966
+ )
967
+ continue
968
+ throw error
969
+ }
970
+ }
971
+ return await select(approvals)
972
+ } catch (error) {
973
+ if (error instanceof MultisigOperation.InvalidApprovalError)
974
+ throw new RpcResponse.InvalidParamsError({ message: error.shortMessage })
975
+ throw error
976
+ }
977
+ }
978
+
979
+ declare namespace selectApprovals {
980
+ /** Options for {@link selectApprovals}. */
981
+ export type Options = MultisigOperation.selectApprovals.Options & {
982
+ /** Block used to validate every config. */
983
+ blockNumber: bigint
984
+ /** Client used to validate nested multisig configurations. */
985
+ client: ReturnType<typeof createClient>
986
+ /** Discards stored nested approvals invalidated by a child configuration change. */
987
+ discardInvalidNested?: boolean | undefined
988
+ /** Shared multisig store. */
989
+ store: Store.Store
990
+ }
991
+ }
992
+
993
+ /** Returns an existing successful operation through the requested send method. */
994
+ async function submittedResult(
995
+ options: submit.Options,
996
+ operation: MultisigOperation.TransactionOperation,
997
+ ) {
998
+ if (
999
+ options.method === 'eth_sendRawTransaction' ||
1000
+ options.method === 'multisig_approveRawTransaction'
1001
+ )
1002
+ return operation.hash
1003
+ if (options.method === 'multisig_approveRawTransactionSync')
1004
+ return MultisigOperation.toRpc(operation)
1005
+ const timeout = options.request.params?.[1]
1006
+ const deadline =
1007
+ Date.now() +
1008
+ (typeof timeout === 'number' && timeout >= 0 ? timeout : submissionTtl)
1009
+ while (true) {
1010
+ const receipt = await options.next(
1011
+ {
1012
+ method: 'eth_getTransactionReceipt',
1013
+ params: [operation.transactionHash],
1014
+ },
1015
+ options.requestOptions,
1016
+ )
1017
+ if (receipt && typeof receipt === 'object')
1018
+ return { ...receipt, multisig: MultisigOperation.toRpc(operation) }
1019
+ if (Date.now() >= deadline)
1020
+ throw new Error('Timed out while waiting for the multisig transaction.')
1021
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval))
1022
+ }
1023
+ }
1024
+
1025
+ /** Waits for the relay that owns a live submission lease. */
1026
+ async function submittingResult(
1027
+ options: submit.Options,
1028
+ operation: MultisigOperation.TransactionOperation,
1029
+ ): Promise<unknown> {
1030
+ if (
1031
+ options.method === 'eth_sendRawTransaction' ||
1032
+ options.method === 'multisig_approveRawTransaction'
1033
+ )
1034
+ return operation.hash
1035
+ const timeout = options.request.params?.[1]
1036
+ const deadline =
1037
+ Date.now() +
1038
+ (typeof timeout === 'number' && timeout >= 0 ? timeout : submissionTtl)
1039
+ while (true) {
1040
+ const current = await OperationStore.read(options.store, operation.hash)
1041
+ if (!current || current.type !== 'transaction')
1042
+ throw new OperationStore.InvalidStoreValueError()
1043
+ if (current.status === 'success')
1044
+ return await submittedResult(options, current)
1045
+ if (current.status === 'pending' || current.expiresAt! <= Date.now())
1046
+ return await submit(options)
1047
+ if (Date.now() >= deadline) return pendingResult(options.method, current)
1048
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval))
1049
+ }
1050
+ }
1051
+
1052
+ /** Returns a pending result for an operation that has not reached quorum. */
1053
+ function pendingResult(
1054
+ method: submit.Options['method'],
1055
+ operation: MultisigOperation.TransactionOperation,
1056
+ ) {
1057
+ if (
1058
+ method === 'eth_sendRawTransaction' ||
1059
+ method === 'multisig_approveRawTransaction'
1060
+ )
1061
+ return operation.hash
1062
+ if (method === 'multisig_approveRawTransactionSync')
1063
+ return MultisigOperation.toRpc(operation)
1064
+ return {
1065
+ blockHash: null,
1066
+ blockNumber: null,
1067
+ contractAddress: null,
1068
+ cumulativeGasUsed: null,
1069
+ effectiveGasPrice: null,
1070
+ from: operation.account,
1071
+ gasUsed: null,
1072
+ logs: [],
1073
+ logsBloom: null,
1074
+ multisig: MultisigOperation.toRpc(operation),
1075
+ status: 'pending',
1076
+ to: null,
1077
+ transactionHash: operation.hash,
1078
+ transactionIndex: null,
1079
+ type: '0x76',
1080
+ } as const
1081
+ }
1082
+
1083
+ /** Marks a transaction as successful after a lookup proves that it was submitted. */
1084
+ async function completeSubmission(
1085
+ store: Store.Atomic,
1086
+ operation: MultisigOperation.TransactionOperation,
1087
+ transactionHash: Hex.Hex,
1088
+ ) {
1089
+ if (operation.status !== 'submitting' || !operation.submissionId)
1090
+ throw new OperationStore.InvalidStoreValueError()
1091
+ const success = await OperationStore.update(
1092
+ store,
1093
+ operation.hash,
1094
+ (current) => {
1095
+ if (!current || current.type !== 'transaction')
1096
+ throw new OperationStore.InvalidStoreValueError()
1097
+ if (current.status === 'success') {
1098
+ if (
1099
+ current.transactionHash?.toLowerCase() !==
1100
+ transactionHash.toLowerCase()
1101
+ )
1102
+ throw new OperationStore.InvalidStoreValueError()
1103
+ return current
1104
+ }
1105
+ if (
1106
+ current.status !== 'submitting' ||
1107
+ current.submissionId !== operation.submissionId
1108
+ )
1109
+ throw new OperationStore.InvalidStoreValueError()
1110
+ const {
1111
+ expiresAt: _,
1112
+ submissionId: __,
1113
+ transactionHash: ___,
1114
+ ...value
1115
+ } = current
1116
+ return MultisigOperation.from({
1117
+ ...value,
1118
+ status: 'success',
1119
+ transactionHash,
1120
+ updatedAt: Date.now(),
1121
+ })
1122
+ },
1123
+ )
1124
+ await removeSettledSubmission(store, operation.hash, operation.submissionId)
1125
+ return success as MultisigOperation.TransactionOperation
1126
+ }
1127
+
1128
+ /** Releases a failed submission lease without discarding collected approvals. */
1129
+ async function releaseSubmission(
1130
+ store: Store.Atomic,
1131
+ hash: Hex.Hex,
1132
+ submissionId: Hex.Hex,
1133
+ ) {
1134
+ await OperationStore.update(store, hash, (current) => {
1135
+ if (!current || current.type !== 'transaction')
1136
+ throw new OperationStore.InvalidStoreValueError()
1137
+ if (
1138
+ current.status !== 'submitting' ||
1139
+ current.submissionId !== submissionId
1140
+ )
1141
+ return current
1142
+ const { expiresAt: _, submissionId: __, ...operation } = current
1143
+ return MultisigOperation.from({
1144
+ ...operation,
1145
+ status: 'pending',
1146
+ updatedAt: Date.now(),
1147
+ })
1148
+ })
1149
+ await OperationStore.removeSubmission(store, hash, submissionId)
1150
+ }
1151
+
1152
+ /** Removes settled submission data without replacing a successful result with a cleanup error. */
1153
+ async function removeSettledSubmission(
1154
+ store: Store.Store,
1155
+ hash: Hex.Hex,
1156
+ submissionId: Hex.Hex,
1157
+ ) {
1158
+ try {
1159
+ await OperationStore.removeSubmission(store, hash, submissionId)
1160
+ } catch {}
1161
+ }
1162
+
1163
+ /** Preserves or upgrades a fee-payer envelope without removing an existing signature. */
1164
+ function mergeTransaction(existing: Hex.Hex | undefined, incoming: Hex.Hex) {
1165
+ if (!existing) return incoming
1166
+ const existingTransaction = TxEnvelopeTempo.deserialize(existing as never)
1167
+ const incomingTransaction = TxEnvelopeTempo.deserialize(incoming as never)
1168
+ if (!('feePayerSignature' in incomingTransaction)) return existing
1169
+ if (incomingTransaction.feePayerSignature !== null) return incoming
1170
+ if (!('feePayerSignature' in existingTransaction)) return incoming
1171
+ return existing
1172
+ }
1173
+
1174
+ /** Returns a synthetic transaction while the downstream transaction is unavailable. */
1175
+ async function toTransaction(
1176
+ client: ReturnType<typeof createClient>,
1177
+ operation: MultisigOperation.TransactionOperation,
1178
+ store: Store.Store,
1179
+ ) {
1180
+ const approvals = await (async () => {
1181
+ if (operation.status !== 'pending')
1182
+ return await MultisigOperation.selectApprovals({
1183
+ account: operation.account,
1184
+ approvals: operation.approvals,
1185
+ config: operation.config,
1186
+ hash: operation.hash,
1187
+ })
1188
+ const blockNumber = await getBlockNumber(client, { cacheTime: 0 })
1189
+ await validateConfig({
1190
+ account: operation.account,
1191
+ blockNumber,
1192
+ client,
1193
+ config: operation.config,
1194
+ })
1195
+ return await selectApprovals({
1196
+ account: operation.account,
1197
+ approvals: operation.approvals,
1198
+ blockNumber,
1199
+ client,
1200
+ config: operation.config,
1201
+ discardInvalidNested: true,
1202
+ hash: operation.hash,
1203
+ store,
1204
+ })
1205
+ })()
1206
+ const current =
1207
+ operation.status === 'pending'
1208
+ ? MultisigOperation.from({
1209
+ ...operation,
1210
+ approvals: approvals.approvals,
1211
+ signatureCount: approvals.signatureCount,
1212
+ threshold: approvals.threshold,
1213
+ weight: approvals.weight,
1214
+ })
1215
+ : operation
1216
+ const serialized = MultisigOperation.serializeTransaction(
1217
+ approvals.approvals.length > 0 ? current : operation,
1218
+ {
1219
+ // Keep one stored approval in the synthetic envelope when every nested
1220
+ // approval became stale. The next submission replaces it before broadcast.
1221
+ approvals:
1222
+ approvals.selectedApprovals.length > 0
1223
+ ? approvals.selectedApprovals
1224
+ : operation.approvals.slice(0, 1),
1225
+ },
1226
+ )
1227
+ const transaction = deserialize(serialized)
1228
+ return {
1229
+ ...ox_Transaction.toRpc(
1230
+ {
1231
+ ...transaction,
1232
+ blockHash: null,
1233
+ blockNumber: null,
1234
+ from: operation.account,
1235
+ hash: operation.hash,
1236
+ transactionIndex: null,
1237
+ } as never,
1238
+ { pending: true },
1239
+ ),
1240
+ multisig: MultisigOperation.toRpc(current),
1241
+ }
1242
+ }
1243
+
1244
+ /** Returns the persisted transaction hash for a submitting or successful operation. */
1245
+ async function getSubmittedTransactionHash(
1246
+ store: Store.Store,
1247
+ operation: MultisigOperation.TransactionOperation,
1248
+ ) {
1249
+ if (operation.status === 'success') return operation.transactionHash!
1250
+ if (operation.status !== 'submitting' || !operation.submissionId)
1251
+ throw new OperationStore.InvalidStoreValueError()
1252
+ return await OperationStore.readSubmission(
1253
+ store,
1254
+ operation,
1255
+ operation.submissionId,
1256
+ )
1257
+ }
1258
+
1259
+ /** Renews a submission lease until the returned cleanup function runs. */
1260
+ function maintainSubmissionLease(
1261
+ store: Store.Atomic,
1262
+ hash: Hex.Hex,
1263
+ submissionId: Hex.Hex,
1264
+ leaseTtl: number,
1265
+ ) {
1266
+ let active = true
1267
+ let error: unknown
1268
+ let renewal = Promise.resolve()
1269
+ const timer = setInterval(() => {
1270
+ renewal = renewal.then(async () => {
1271
+ if (!active || error) return
1272
+ try {
1273
+ const operation = await OperationStore.update(
1274
+ store,
1275
+ hash,
1276
+ (current) => {
1277
+ if (!current || current.type !== 'transaction')
1278
+ throw new OperationStore.InvalidStoreValueError()
1279
+ if (
1280
+ current.status !== 'submitting' ||
1281
+ current.submissionId !== submissionId
1282
+ )
1283
+ return current
1284
+ return MultisigOperation.from({
1285
+ ...current,
1286
+ expiresAt: Math.min(
1287
+ Date.now() + leaseTtl,
1288
+ Number.MAX_SAFE_INTEGER,
1289
+ ),
1290
+ updatedAt: Date.now(),
1291
+ })
1292
+ },
1293
+ )
1294
+ if (
1295
+ operation.type !== 'transaction' ||
1296
+ operation.status !== 'submitting' ||
1297
+ operation.submissionId !== submissionId
1298
+ )
1299
+ throw new OperationStore.InvalidStoreValueError()
1300
+ } catch (cause) {
1301
+ error = cause
1302
+ }
1303
+ })
1304
+ }, submissionTtl / 2)
1305
+
1306
+ return async () => {
1307
+ active = false
1308
+ clearInterval(timer)
1309
+ await renewal
1310
+ if (error) throw error
1311
+ }
1312
+ }
1313
+
1314
+ /** Canonically serializes an unsigned Tempo transaction. */
1315
+ function serializeUnsigned(
1316
+ envelope: Omit<TxEnvelopeTempo.TxEnvelopeTempo, 'signature'>,
1317
+ feePayer: boolean,
1318
+ ) {
1319
+ return TxEnvelopeTempo.serialize(
1320
+ envelope,
1321
+ feePayer
1322
+ ? envelope.from
1323
+ ? { format: 'feePayer', sender: envelope.from }
1324
+ : { format: 'feePayer' }
1325
+ : {},
1326
+ )
1327
+ }
1328
+
1329
+ /** Extracts a transaction hash from an RPC submission result. */
1330
+ function getTransactionHash(result: unknown): Hex.Hex {
1331
+ if (typeof result === 'string' && Hash.validate(result)) return result
1332
+ if (
1333
+ result &&
1334
+ typeof result === 'object' &&
1335
+ 'transactionHash' in result &&
1336
+ typeof result.transactionHash === 'string' &&
1337
+ Hash.validate(result.transactionHash)
1338
+ )
1339
+ return result.transactionHash
1340
+ throw new Error('Expected transaction hash in multisig broadcast result.')
1341
+ }
1342
+
1343
+ /** Checks whether a value is a serialized Tempo transaction. */
1344
+ function isSerializedTempoTransaction(value: unknown): value is Hex.Hex {
1345
+ return (
1346
+ typeof value === 'string' &&
1347
+ (value.startsWith('0x76') || value.startsWith('0x78'))
1348
+ )
1349
+ }