@unionlabs/payments 0.2.1 → 0.3.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 (126) hide show
  1. package/dist/cjs/Attestor.js +9 -2
  2. package/dist/cjs/Attestor.js.map +1 -1
  3. package/dist/cjs/Domain.js +8 -2
  4. package/dist/cjs/Domain.js.map +1 -1
  5. package/dist/cjs/Error.js +1 -1
  6. package/dist/cjs/Error.js.map +1 -1
  7. package/dist/cjs/EvmPublicClient.js +5 -277
  8. package/dist/cjs/EvmPublicClient.js.map +1 -1
  9. package/dist/cjs/EvmWalletClient.js +7 -642
  10. package/dist/cjs/EvmWalletClient.js.map +1 -1
  11. package/dist/cjs/Payment.js +84 -79
  12. package/dist/cjs/Payment.js.map +1 -1
  13. package/dist/cjs/Prover.js +2 -2
  14. package/dist/cjs/Prover.js.map +1 -1
  15. package/dist/cjs/PublicClient.js +2 -2
  16. package/dist/cjs/PublicClient.js.map +1 -1
  17. package/dist/cjs/WalletClient.js +2 -2
  18. package/dist/cjs/WalletClient.js.map +1 -1
  19. package/dist/cjs/constants/ibc-core-registry.js +6 -6
  20. package/dist/cjs/constants/ibc-core-registry.js.map +1 -1
  21. package/dist/cjs/internal/evmPublicClient.js +261 -0
  22. package/dist/cjs/internal/evmPublicClient.js.map +1 -0
  23. package/dist/cjs/internal/evmWalletClient.js +695 -0
  24. package/dist/cjs/internal/evmWalletClient.js.map +1 -1
  25. package/dist/cjs/internal/publicClient.js +0 -2
  26. package/dist/cjs/internal/publicClient.js.map +1 -1
  27. package/dist/cjs/promises/Payment.js +4 -3
  28. package/dist/cjs/promises/Payment.js.map +1 -1
  29. package/dist/cjs/promises/PublicClient.js +1 -2
  30. package/dist/cjs/promises/PublicClient.js.map +1 -1
  31. package/dist/cjs/promises/WalletClient.js +0 -1
  32. package/dist/cjs/promises/WalletClient.js.map +1 -1
  33. package/dist/cjs/rpc.js +3 -5
  34. package/dist/cjs/rpc.js.map +1 -1
  35. package/dist/dts/Attestor.d.ts +21 -6
  36. package/dist/dts/Attestor.d.ts.map +1 -1
  37. package/dist/dts/Domain.d.ts +92 -59
  38. package/dist/dts/Domain.d.ts.map +1 -1
  39. package/dist/dts/Error.d.ts +2 -2
  40. package/dist/dts/Error.d.ts.map +1 -1
  41. package/dist/dts/EvmPublicClient.d.ts +7 -19
  42. package/dist/dts/EvmPublicClient.d.ts.map +1 -1
  43. package/dist/dts/EvmWalletClient.d.ts +7 -23
  44. package/dist/dts/EvmWalletClient.d.ts.map +1 -1
  45. package/dist/dts/Payment.d.ts +71 -69
  46. package/dist/dts/Payment.d.ts.map +1 -1
  47. package/dist/dts/Prover.d.ts +6 -0
  48. package/dist/dts/Prover.d.ts.map +1 -1
  49. package/dist/dts/PublicClient.d.ts +7 -11
  50. package/dist/dts/PublicClient.d.ts.map +1 -1
  51. package/dist/dts/WalletClient.d.ts +10 -4
  52. package/dist/dts/WalletClient.d.ts.map +1 -1
  53. package/dist/dts/constants/ibc-core-registry.d.ts +5 -6
  54. package/dist/dts/constants/ibc-core-registry.d.ts.map +1 -1
  55. package/dist/dts/internal/evm.d.ts +3 -3
  56. package/dist/dts/internal/evm.d.ts.map +1 -1
  57. package/dist/dts/internal/evmPublicClient.d.ts +6 -0
  58. package/dist/dts/internal/evmPublicClient.d.ts.map +1 -0
  59. package/dist/dts/promises/Attestor.d.ts +5 -5
  60. package/dist/dts/promises/EvmPublicClient.d.ts +73 -74
  61. package/dist/dts/promises/EvmPublicClient.d.ts.map +1 -1
  62. package/dist/dts/promises/EvmWalletClient.d.ts +4 -5
  63. package/dist/dts/promises/EvmWalletClient.d.ts.map +1 -1
  64. package/dist/dts/promises/Payment.d.ts +39 -17
  65. package/dist/dts/promises/Payment.d.ts.map +1 -1
  66. package/dist/dts/promises/PublicClient.d.ts +3 -4
  67. package/dist/dts/promises/PublicClient.d.ts.map +1 -1
  68. package/dist/dts/promises/WalletClient.d.ts +77 -34
  69. package/dist/dts/promises/WalletClient.d.ts.map +1 -1
  70. package/dist/dts/rpc.d.ts +31 -0
  71. package/dist/dts/rpc.d.ts.map +1 -1
  72. package/dist/esm/Attestor.js +8 -1
  73. package/dist/esm/Attestor.js.map +1 -1
  74. package/dist/esm/Domain.js +7 -1
  75. package/dist/esm/Domain.js.map +1 -1
  76. package/dist/esm/Error.js +1 -1
  77. package/dist/esm/Error.js.map +1 -1
  78. package/dist/esm/EvmPublicClient.js +4 -275
  79. package/dist/esm/EvmPublicClient.js.map +1 -1
  80. package/dist/esm/EvmWalletClient.js +5 -638
  81. package/dist/esm/EvmWalletClient.js.map +1 -1
  82. package/dist/esm/Payment.js +82 -78
  83. package/dist/esm/Payment.js.map +1 -1
  84. package/dist/esm/Prover.js +1 -1
  85. package/dist/esm/Prover.js.map +1 -1
  86. package/dist/esm/PublicClient.js +2 -2
  87. package/dist/esm/PublicClient.js.map +1 -1
  88. package/dist/esm/Schema.js +8 -4
  89. package/dist/esm/Schema.js.map +1 -1
  90. package/dist/esm/WalletClient.js +2 -2
  91. package/dist/esm/WalletClient.js.map +1 -1
  92. package/dist/esm/constants/ibc-core-registry.js +4 -4
  93. package/dist/esm/constants/ibc-core-registry.js.map +1 -1
  94. package/dist/esm/internal/evmPublicClient.js +253 -0
  95. package/dist/esm/internal/evmPublicClient.js.map +1 -0
  96. package/dist/esm/internal/evmWalletClient.js +691 -1
  97. package/dist/esm/internal/evmWalletClient.js.map +1 -1
  98. package/dist/esm/internal/publicClient.js +0 -2
  99. package/dist/esm/internal/publicClient.js.map +1 -1
  100. package/dist/esm/promises/Payment.js +2 -2
  101. package/dist/esm/promises/Payment.js.map +1 -1
  102. package/dist/esm/promises/PublicClient.js +2 -3
  103. package/dist/esm/promises/PublicClient.js.map +1 -1
  104. package/dist/esm/promises/WalletClient.js +0 -1
  105. package/dist/esm/promises/WalletClient.js.map +1 -1
  106. package/dist/esm/rpc.js +2 -4
  107. package/dist/esm/rpc.js.map +1 -1
  108. package/package.json +7 -3
  109. package/src/Attestor.ts +12 -3
  110. package/src/Domain.ts +30 -9
  111. package/src/Error.ts +1 -0
  112. package/src/EvmPublicClient.ts +9 -488
  113. package/src/EvmWalletClient.ts +21 -973
  114. package/src/Payment.ts +216 -149
  115. package/src/Prover.ts +2 -2
  116. package/src/PublicClient.ts +7 -14
  117. package/src/WalletClient.ts +11 -5
  118. package/src/constants/ibc-core-registry.ts +9 -13
  119. package/src/internal/evmPublicClient.ts +459 -0
  120. package/src/internal/evmWalletClient.ts +1063 -0
  121. package/src/internal/publicClient.ts +0 -3
  122. package/src/promises/Payment.ts +26 -25
  123. package/src/promises/PublicClient.ts +2 -3
  124. package/src/promises/WalletClient.ts +0 -1
  125. package/src/rpc.ts +2 -4
  126. package/unionlabs-payments-0.3.0.tgz +0 -0
@@ -3,4 +3,699 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ exports.resolveUniversalChainId = exports.makeViem = exports.makeBrowser = exports.TypeId = void 0;
7
+ var A = _interopRequireWildcard(require("effect/Array"));
8
+ var Effect = _interopRequireWildcard(require("effect/Effect"));
9
+ var _Function = require("effect/Function");
10
+ var Number = _interopRequireWildcard(require("effect/Number"));
11
+ var O = _interopRequireWildcard(require("effect/Option"));
12
+ var R = _interopRequireWildcard(require("effect/Record"));
13
+ var Ref = _interopRequireWildcard(require("effect/Ref"));
14
+ var ViemChains = _interopRequireWildcard(require("viem/chains"));
15
+ var Abi = _interopRequireWildcard(require("../Abi.js"));
16
+ var ZAssetRegistry = _interopRequireWildcard(require("../constants/z-asset-registry.js"));
17
+ var Domain = _interopRequireWildcard(require("../Domain.js"));
18
+ var Error = _interopRequireWildcard(require("../Error.js"));
19
+ var Client = _interopRequireWildcard(require("../WalletClient.js"));
20
+ var internalEvmPublicClient = _interopRequireWildcard(require("./evmPublicClient.js"));
21
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
22
+ const UniversalChainIdMap = {
23
+ [/*#__PURE__*/Domain.UniversalChainId.make("base.8453")]: ViemChains.base
24
+ };
25
+ /** @internal */
26
+ const resolveUniversalChainId = ucid => (0, _Function.pipe)(UniversalChainIdMap, R.get(ucid), O.match({
27
+ onNone: () => Effect.fail(new Error.SystemError({
28
+ method: "resolveUniversalChainId",
29
+ module: "EvmWalletClient",
30
+ reason: "InvalidData"
31
+ })),
32
+ onSome: Effect.succeed
33
+ }));
34
+ /** @internal */
35
+ exports.resolveUniversalChainId = resolveUniversalChainId;
36
+ const TypeId = exports.TypeId = /*#__PURE__*/Symbol.for("@unionlabs/payments/EvmWalletClient");
37
+ /** @internal */
38
+ const makeViem = wallet => Effect.gen(function* () {
39
+ const Viem = yield* Effect.tryPromise({
40
+ try: () => import("viem").then(x => x),
41
+ catch: cause => new Error.SystemError({
42
+ reason: "DynamicImport",
43
+ method: "makeViem",
44
+ module: "EvmWalletClient",
45
+ cause,
46
+ description: "could not import viem"
47
+ })
48
+ });
49
+ const ViemActions = yield* Effect.tryPromise({
50
+ try: () => import("viem/actions").then(x => x),
51
+ catch: cause => new Error.SystemError({
52
+ reason: "DynamicImport",
53
+ method: "makeViemActions",
54
+ module: "EvmWalletClient",
55
+ cause,
56
+ description: "could not import viem/actions"
57
+ })
58
+ });
59
+ const publicClient = yield* (0, _Function.pipe)(Effect.try({
60
+ try: () => Viem.createPublicClient({
61
+ chain: wallet.chain,
62
+ transport: Viem.custom(wallet)
63
+ }),
64
+ catch: cause => new Error.SystemError({
65
+ reason: "DynamicImport",
66
+ method: "make",
67
+ module: "EvmWalletClient",
68
+ cause,
69
+ description: "could derive public client from wallet client"
70
+ })
71
+ }), Effect.flatMap(internalEvmPublicClient.makeViem));
72
+ // Use "latest" to avoid stale pending txs in mempool
73
+ const transactionCount = yield* (0, _Function.pipe)(Effect.tryPromise({
74
+ try: () => ViemActions.getTransactionCount(wallet, {
75
+ address: wallet.account?.address,
76
+ blockTag: "latest"
77
+ }),
78
+ catch: cause => new Error.SystemError({
79
+ reason: "InvalidData",
80
+ method: "encodeFunctionData",
81
+ module: "EvmWalletClient",
82
+ cause
83
+ })
84
+ }), Effect.flatMap(Ref.make));
85
+ const encodeFunctionData = Effect.fn("encodeFunctionData")(parameters => Effect.try({
86
+ try: () => Viem.encodeFunctionData(parameters),
87
+ catch: cause => new Error.SystemError({
88
+ reason: "InvalidData",
89
+ method: "encodeFunctionData",
90
+ module: "EvmWalletClient",
91
+ cause
92
+ })
93
+ }));
94
+ const validateFunctionData = Effect.fn("validateFunctionData")(parameters => (0, _Function.pipe)(Effect.try({
95
+ try: () => Viem.encodeFunctionData(parameters),
96
+ catch: cause => new Error.SystemError({
97
+ reason: "InvalidData",
98
+ method: "validateFunctionData",
99
+ module: "EvmWalletClient",
100
+ cause
101
+ })
102
+ }), Effect.andThen(() => ({
103
+ ...parameters,
104
+ args: parameters.args ?? [],
105
+ functionName: parameters.functionName
106
+ }))));
107
+ const writeContract = Effect.fn("writeContract")(params => (0, _Function.pipe)(Effect.tryPromise({
108
+ try: () => wallet.writeContract(params),
109
+ catch: cause => new Error.SystemError({
110
+ method: "writeContract",
111
+ module: "EvmWalletClient",
112
+ reason: "InvalidData",
113
+ cause
114
+ })
115
+ }), Effect.map(hash => Domain.SubmissionResult.SubmissionEvm({
116
+ hash: Domain.TxHash(hash)
117
+ }))));
118
+ const prepareTransactionRequest = Effect.fn("prepareTransactionRequest")(params => (0, _Function.pipe)(Ref.get(transactionCount), Effect.flatMap(nonce => Effect.tryPromise({
119
+ try: () => wallet.prepareTransactionRequest({
120
+ ...params,
121
+ nonce
122
+ }),
123
+ catch: cause => new Error.SystemError({
124
+ method: "prepareTransactionRequest",
125
+ module: "EvmWalletClient",
126
+ reason: "InvalidData",
127
+ cause
128
+ })
129
+ })), Effect.tap(() => Ref.update(transactionCount, Number.increment))));
130
+ const prepareBatchTransactionRequest = Effect.fn("prepareBatchTransactionRequest")(requests => Effect.gen(function* () {
131
+ // Refresh nonce from chain before batch to ensure we're in sync
132
+ const chainNonce = yield* Effect.tryPromise({
133
+ try: () => ViemActions.getTransactionCount(wallet, {
134
+ address: wallet.account?.address,
135
+ blockTag: "latest"
136
+ }),
137
+ catch: cause => new Error.SystemError({
138
+ reason: "InvalidData",
139
+ method: "prepareBatchTransactionRequest",
140
+ module: "EvmWalletClient",
141
+ cause
142
+ })
143
+ });
144
+ yield* Ref.set(transactionCount, chainNonce);
145
+ yield* Effect.log("[prepareBatchTransactionRequest] Synced nonce", {
146
+ chainNonce
147
+ });
148
+ const calls = yield* (0, _Function.pipe)(requests, Effect.forEach(request => (0, _Function.pipe)(encodeFunctionData({
149
+ abi: request.abi,
150
+ args: request.args,
151
+ functionName: request.functionName
152
+ }), Effect.map(data => ({
153
+ to: request.contractAddress,
154
+ data,
155
+ value: undefined
156
+ })))));
157
+ yield* Effect.log({
158
+ calls
159
+ });
160
+ const simulationResult = yield* publicClient.simulateCalls({
161
+ calls: calls.map(call => ({
162
+ to: call.to,
163
+ data: call.data,
164
+ value: call.value
165
+ })),
166
+ account: wallet.account?.address
167
+ });
168
+ yield* Effect.log("[prepareBatchTransactionRequest] Simulation results", {
169
+ results: simulationResult.results
170
+ });
171
+ // Extract gas estimates with 20% buffer for safety
172
+ const gasEstimates = simulationResult.results?.map(r => r?.gasUsed ? BigInt(r.gasUsed) * 120n / 100n : undefined) ?? [];
173
+ yield* Effect.log("[prepareBatchTransactionRequest] Gas estimates", {
174
+ gasEstimates
175
+ });
176
+ // Prepare each transaction with gas
177
+ const prepared = [];
178
+ for (let i = 0; i < calls.length; i++) {
179
+ const call = calls[i];
180
+ const gas = gasEstimates[i];
181
+ const nonce = yield* Ref.get(transactionCount);
182
+ const request = yield* Effect.tryPromise({
183
+ try: () => wallet.prepareTransactionRequest({
184
+ to: call.to,
185
+ data: call.data,
186
+ ...(call.value !== undefined && {
187
+ value: call.value
188
+ }),
189
+ ...(gas !== undefined && {
190
+ gas
191
+ }),
192
+ nonce,
193
+ chain: wallet.chain
194
+ }),
195
+ catch: cause => new Error.SystemError({
196
+ method: "prepareBatchTransactionRequest",
197
+ module: "EvmWalletClient",
198
+ reason: "InvalidData",
199
+ cause
200
+ })
201
+ });
202
+ yield* Ref.update(transactionCount, Number.increment);
203
+ prepared.push(request);
204
+ }
205
+ return prepared;
206
+ }));
207
+ const signTransaction = Effect.fn("signTransaction")(params => Effect.tryPromise({
208
+ try: () => wallet.signTransaction(params),
209
+ catch: cause => new Error.SystemError({
210
+ method: "signTransaction",
211
+ module: "EvmWalletClient",
212
+ reason: "InvalidData",
213
+ cause
214
+ })
215
+ }));
216
+ const sendRawTransaction = Effect.fn("sendRawTransaction")(params => Effect.tryPromise({
217
+ try: () => wallet.sendRawTransaction(params),
218
+ catch: cause => new Error.SystemError({
219
+ method: "sendRawTransaction",
220
+ module: "EvmWalletClient",
221
+ reason: "InvalidData",
222
+ cause
223
+ })
224
+ }));
225
+ const sign = Effect.fn("sign")(function* (request) {
226
+ // const chain = yield* resolveUniversalChainId(request.universalChainId);
227
+ const requests = yield* (0, _Function.pipe)(request, A.ensure, Effect.forEach(n => (0, _Function.pipe)(n, Effect.liftPredicate(Domain.PreparedRequest.$is("PreparedEvm"), x => new Error.SystemError({
228
+ method: "sign",
229
+ module: "EvmWalletClient",
230
+ reason: "InvalidData"
231
+ })))));
232
+ return yield* (0, _Function.pipe)(requests, prepareBatchTransactionRequest, Effect.flatMap(Effect.forEach(value => signTransaction({
233
+ ...value,
234
+ account: wallet.account,
235
+ chain: wallet.chain
236
+ }))),
237
+ // Effect.tap((success) => Effect.log({ success })),
238
+ Effect.map(A.map(value => Domain.SignedRequest.SignedEvm({
239
+ value
240
+ }))));
241
+ });
242
+ const submit = Effect.fn("submit")(request => (0, _Function.pipe)(request, Effect.liftPredicate(Domain.SignedRequest.$is("SignedEvm"), cause => new Error.SystemError({
243
+ method: "submit",
244
+ module: "EvmWalletClient",
245
+ reason: "InvalidData",
246
+ cause
247
+ })), Effect.map(x => x.value), Effect.flatMap(serializedTransaction => sendRawTransaction({
248
+ serializedTransaction
249
+ })), Effect.map(hash => Domain.SubmissionResult.SubmissionEvm({
250
+ hash: Domain.TxHash(hash)
251
+ }))));
252
+ const signAndSubmit = Effect.fn("signAndSubmit")(function* (request) {
253
+ const _request = yield* Effect.liftPredicate(request, Domain.PreparedRequest.$is("PreparedEvm"), cause => new Error.SystemError({
254
+ method: "signAndSubmit",
255
+ module: "EvmWalletClient",
256
+ reason: "InvalidData",
257
+ cause
258
+ }));
259
+ const data = yield* encodeFunctionData({
260
+ abi: _request.abi,
261
+ args: _request.args,
262
+ functionName: _request.functionName
263
+ });
264
+ const prepared = yield* prepareTransactionRequest({
265
+ to: _request.contractAddress,
266
+ data,
267
+ chain: wallet.chain
268
+ });
269
+ return yield* (0, _Function.pipe)(Effect.tryPromise({
270
+ try: () => ViemActions.sendTransaction(wallet, {
271
+ to: prepared.to,
272
+ data: prepared.data,
273
+ value: prepared.value,
274
+ gas: prepared.gas,
275
+ nonce: prepared.nonce,
276
+ account: wallet.account,
277
+ chain: wallet.chain
278
+ }),
279
+ catch: cause => new Error.SystemError({
280
+ method: "signAndSubmit",
281
+ module: "EvmWalletClient",
282
+ reason: "InvalidData",
283
+ cause
284
+ })
285
+ }), Effect.map(hash => Domain.SubmissionResult.SubmissionEvm({
286
+ hash: Domain.TxHash(hash)
287
+ })));
288
+ });
289
+ // TODO: check if required
290
+ const approveZAssetToSpendErc20 = Effect.fn("approveZAssetToSpendErc20")(function* (args) {
291
+ return yield* (0, _Function.pipe)(
292
+ // XXX: fix hardcoded chainid
293
+ ZAssetRegistry.getZAsset(8453n, args.srcErc20Address), Effect.mapError(cause => new Error.SystemError({
294
+ method: "approveZAssetToSpendErc20",
295
+ module: "EvmWalletClient",
296
+ reason: "InvalidData",
297
+ cause
298
+ })), Effect.flatMap(zAsset => validateFunctionData({
299
+ abi: Abi.ERC20_ABI,
300
+ functionName: "approve",
301
+ args: [zAsset, args.amount]
302
+ })), Effect.map(request => Domain.PreparedRequest.PreparedEvm({
303
+ abi: request.abi,
304
+ args: request.args ?? [],
305
+ contractAddress: args.srcErc20Address,
306
+ functionName: request.functionName || "",
307
+ universalChainId: args.universalChainId,
308
+ kind: "Erc20.Approve"
309
+ })));
310
+ });
311
+ // TODO: check if required
312
+ const updateLoopbackClient = Effect.fn("updateLoopbackClient")(function* ({
313
+ clientId,
314
+ height,
315
+ ibcHandlerAddress,
316
+ universalChainId
317
+ }) {
318
+ // const publicClient = Viem.createPublicClient({
319
+ // transport: Viem.http(wallet.transport.rpcUrl),
320
+ // });
321
+ const publicClient = wallet.extend(Viem.publicActions);
322
+ const blockNumber = height;
323
+ const block = yield* Effect.tryPromise({
324
+ try: () => publicClient.getBlock({
325
+ blockNumber
326
+ }),
327
+ catch: cause => new Error.SystemError({
328
+ module: "EvmWalletClient",
329
+ method: "updateLoopbackClient",
330
+ reason: "InvalidData",
331
+ description: "Cannot getBlockNumber",
332
+ cause
333
+ })
334
+ });
335
+ // if (!block.number) {
336
+ // throw new Error("Block number is null");
337
+ // }
338
+ // Helper to convert bigint/number to minimal RLP hex encoding
339
+ const toRlpHex = value => {
340
+ if (value === undefined || value === null || value === 0n || value === 0) {
341
+ return "0x";
342
+ }
343
+ let hex = typeof value === "bigint" ? value.toString(16) : value.toString(16);
344
+ if (hex.length % 2 !== 0) {
345
+ hex = "0" + hex;
346
+ }
347
+ return `0x${hex}`;
348
+ };
349
+ // Build header fields in order (pre-merge + post-merge fields)
350
+ const headerFields = [block.parentHash, block.sha3Uncles, block.miner, block.stateRoot, block.transactionsRoot, block.receiptsRoot, block.logsBloom ?? "0x" + "00".repeat(256), toRlpHex(block.difficulty), toRlpHex(block.number), toRlpHex(block.gasLimit), toRlpHex(block.gasUsed), toRlpHex(block.timestamp), block.extraData, block.mixHash ?? "0x0000000000000000000000000000000000000000000000000000000000000000", block.nonce ?? "0x0000000000000000"];
351
+ // Post-merge fields
352
+ if (block.baseFeePerGas !== undefined && block.baseFeePerGas !== null) {
353
+ headerFields.push(toRlpHex(block.baseFeePerGas));
354
+ }
355
+ if (block.withdrawalsRoot) {
356
+ headerFields.push(block.withdrawalsRoot);
357
+ }
358
+ if (block.blobGasUsed !== undefined && block.blobGasUsed !== null) {
359
+ headerFields.push(toRlpHex(block.blobGasUsed));
360
+ }
361
+ if (block.excessBlobGas !== undefined && block.excessBlobGas !== null) {
362
+ headerFields.push(toRlpHex(block.excessBlobGas));
363
+ }
364
+ if (block.parentBeaconBlockRoot) {
365
+ headerFields.push(block.parentBeaconBlockRoot);
366
+ }
367
+ const blockAny = block;
368
+ if (blockAny.requestsHash) {
369
+ headerFields.push(blockAny.requestsHash);
370
+ }
371
+ const rlpEncoded = Viem.toRlp(headerFields);
372
+ // Verify the encoding produces the correct block hash
373
+ const computedHash = Viem.keccak256(rlpEncoded);
374
+ if (computedHash !== block.hash) {
375
+ return yield* new Error.SystemError({
376
+ module: "EvmWalletClient",
377
+ method: "updateLooopbackClient",
378
+ reason: "InvalidData",
379
+ description: `RLP encoding mismatch: computed hash ${computedHash} does not match block hash ${block.hash}`
380
+ });
381
+ }
382
+ // Encode the Header struct: (uint64 height, bytes encodedHeader)
383
+ const clientMessage = Viem.encodeAbiParameters([{
384
+ type: "uint64",
385
+ name: "height"
386
+ }, {
387
+ type: "bytes",
388
+ name: "encodedHeader"
389
+ }], [block.number, rlpEncoded]);
390
+ const LIGHTCLIENT_ABI = [{
391
+ inputs: [{
392
+ name: "caller",
393
+ type: "address"
394
+ }, {
395
+ name: "clientId",
396
+ type: "uint32"
397
+ }, {
398
+ name: "clientMessage",
399
+ type: "bytes"
400
+ }, {
401
+ name: "relayer",
402
+ type: "address"
403
+ }],
404
+ name: "updateClient",
405
+ outputs: [],
406
+ stateMutability: "nonpayable",
407
+ type: "function"
408
+ }];
409
+ // Wait for the next block so the fetched block's hash is verifiable on-chain
410
+ let currentBlock = yield* Effect.tryPromise({
411
+ try: () => publicClient.getBlockNumber(),
412
+ catch: cause => new Error.SystemError({
413
+ module: "EvmWalletClient",
414
+ method: "updateLoopbackClient",
415
+ reason: "InvalidData",
416
+ description: "Cannot getBlockNumber",
417
+ cause
418
+ })
419
+ });
420
+ while (currentBlock <= blockNumber) {
421
+ yield* Effect.sleep("1 second");
422
+ currentBlock = yield* Effect.tryPromise({
423
+ try: () => publicClient.getBlockNumber(),
424
+ catch: cause => new Error.SystemError({
425
+ module: "EvmWalletClient",
426
+ method: "updateLoopbackClient",
427
+ reason: "InvalidData",
428
+ description: "Cannot getBlockNumber",
429
+ cause
430
+ })
431
+ });
432
+ }
433
+ const loopbackClient = yield* (0, _Function.pipe)(Effect.tryPromise({
434
+ try: () => publicClient.readContract({
435
+ address: ibcHandlerAddress,
436
+ abi: Abi.IBC_STORE_ABI,
437
+ functionName: "getClient",
438
+ args: [clientId]
439
+ }),
440
+ catch: cause => new Error.SystemError({
441
+ module: "EvmWalletClient",
442
+ method: "updateLoopbackClient",
443
+ reason: "InvalidData",
444
+ description: "cannot get client given ibc handler address",
445
+ cause
446
+ })
447
+ }), Effect.map(Domain.Erc20Address));
448
+ return yield* (0, _Function.pipe)(validateFunctionData({
449
+ abi: LIGHTCLIENT_ABI,
450
+ functionName: "updateClient",
451
+ args: [wallet.account.address, clientId, clientMessage, wallet.account.address]
452
+ }), Effect.map(data => Domain.PreparedRequest.PreparedEvm({
453
+ ...data,
454
+ contractAddress: loopbackClient,
455
+ universalChainId,
456
+ kind: "LoopbackClient.Update"
457
+ })));
458
+ });
459
+ const depositUnderlyingZAsset = Effect.fn("depositUnderlyingZAsset")(function* (args) {
460
+ const zAssetAddr = yield* ZAssetRegistry.getZAsset(8453n, args.srcErc20Address).pipe(Effect.mapError(cause => new Error.SystemError({
461
+ method: "depositUnderlyingZAsset",
462
+ module: "EvmWalletClient",
463
+ reason: "InvalidData",
464
+ cause
465
+ })));
466
+ return yield* (0, _Function.pipe)(validateFunctionData({
467
+ abi: Abi.ZASSET_ABI,
468
+ functionName: "deposit",
469
+ args: [args.amount]
470
+ }),
471
+ // Effect.map((data) =>
472
+ // prepareTransactionRequest({
473
+ // to: zAssetAddr,
474
+ // data,
475
+ // chain: wallet.chain,
476
+ // }),
477
+ // ),
478
+ Effect.map(data => Domain.PreparedRequest.PreparedEvm({
479
+ ...data,
480
+ contractAddress: Domain.Erc20Address(zAssetAddr),
481
+ universalChainId: args.universalChainId,
482
+ kind: "Erc20.Wrap"
483
+ })));
484
+ });
485
+ const transferZAsset = Effect.fn("transferZAsset")(function* (args) {
486
+ const zAssetAddr = yield* ZAssetRegistry.getZAsset(8453n, args.srcErc20Address).pipe(Effect.mapError(cause => new Error.SystemError({
487
+ method: "transferZAsset",
488
+ module: "EvmWalletClient",
489
+ reason: "InvalidData",
490
+ cause
491
+ })));
492
+ return yield* (0, _Function.pipe)(validateFunctionData({
493
+ abi: Abi.ZASSET_ABI,
494
+ functionName: "transfer",
495
+ args: [args.depositAddress, args.amount]
496
+ }),
497
+ // Effect.flatMap((data) =>
498
+ // prepareTransactionRequest({
499
+ // to: zAssetAddr,
500
+ // data,
501
+ // chain: wallet.chain,
502
+ // }),
503
+ // ),
504
+ Effect.map(data => Domain.PreparedRequest.PreparedEvm({
505
+ ...data,
506
+ contractAddress: Domain.Erc20Address(zAssetAddr),
507
+ universalChainId: args.universalChainId,
508
+ kind: "ZAsset.Transfer"
509
+ })));
510
+ });
511
+ const prepareDeposit = Effect.fn("prepareDeposit")(function* (args) {
512
+ const zAssetAddress = ZAssetRegistry.Z_ASSET_REGISTRY[`${args.sourceChainId}`][args.srcErc20Address];
513
+ if (!zAssetAddress) {
514
+ return yield* new Error.SystemError({
515
+ method: "deposit",
516
+ module: "PaymentClient",
517
+ reason: "InvalidData",
518
+ description: `No zAsset found for ${args.srcErc20Address} on chain ${args.sourceChainId}`
519
+ });
520
+ }
521
+ const [approval, deposit, transfer] = yield* Effect.all([(0, _Function.pipe)(validateFunctionData({
522
+ abi: Abi.ERC20_ABI,
523
+ functionName: "approve",
524
+ args: [zAssetAddress, args.amount]
525
+ }), Effect.map(data => Domain.PreparedRequest.PreparedEvm({
526
+ ...data,
527
+ contractAddress: args.srcErc20Address,
528
+ universalChainId: args.universalChainId,
529
+ kind: "Erc20.Approve"
530
+ }))), (0, _Function.pipe)(validateFunctionData({
531
+ abi: Abi.ZASSET_ABI,
532
+ functionName: "deposit",
533
+ args: [args.amount]
534
+ }), Effect.map(data => Domain.PreparedRequest.PreparedEvm({
535
+ ...data,
536
+ contractAddress: Domain.Erc20Address(zAssetAddress),
537
+ universalChainId: args.universalChainId,
538
+ kind: "Erc20.Wrap"
539
+ }))), (0, _Function.pipe)(validateFunctionData({
540
+ abi: Abi.ZASSET_ABI,
541
+ functionName: "transfer",
542
+ args: [args.depositAddress, args.amount]
543
+ }), Effect.map(data => Domain.PreparedRequest.PreparedEvm({
544
+ ...data,
545
+ contractAddress: Domain.Erc20Address(zAssetAddress),
546
+ universalChainId: args.universalChainId,
547
+ kind: "ZAsset.Transfer"
548
+ })))], {
549
+ concurrency: "unbounded"
550
+ });
551
+ yield* Effect.log("[deposit]", {
552
+ approval,
553
+ deposit,
554
+ transfer
555
+ });
556
+ return [approval, deposit, transfer];
557
+ });
558
+ const prepareRedemption = Effect.fn("prepareRedemption")(function* (args) {
559
+ const zAssetAddr = yield* ZAssetRegistry.getZAsset(8453n, args.dstErc20Address).pipe(Effect.mapError(cause => new Error.SystemError({
560
+ method: "transferZAsset",
561
+ module: "EvmWalletClient",
562
+ reason: "InvalidData",
563
+ cause
564
+ })));
565
+ return yield* (0, _Function.pipe)(validateFunctionData({
566
+ abi: Abi.ZASSET_ABI,
567
+ functionName: "redeem",
568
+ args: [args.proof, args.commitments, args.commitmentPok, args.lightClients, args.nullifier, args.value, args.beneficiary, args.attestedMessage, args.signature, args.unwrap ?? true]
569
+ }),
570
+ // Effect.flatMap((data) =>
571
+ // prepareTransactionRequest({
572
+ // to: zAssetAddr,
573
+ // data,
574
+ // chain: wallet.chain,
575
+ // }),
576
+ // ),
577
+ Effect.map(data => Domain.PreparedRequest.PreparedEvm({
578
+ ...data,
579
+ contractAddress: Domain.Erc20Address(zAssetAddr),
580
+ universalChainId: args.universalChainId,
581
+ kind: "ZAsset.Transfer"
582
+ })));
583
+ });
584
+ return Object.assign(yield* Client.make({
585
+ sign: sign,
586
+ submit,
587
+ approveZAssetToSpendErc20,
588
+ updateLoopbackClient,
589
+ depositUnderlyingZAsset,
590
+ transferZAsset,
591
+ prepareDeposit,
592
+ prepareRedemption,
593
+ signAndSubmit
594
+ }), {
595
+ [TypeId]: TypeId,
596
+ signTransaction,
597
+ sendRawTransaction,
598
+ writeContract,
599
+ prepareBatchTransactionRequest
600
+ });
601
+ });
602
+ /** @internal */
603
+ exports.makeViem = makeViem;
604
+ const makeBrowser = exports.makeBrowser = /*#__PURE__*/Effect.fn(function* (options) {
605
+ const Mipd = yield* Effect.tryPromise({
606
+ try: () => import("mipd").then(x => x),
607
+ catch: cause => new Error.SystemError({
608
+ reason: "DynamicImport",
609
+ method: "makeBrowser",
610
+ module: "EvmWalletClient",
611
+ cause,
612
+ description: "could not import mipd"
613
+ })
614
+ });
615
+ const store = Mipd.createStore();
616
+ yield* Effect.log({
617
+ store
618
+ });
619
+ const providers = store.getProviders();
620
+ yield* Effect.log({
621
+ providers
622
+ });
623
+ const selected = yield* (0, _Function.pipe)(A.findFirst(providers, options.providerPredicate), Effect.mapError(cause => new Error.SystemError({
624
+ reason: "DynamicImport",
625
+ method: "makeBrowser",
626
+ module: "EvmWalletClient",
627
+ cause,
628
+ description: "could not find provider"
629
+ })));
630
+ yield* Effect.log({
631
+ selected
632
+ });
633
+ const account = yield* (0, _Function.pipe)(Effect.tryPromise({
634
+ try: () => selected.provider.request({
635
+ method: "eth_requestAccounts"
636
+ }),
637
+ catch: cause => new Error.SystemError({
638
+ reason: "DynamicImport",
639
+ method: "makeBrowser",
640
+ module: "EvmWalletClient",
641
+ cause,
642
+ description: "could not request accounts"
643
+ })
644
+ }), Effect.flatMap(A.findFirst(options.accountPredicate)), Effect.catchTag("NoSuchElementException", cause => new Error.SystemError({
645
+ reason: "DynamicImport",
646
+ method: "makeBrowser",
647
+ module: "EvmWalletClient",
648
+ cause,
649
+ description: "could not match account by predicate"
650
+ })));
651
+ const Viem = yield* Effect.tryPromise({
652
+ try: () => import("viem").then(x => x),
653
+ catch: cause => new Error.SystemError({
654
+ reason: "DynamicImport",
655
+ method: "makeViem",
656
+ module: "EvmWalletClient",
657
+ cause,
658
+ description: "could not import viem"
659
+ })
660
+ });
661
+ const ViemChains = yield* Effect.tryPromise({
662
+ try: () => import("viem/chains").then(x => x),
663
+ catch: cause => new Error.SystemError({
664
+ reason: "DynamicImport",
665
+ method: "makeViem",
666
+ module: "EvmWalletClient",
667
+ cause,
668
+ description: "could not import viem/chains"
669
+ })
670
+ });
671
+ const wallet = yield* Effect.try({
672
+ try: () => Viem.createWalletClient({
673
+ account: account,
674
+ chain: ViemChains.base,
675
+ transport: Viem.custom(selected.provider)
676
+ }),
677
+ catch: cause => new Error.SystemError({
678
+ reason: "DynamicImport",
679
+ method: "makeViem",
680
+ module: "EvmWalletClient",
681
+ cause,
682
+ description: "could not import viem/chains"
683
+ })
684
+ });
685
+ return yield* makeViem(wallet);
686
+ });
687
+ // import type * as ThirdwebAdaptersViem from "thirdweb/adapters/viem"
688
+ // export const makeThirdweb = Effect.fn(function* (...options: Parameters<typeof ThirdwebAdaptersViem['viemAdapter']['wallet']['toViem']>) {
689
+ // const { viemAdapter } = yield* Effect.tryPromise({
690
+ // try: () => import("thirdweb/adapters/viem"),
691
+ // catch: (cause) => new Error.SystemError({
692
+ // method: "makeThirdweb",
693
+ // module: "EvmWalletClient",
694
+ // reason: "DynamicImport",
695
+ // cause,
696
+ // })
697
+ // })
698
+ // const wallet = viemAdapter.wallet.toViem(...options)
699
+ // return layerFromViem(wallet as Viem.WalletClient)
700
+ // })
6
701
  //# sourceMappingURL=evmWalletClient.js.map