@matterlabs/zksync-js 0.0.20 → 0.0.22

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 (72) hide show
  1. package/dist/adapters/ethers/client.cjs +31 -1
  2. package/dist/adapters/ethers/client.cjs.map +1 -1
  3. package/dist/adapters/ethers/client.d.ts +11 -0
  4. package/dist/adapters/ethers/client.js +6 -5
  5. package/dist/adapters/ethers/index.cjs +1057 -290
  6. package/dist/adapters/ethers/index.cjs.map +1 -1
  7. package/dist/adapters/ethers/index.d.ts +2 -1
  8. package/dist/adapters/ethers/index.js +10 -8
  9. package/dist/adapters/ethers/resources/withdrawals/context.d.ts +12 -1
  10. package/dist/adapters/ethers/resources/withdrawals/index.d.ts +17 -1
  11. package/dist/adapters/ethers/resources/withdrawals/routes/interop-bundle.d.ts +2 -0
  12. package/dist/adapters/ethers/resources/withdrawals/services/finalization.d.ts +35 -17
  13. package/dist/adapters/ethers/resources/withdrawals/services/protocol.d.ts +11 -0
  14. package/dist/adapters/ethers/sdk.cjs +1010 -274
  15. package/dist/adapters/ethers/sdk.cjs.map +1 -1
  16. package/dist/adapters/ethers/sdk.d.ts +3 -1
  17. package/dist/adapters/ethers/sdk.js +8 -7
  18. package/dist/adapters/viem/client.cjs +44 -0
  19. package/dist/adapters/viem/client.cjs.map +1 -1
  20. package/dist/adapters/viem/client.d.ts +11 -0
  21. package/dist/adapters/viem/client.js +6 -5
  22. package/dist/adapters/viem/index.cjs +1094 -296
  23. package/dist/adapters/viem/index.cjs.map +1 -1
  24. package/dist/adapters/viem/index.d.ts +2 -1
  25. package/dist/adapters/viem/index.js +10 -8
  26. package/dist/adapters/viem/resources/withdrawals/context.d.ts +12 -1
  27. package/dist/adapters/viem/resources/withdrawals/index.d.ts +17 -1
  28. package/dist/adapters/viem/resources/withdrawals/routes/interop-bundle.d.ts +2 -0
  29. package/dist/adapters/viem/resources/withdrawals/services/finalization.d.ts +36 -18
  30. package/dist/adapters/viem/resources/withdrawals/services/protocol.d.ts +11 -0
  31. package/dist/adapters/viem/sdk.cjs +1048 -295
  32. package/dist/adapters/viem/sdk.cjs.map +1 -1
  33. package/dist/adapters/viem/sdk.d.ts +3 -1
  34. package/dist/adapters/viem/sdk.js +8 -7
  35. package/dist/{chunk-SBGBYZJM.js → chunk-2D3FBCZC.js} +2 -2
  36. package/dist/{chunk-3HHUZXSV.js → chunk-32N6TI6K.js} +10 -2
  37. package/dist/{chunk-6LYAENO6.js → chunk-3SPDWWRD.js} +6 -4
  38. package/dist/{chunk-3T5V4HKS.js → chunk-4K4LOCQJ.js} +569 -259
  39. package/dist/{chunk-UEKFQAOS.js → chunk-AMRHBZIY.js} +304 -2
  40. package/dist/{chunk-E2XKJCI5.js → chunk-CP4SQ5PM.js} +537 -242
  41. package/dist/{chunk-NJK325XV.js → chunk-CPNHKNI4.js} +2 -2
  42. package/dist/{chunk-TYYUG5GA.js → chunk-CUBUD4J4.js} +1 -1
  43. package/dist/{chunk-CK5UFAZK.js → chunk-JXBLQQEN.js} +37 -3
  44. package/dist/{chunk-JSBMIT4S.js → chunk-KL6ZCPWJ.js} +1 -1
  45. package/dist/{chunk-MT4X5FEO.js → chunk-NQRYXL3K.js} +3 -1
  46. package/dist/{chunk-24TE2NNJ.js → chunk-PI4PF6WT.js} +24 -4
  47. package/dist/chunk-QUAPG3ZR.js +157 -0
  48. package/dist/chunk-UMPAKZCQ.js +19 -0
  49. package/dist/core/abi.d.ts +1 -0
  50. package/dist/core/constants.cjs +2 -0
  51. package/dist/core/constants.cjs.map +1 -1
  52. package/dist/core/constants.d.ts +9 -0
  53. package/dist/core/constants.js +1 -1
  54. package/dist/core/index.cjs +513 -0
  55. package/dist/core/index.cjs.map +1 -1
  56. package/dist/core/index.d.ts +6 -1
  57. package/dist/core/index.js +6 -4
  58. package/dist/core/internal/abis/IERC7786Attributes.d.ts +10 -0
  59. package/dist/core/internal/abis/IL1NullifierV32.d.ts +221 -0
  60. package/dist/core/resources/interop/attributes/bundle.d.ts +1 -0
  61. package/dist/core/resources/interop/attributes/resource.d.ts +1 -0
  62. package/dist/core/resources/protocol/semver.d.ts +18 -0
  63. package/dist/core/resources/withdrawals/bundle.d.ts +80 -0
  64. package/dist/core/resources/withdrawals/finalization.d.ts +142 -0
  65. package/dist/core/resources/withdrawals/protocol.d.ts +55 -0
  66. package/dist/core/resources/withdrawals/status.d.ts +5 -0
  67. package/dist/core/types/flows/withdrawals.d.ts +32 -2
  68. package/dist/core/utils/events.d.ts +2 -0
  69. package/dist/index.cjs +313 -0
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.js +4 -4
  72. package/package.json +1 -1
@@ -1,9 +1,10 @@
1
- import { createNTVCodec, resolveCreateDepositL1GasLimit, isInteropFinalizationInfo, DEFAULT_POLL_MS, DEFAULT_TIMEOUT_MS, resolveIdsFromWaitable, parseBundleReceiptInfo, buildFinalizationInfo, parseBundleSentFromReceipt, createAttributesResource, pickInteropRoute, ZERO_HASH, toGasOverrides, applyPriorityL2GasLimitBuffer, buildFeeBreakdown, buildIndirectBundle, preflightIndirect, buildDirectBundle, preflightDirect, derivePriorityTxGasBreakdown, quoteL2Gas, quoteL1Gas, derivePriorityBodyGasEstimateCap, quoteL2Gas2, assertProtocolVersion } from './chunk-6LYAENO6.js';
2
- import { findL1MessageSentLog, messengerLogIndex, pickWithdrawRoute } from './chunk-3HHUZXSV.js';
3
- import { createErrorHandlers, toZKsyncError, classifyReadinessFromRevert } from './chunk-SBGBYZJM.js';
4
- import { isHash66, IL1Nullifier_default, OP_WITHDRAWALS, createError, normalizeL1Token, isAddressEq, hexEq, OP_DEPOSITS, IERC20_default, isZKsyncError, isReceiptNotFound, OP_INTEROP, IInteropHandler_default, IInteropRootStorage_default, IInteropCenter_default, sleep, IERC7786Attributes_default, IBridgehub_default, isETH, normalizeAddrEq, L2NativeTokenVault_default, IL2AssetRouter_default, IBaseToken_default, assertNever } from './chunk-UEKFQAOS.js';
5
- import { ETH_ADDRESS, TOPIC_CANONICAL_ASSIGNED, TOPIC_CANONICAL_SUCCESS, L1_MESSENGER_ADDRESS, L2_BASE_TOKEN_ADDRESS, L2_NATIVE_TOKEN_VAULT_ADDRESS, L2_INTEROP_ROOT_STORAGE_ADDRESS, BUFFER, SAFE_L1_BRIDGE_GAS, L2_ASSET_ROUTER_ADDRESS, FORMAL_ETH_ADDRESS } from './chunk-MT4X5FEO.js';
6
- import { keccak256, encodeAbiParameters, toBytes, concat, decodeEventLog, decodeAbiParameters, createWalletClient, custom, encodeFunctionData, createPublicClient, http, encodeEventTopics, numberToHex, zeroAddress, getAddress, toHex } from 'viem';
1
+ import { createNTVCodec, createAttributesResource, resolveCreateDepositL1GasLimit, isInteropFinalizationInfo, DEFAULT_POLL_MS, DEFAULT_TIMEOUT_MS, resolveIdsFromWaitable, parseBundleReceiptInfo, buildFinalizationInfo, parseBundleSentFromReceipt, pickInteropRoute, ZERO_HASH, toGasOverrides, applyPriorityL2GasLimitBuffer, buildFeeBreakdown, buildIndirectBundle, preflightIndirect, buildDirectBundle, preflightDirect, derivePriorityTxGasBreakdown, quoteL2Gas, quoteL1Gas, derivePriorityBodyGasEstimateCap, assertProtocolVersion, quoteL2Gas2 } from './chunk-3SPDWWRD.js';
2
+ import { detectWithdrawalProtocol, buildWithdrawalFinalization, parseBundleHashFromLogs, classifyWithdrawalOutcome, phaseFromReadiness, buildWithdrawalBundle } from './chunk-QUAPG3ZR.js';
3
+ import { findL1MessageSentLog, messengerLogIndex, l1MessageSentSender, pickWithdrawRoute } from './chunk-32N6TI6K.js';
4
+ import { createErrorHandlers, toZKsyncError, classifyReadinessFromRevert } from './chunk-2D3FBCZC.js';
5
+ import { IERC7786Attributes_default, isHash66, IL1Nullifier_default, IInteropHandler_default, OP_WITHDRAWALS, createError, normalizeL1Token, isAddressEq, hexEq, OP_DEPOSITS, IERC20_default, isZKsyncError, isReceiptNotFound, IL1NullifierV32_default, OP_INTEROP, IInteropRootStorage_default, IInteropCenter_default, sleep, IBridgehub_default, isETH, normalizeAddrEq, IL2AssetRouter_default, L2NativeTokenVault_default, IBaseToken_default, assertNever } from './chunk-AMRHBZIY.js';
6
+ import { ETH_ADDRESS, TOPIC_CANONICAL_ASSIGNED, TOPIC_CANONICAL_SUCCESS, L2_BASE_TOKEN_ADDRESS, L2_NATIVE_TOKEN_VAULT_ADDRESS, L1_MESSENGER_ADDRESS, L2_INTEROP_ROOT_STORAGE_ADDRESS, BUFFER, SAFE_L1_BRIDGE_GAS, L2_ASSET_ROUTER_ADDRESS, FORMAL_ETH_ADDRESS } from './chunk-NQRYXL3K.js';
7
+ import { keccak256, encodeAbiParameters, toBytes, encodeFunctionData, concat, decodeEventLog, createWalletClient, custom, decodeAbiParameters, createPublicClient, http, encodeEventTopics, numberToHex, zeroAddress, getAddress, toHex } from 'viem';
7
8
 
8
9
  // src/adapters/viem/resources/deposits/context.ts
9
10
  async function commonCtx(p, client, tokens, contracts) {
@@ -1950,7 +1951,7 @@ function createDepositsResource(client, tokens, contracts) {
1950
1951
  }
1951
1952
 
1952
1953
  // src/adapters/viem/resources/withdrawals/context.ts
1953
- async function commonCtx2(p, client, tokens, contracts) {
1954
+ async function commonCtx2(p, client, tokens, contracts, protocol) {
1954
1955
  const sender = client.account.address;
1955
1956
  const {
1956
1957
  bridgehub,
@@ -1958,9 +1959,11 @@ async function commonCtx2(p, client, tokens, contracts) {
1958
1959
  l1Nullifier,
1959
1960
  l2AssetRouter,
1960
1961
  l2NativeTokenVault,
1961
- l2BaseTokenSystem
1962
+ l2BaseTokenSystem,
1963
+ interopCenter
1962
1964
  } = await contracts.addresses();
1963
1965
  const chainIdL2 = BigInt(await client.l2.getChainId());
1966
+ const l1ChainId = BigInt(await client.l1.getChainId());
1964
1967
  const resolvedToken = await tokens.resolve(p.token, { chain: "l2" });
1965
1968
  const baseTokenAssetId = resolvedToken.baseTokenAssetId;
1966
1969
  const baseTokenL1 = await tokens.l1TokenFromAssetId(baseTokenAssetId);
@@ -1982,6 +1985,9 @@ async function commonCtx2(p, client, tokens, contracts) {
1982
1985
  l2AssetRouter,
1983
1986
  l2NativeTokenVault,
1984
1987
  l2BaseTokenSystem,
1988
+ interopCenter,
1989
+ protocol,
1990
+ l1ChainId,
1985
1991
  baseIsEth,
1986
1992
  gasOverrides: p.l2TxOverrides ? toGasOverrides(p.l2TxOverrides) : void 0
1987
1993
  };
@@ -2230,7 +2236,261 @@ function routeErc20NonBase2() {
2230
2236
  }
2231
2237
  };
2232
2238
  }
2239
+ var PREFIX_EVM_CHAIN = toBytes("0x00010000");
2240
+ var PREFIX_EVM_ADDRESS = toBytes("0x000100000014");
2241
+ function formatInteropEvmChain(chainId) {
2242
+ const chainRef = toBytes(toHex(chainId));
2243
+ const chainRefLength = toBytes(toHex(chainRef.length, { size: 1 }));
2244
+ const payload = concat([PREFIX_EVM_CHAIN, chainRefLength, chainRef, new Uint8Array([0])]);
2245
+ return toHex(payload);
2246
+ }
2247
+ function formatInteropEvmAddress(address) {
2248
+ const normalized = getAddress(address);
2249
+ const addrBytes = toBytes(normalized);
2250
+ const payload = concat([PREFIX_EVM_ADDRESS, addrBytes]);
2251
+ return toHex(payload);
2252
+ }
2253
+ var interopCodec = {
2254
+ formatChain: formatInteropEvmChain,
2255
+ formatAddress: formatInteropEvmAddress
2256
+ };
2257
+ function getInteropAttributes(params, ctx) {
2258
+ const bundleAttributes = [];
2259
+ if (params.execution?.only) {
2260
+ bundleAttributes.push(ctx.attributes.bundle.executionAddress(params.execution.only));
2261
+ }
2262
+ if (params.unbundling?.by) {
2263
+ bundleAttributes.push(ctx.attributes.bundle.unbundlerAddress(params.unbundling.by));
2264
+ }
2265
+ bundleAttributes.push(ctx.attributes.bundle.useFixedFee(params.fee?.useFixed ?? false));
2266
+ const callAttributes = params.actions.map((action) => {
2267
+ switch (action.type) {
2268
+ case "sendNative": {
2269
+ const baseMatches = ctx.baseTokens.src.toLowerCase() === ctx.baseTokens.dst.toLowerCase();
2270
+ if (baseMatches) {
2271
+ return [ctx.attributes.call.interopCallValue(action.amount)];
2272
+ }
2273
+ return [ctx.attributes.call.indirectCall(action.amount)];
2274
+ }
2275
+ case "call":
2276
+ if (action.value && action.value > 0n) {
2277
+ return [ctx.attributes.call.interopCallValue(action.value)];
2278
+ }
2279
+ return [];
2280
+ case "sendErc20":
2281
+ return [ctx.attributes.call.indirectCall(0n)];
2282
+ default:
2283
+ assertNever(action);
2284
+ }
2285
+ });
2286
+ return { bundleAttributes, callAttributes };
2287
+ }
2288
+ function createViemAttributesResource() {
2289
+ const encode = (fn, args) => encodeFunctionData({
2290
+ abi: IERC7786Attributes_default,
2291
+ functionName: fn,
2292
+ args
2293
+ });
2294
+ return createAttributesResource({ encode });
2295
+ }
2296
+
2297
+ // src/adapters/viem/resources/withdrawals/routes/interop-bundle.ts
2233
2298
  var { wrapAs: wrapAs9 } = createErrorHandlers("withdrawals");
2299
+ var attributes = createViemAttributesResource();
2300
+ function saltFor(sender, nonce) {
2301
+ return keccak256(
2302
+ encodeAbiParameters(
2303
+ [
2304
+ { type: "address", name: "sender" },
2305
+ { type: "uint256", name: "nonce" }
2306
+ ],
2307
+ [sender, BigInt(nonce)]
2308
+ )
2309
+ );
2310
+ }
2311
+ function routeInteropBundle() {
2312
+ return {
2313
+ async build(p, ctx) {
2314
+ const steps = [];
2315
+ const approvals = [];
2316
+ const isBaseToken = ctx.route === "base";
2317
+ const l1Receiver = p.to ?? ctx.sender;
2318
+ let assetId;
2319
+ let allowanceSufficient = true;
2320
+ if (isBaseToken) {
2321
+ assetId = ctx.baseTokenAssetId;
2322
+ } else {
2323
+ assetId = (await wrapAs9(
2324
+ "CONTRACT",
2325
+ OP_WITHDRAWALS.erc20.ensureRegistered,
2326
+ () => ctx.client.l2.simulateContract({
2327
+ address: ctx.l2NativeTokenVault,
2328
+ abi: L2NativeTokenVault_default,
2329
+ functionName: "ensureTokenIsRegistered",
2330
+ args: [p.token],
2331
+ account: ctx.client.account
2332
+ }),
2333
+ {
2334
+ ctx: { where: "L2NativeTokenVault.ensureTokenIsRegistered", token: p.token },
2335
+ message: "Failed to ensure token is registered in L2NativeTokenVault."
2336
+ }
2337
+ )).result;
2338
+ const current = await wrapAs9(
2339
+ "CONTRACT",
2340
+ OP_WITHDRAWALS.erc20.allowance,
2341
+ () => ctx.client.l2.readContract({
2342
+ address: p.token,
2343
+ abi: IERC20_default,
2344
+ functionName: "allowance",
2345
+ args: [ctx.sender, ctx.l2NativeTokenVault],
2346
+ account: ctx.client.account
2347
+ }),
2348
+ {
2349
+ ctx: {
2350
+ where: "erc20.allowance",
2351
+ chain: "L2",
2352
+ token: p.token,
2353
+ spender: ctx.l2NativeTokenVault
2354
+ },
2355
+ message: "Failed to read L2 ERC-20 allowance."
2356
+ }
2357
+ );
2358
+ allowanceSufficient = current >= p.amount;
2359
+ if (!allowanceSufficient) {
2360
+ approvals.push({ token: p.token, spender: ctx.l2NativeTokenVault, amount: p.amount });
2361
+ const approveTxCandidate = {
2362
+ to: p.token,
2363
+ data: encodeFunctionData({
2364
+ abi: IERC20_default,
2365
+ functionName: "approve",
2366
+ args: [ctx.l2NativeTokenVault, p.amount]
2367
+ }),
2368
+ value: 0n,
2369
+ from: ctx.sender
2370
+ };
2371
+ const approveGas = await quoteL2Gas4({ ctx, tx: approveTxCandidate });
2372
+ steps.push({
2373
+ key: `approve:l2:${p.token}:${ctx.l2NativeTokenVault}`,
2374
+ kind: "approve:l2",
2375
+ description: `Approve ${p.amount} to NativeTokenVault`,
2376
+ tx: {
2377
+ address: p.token,
2378
+ abi: IERC20_default,
2379
+ functionName: "approve",
2380
+ args: [ctx.l2NativeTokenVault, p.amount],
2381
+ account: ctx.client.account,
2382
+ ...approveGas
2383
+ }
2384
+ });
2385
+ }
2386
+ }
2387
+ const nonce = await wrapAs9(
2388
+ "RPC",
2389
+ OP_WITHDRAWALS.prepare,
2390
+ () => ctx.client.l2.getTransactionCount({ address: ctx.sender, blockTag: "pending" }),
2391
+ {
2392
+ ctx: { where: "l2.getTransactionCount", sender: ctx.sender },
2393
+ message: "Failed to read L2 nonce for the interop bundle salt."
2394
+ }
2395
+ );
2396
+ const bundle = buildWithdrawalBundle({
2397
+ assetId,
2398
+ amount: p.amount,
2399
+ l1Receiver,
2400
+ l2Token: isBaseToken ? FORMAL_ETH_ADDRESS : p.token,
2401
+ isBaseToken,
2402
+ l1ChainId: ctx.l1ChainId,
2403
+ l2AssetRouter: ctx.l2AssetRouter,
2404
+ salt: saltFor(ctx.sender, nonce),
2405
+ codec: interopCodec,
2406
+ attributes: {
2407
+ indirectCall: attributes.call.indirectCall,
2408
+ interopCallValue: attributes.call.interopCallValue,
2409
+ interopBundleSalt: attributes.bundle.interopBundleSalt
2410
+ },
2411
+ transferData: {
2412
+ encodeBridgeBurnData: encodeNativeTokenVaultTransferData,
2413
+ encodeAssetRouterDepositData: encodeSecondBridgeDataV1
2414
+ }
2415
+ });
2416
+ const sendArgs = [bundle.destinationChain, bundle.starters, bundle.bundleAttributes];
2417
+ const sendTxCandidate = {
2418
+ to: ctx.interopCenter,
2419
+ data: encodeFunctionData({
2420
+ abi: IInteropCenter_default,
2421
+ functionName: "sendBundle",
2422
+ args: sendArgs
2423
+ }),
2424
+ value: bundle.value,
2425
+ from: ctx.sender
2426
+ };
2427
+ const sendGas = allowanceSufficient ? await quoteL2Gas4({ ctx, tx: sendTxCandidate }) : void 0;
2428
+ const sendTx = {
2429
+ address: ctx.interopCenter,
2430
+ abi: IInteropCenter_default,
2431
+ functionName: "sendBundle",
2432
+ args: sendArgs,
2433
+ account: ctx.client.account,
2434
+ value: bundle.value,
2435
+ ...sendGas
2436
+ };
2437
+ steps.push({
2438
+ key: "interop-center:send-bundle",
2439
+ kind: "interop-center:send-bundle",
2440
+ description: "Burn on L2 & send L2\u2192L1 withdrawal bundle",
2441
+ tx: sendTx
2442
+ });
2443
+ const fees = buildFeeBreakdown2({
2444
+ feeToken: ctx.baseTokenL1 ?? await ctx.client.baseToken(ctx.chainIdL2),
2445
+ l2Gas: sendGas
2446
+ });
2447
+ return { steps, approvals, fees };
2448
+ }
2449
+ };
2450
+ }
2451
+
2452
+ // src/adapters/viem/resources/withdrawals/services/protocol.ts
2453
+ function createWithdrawalProtocolService(client, override) {
2454
+ let cached;
2455
+ async function hasCodeAt(address) {
2456
+ try {
2457
+ const code = await client.l2.getCode({ address });
2458
+ return !!code && code !== "0x";
2459
+ } catch {
2460
+ return false;
2461
+ }
2462
+ }
2463
+ async function protocolVersion() {
2464
+ try {
2465
+ return await client.getChainProtocolVersion();
2466
+ } catch {
2467
+ return void 0;
2468
+ }
2469
+ }
2470
+ function detect() {
2471
+ cached ??= detectWithdrawalProtocol(
2472
+ {
2473
+ protocolVersion,
2474
+ hasCodeAt
2475
+ },
2476
+ override
2477
+ ).catch((e) => {
2478
+ cached = void 0;
2479
+ throw e;
2480
+ });
2481
+ return cached;
2482
+ }
2483
+ return {
2484
+ detect,
2485
+ async protocol() {
2486
+ return (await detect()).protocol;
2487
+ },
2488
+ refresh() {
2489
+ cached = void 0;
2490
+ }
2491
+ };
2492
+ }
2493
+ var { wrapAs: wrapAs10 } = createErrorHandlers("withdrawals");
2234
2494
  var IL1NullifierMini = [
2235
2495
  {
2236
2496
  type: "function",
@@ -2244,183 +2504,279 @@ var IL1NullifierMini = [
2244
2504
  outputs: [{ type: "bool" }]
2245
2505
  }
2246
2506
  ];
2247
- function createFinalizationServices(client) {
2248
- return {
2249
- async fetchFinalizeDepositParams(l2TxHash) {
2250
- const parsed = await wrapAs9(
2251
- "RPC",
2252
- OP_WITHDRAWALS.finalize.fetchParams.receipt,
2253
- () => client.zks.getReceiptWithL2ToL1(l2TxHash),
2254
- {
2255
- ctx: { where: "getReceiptWithL2ToL1", l2TxHash },
2256
- message: "Failed to fetch L2 receipt (with L2\u2192L1 logs)."
2507
+ function createFinalizationServices(client, protocolService = createWithdrawalProtocolService(client)) {
2508
+ async function finalizationTarget(protocol) {
2509
+ const { l1Nullifier } = await client.ensureAddresses();
2510
+ if (protocol === "legacy-withdrawal") return l1Nullifier;
2511
+ return await wrapAs10(
2512
+ "CONTRACT",
2513
+ OP_WITHDRAWALS.finalize.fetchParams.receipt,
2514
+ () => client.l1.readContract({
2515
+ address: l1Nullifier,
2516
+ abi: IL1NullifierV32_default,
2517
+ functionName: "l1InteropHandler"
2518
+ }),
2519
+ {
2520
+ ctx: { where: "L1Nullifier.l1InteropHandler", l1Nullifier },
2521
+ message: "Failed to resolve the L1 interop handler. The chain reports protocol v32+, but its L1Nullifier does not expose `l1InteropHandler()`."
2522
+ }
2523
+ );
2524
+ }
2525
+ async function fetchMessageAndProof(l2TxHash) {
2526
+ const raw = await wrapAs10(
2527
+ "RPC",
2528
+ OP_WITHDRAWALS.finalize.fetchParams.receipt,
2529
+ () => client.zks.getReceiptWithL2ToL1(l2TxHash),
2530
+ {
2531
+ ctx: { where: "getReceiptWithL2ToL1", l2TxHash },
2532
+ message: "Failed to fetch L2 receipt (with L2\u2192L1 logs)."
2533
+ }
2534
+ );
2535
+ if (!raw) {
2536
+ throw createError("STATE", {
2537
+ resource: "withdrawals",
2538
+ operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
2539
+ message: "L2 receipt not found.",
2540
+ context: { l2TxHash }
2541
+ });
2542
+ }
2543
+ const ev = await wrapAs10(
2544
+ "INTERNAL",
2545
+ OP_WITHDRAWALS.finalize.fetchParams.findMessage,
2546
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
2547
+ () => Promise.resolve(findL1MessageSentLog(raw, { index: 0 })),
2548
+ {
2549
+ ctx: { l2TxHash, index: 0 },
2550
+ message: "Failed to locate L1MessageSent event in L2 receipt."
2551
+ }
2552
+ );
2553
+ const message = await wrapAs10(
2554
+ "INTERNAL",
2555
+ OP_WITHDRAWALS.finalize.fetchParams.decodeMessage,
2556
+ () => {
2557
+ const [decoded] = decodeAbiParameters([{ type: "bytes" }], ev.data);
2558
+ return Promise.resolve(decoded);
2559
+ },
2560
+ {
2561
+ ctx: { where: "decode L1MessageSent", data: ev.data },
2562
+ message: "Failed to decode withdrawal message."
2563
+ }
2564
+ );
2565
+ const idx = await wrapAs10(
2566
+ "INTERNAL",
2567
+ OP_WITHDRAWALS.finalize.fetchParams.messengerIndex,
2568
+ () => Promise.resolve(messengerLogIndex(raw, { index: 0, messenger: L1_MESSENGER_ADDRESS })),
2569
+ {
2570
+ ctx: { where: "derive messenger log index", l2TxHash, receipt: raw },
2571
+ message: "Failed to derive messenger log index."
2572
+ }
2573
+ );
2574
+ const proof = await wrapAs10(
2575
+ "RPC",
2576
+ OP_WITHDRAWALS.finalize.fetchParams.proof,
2577
+ () => client.zks.getL2ToL1LogProof(l2TxHash, idx),
2578
+ {
2579
+ ctx: { where: "get L2\u2192L1 log proof", l2TxHash, messengerLogIndex: idx },
2580
+ message: "Failed to fetch L2\u2192L1 log proof."
2581
+ }
2582
+ );
2583
+ const chainId = await wrapAs10(
2584
+ "RPC",
2585
+ OP_WITHDRAWALS.finalize.fetchParams.network,
2586
+ () => client.l2.getChainId(),
2587
+ { ctx: { where: "l2.getChainId" }, message: "Failed to read L2 chain id." }
2588
+ );
2589
+ const txNumberInBatch = Number(raw.transactionIndex ?? 0);
2590
+ const l2Sender = l1MessageSentSender(ev);
2591
+ return { raw, message, proof, chainId: BigInt(chainId), txNumberInBatch, l2Sender };
2592
+ }
2593
+ async function fetchFinalization(l2TxHash) {
2594
+ const protocol = await protocolService.protocol();
2595
+ const { raw, message, proof, chainId, txNumberInBatch, l2Sender } = await fetchMessageAndProof(l2TxHash);
2596
+ const target = await finalizationTarget(protocol);
2597
+ if (protocol === "legacy-withdrawal") {
2598
+ const params2 = {
2599
+ chainId,
2600
+ l2BatchNumber: proof.batchNumber,
2601
+ l2MessageIndex: proof.id,
2602
+ l2Sender,
2603
+ l2TxNumberInBatch: txNumberInBatch,
2604
+ message,
2605
+ merkleProof: proof.proof
2606
+ };
2607
+ return {
2608
+ target,
2609
+ finalization: { protocol, params: params2 },
2610
+ key: {
2611
+ chainIdL2: chainId,
2612
+ l2BatchNumber: proof.batchNumber,
2613
+ l2MessageIndex: proof.id
2257
2614
  }
2258
- );
2259
- if (!parsed) {
2260
- throw createError("STATE", {
2261
- resource: "withdrawals",
2262
- operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
2263
- message: "L2 receipt not found.",
2264
- context: { l2TxHash }
2265
- });
2615
+ };
2616
+ }
2617
+ const { interopCenter } = await client.ensureAddresses();
2618
+ const params = buildWithdrawalFinalization({
2619
+ messageData: message,
2620
+ sourceChainId: chainId,
2621
+ txNumberInBatch,
2622
+ proof: { batchNumber: proof.batchNumber, id: proof.id, proof: proof.proof },
2623
+ // Prefer the hash the InteropCenter emitted over recomputing it.
2624
+ bundleHash: parseBundleHashFromLogs(raw.logs ?? [], interopCenter),
2625
+ interopCenter
2626
+ });
2627
+ return {
2628
+ target,
2629
+ finalization: { protocol, params },
2630
+ key: {
2631
+ chainIdL2: chainId,
2632
+ l2BatchNumber: proof.batchNumber,
2633
+ l2MessageIndex: proof.id,
2634
+ bundleHash: params.bundleHash
2266
2635
  }
2267
- const ev = await wrapAs9(
2268
- "INTERNAL",
2269
- OP_WITHDRAWALS.finalize.fetchParams.findMessage,
2270
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
2271
- () => Promise.resolve(findL1MessageSentLog(parsed, { index: 0 })),
2636
+ };
2637
+ }
2638
+ async function withdrawalOutcome(finalization) {
2639
+ const target = await finalizationTarget(finalization.protocol);
2640
+ if (finalization.protocol === "legacy-withdrawal") {
2641
+ const done = await wrapAs10(
2642
+ "RPC",
2643
+ OP_WITHDRAWALS.finalize.isFinalized,
2644
+ () => client.l1.readContract({
2645
+ address: target,
2646
+ abi: IL1NullifierMini,
2647
+ functionName: "isWithdrawalFinalized",
2648
+ args: [
2649
+ finalization.params.chainId,
2650
+ finalization.params.l2BatchNumber,
2651
+ finalization.params.l2MessageIndex
2652
+ ]
2653
+ }),
2272
2654
  {
2273
- ctx: { l2TxHash, index: 0 },
2274
- message: "Failed to locate L1MessageSent event in L2 receipt."
2655
+ ctx: { where: "isWithdrawalFinalized", params: finalization.params },
2656
+ message: "Failed to read finalization status."
2275
2657
  }
2276
2658
  );
2277
- const message = await wrapAs9(
2278
- "INTERNAL",
2279
- OP_WITHDRAWALS.finalize.fetchParams.decodeMessage,
2280
- () => {
2281
- const [decoded] = decodeAbiParameters([{ type: "bytes" }], ev.data);
2282
- return decoded;
2283
- },
2659
+ return done ? "finalized" : "pending";
2660
+ }
2661
+ const { bundleHash } = finalization.params;
2662
+ const status = Number(
2663
+ await wrapAs10(
2664
+ "RPC",
2665
+ OP_WITHDRAWALS.finalize.isFinalized,
2666
+ () => client.l1.readContract({
2667
+ address: target,
2668
+ abi: IInteropHandler_default,
2669
+ functionName: "bundleStatus",
2670
+ args: [bundleHash]
2671
+ }),
2284
2672
  {
2285
- ctx: { where: "decode L1MessageSent", data: ev.data },
2286
- message: "Failed to decode withdrawal message."
2673
+ ctx: { where: "L1InteropHandler.bundleStatus", bundleHash },
2674
+ message: "Failed to read bundle status."
2287
2675
  }
2288
- );
2289
- const raw = await wrapAs9(
2676
+ )
2677
+ );
2678
+ if (status !== 3 /* Unbundled */) return classifyWithdrawalOutcome(status);
2679
+ const callStatus = Number(
2680
+ await wrapAs10(
2290
2681
  "RPC",
2291
- OP_WITHDRAWALS.finalize.fetchParams.rawReceipt,
2292
- () => client.zks.getReceiptWithL2ToL1(l2TxHash),
2682
+ OP_WITHDRAWALS.finalize.isFinalized,
2683
+ () => client.l1.readContract({
2684
+ address: target,
2685
+ abi: IInteropHandler_default,
2686
+ functionName: "callStatus",
2687
+ args: [bundleHash, 0n]
2688
+ }),
2293
2689
  {
2294
- ctx: { where: "getReceiptWithL2ToL1 (raw)", l2TxHash },
2295
- message: "Failed to fetch raw L2 receipt."
2690
+ ctx: { where: "L1InteropHandler.callStatus", bundleHash },
2691
+ message: "Failed to read bundle call status."
2296
2692
  }
2297
- );
2298
- if (!raw) {
2299
- throw createError("STATE", {
2693
+ )
2694
+ );
2695
+ return classifyWithdrawalOutcome(status, callStatus);
2696
+ }
2697
+ async function isWithdrawalFinalized(finalization) {
2698
+ return await withdrawalOutcome(finalization) === "finalized";
2699
+ }
2700
+ return {
2701
+ fetchFinalization,
2702
+ isWithdrawalFinalized,
2703
+ withdrawalOutcome,
2704
+ async fetchFinalizeDepositParams(l2TxHash) {
2705
+ const resolved = await fetchFinalization(l2TxHash);
2706
+ if (resolved.finalization.protocol !== "legacy-withdrawal") {
2707
+ throw createError("VALIDATION", {
2300
2708
  resource: "withdrawals",
2301
- operation: OP_WITHDRAWALS.finalize.fetchParams.rawReceipt,
2302
- message: "Raw L2 receipt not found.",
2303
- context: { l2TxHash }
2709
+ operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
2710
+ message: "This chain finalizes withdrawals through the L1 interop handler; `finalizeDeposit` params do not exist. Use `fetchFinalization` instead.",
2711
+ context: { l2TxHash, protocol: resolved.finalization.protocol }
2304
2712
  });
2305
2713
  }
2306
- const idx = await wrapAs9(
2307
- "INTERNAL",
2308
- OP_WITHDRAWALS.finalize.fetchParams.messengerIndex,
2309
- () => Promise.resolve(messengerLogIndex(raw, { index: 0, messenger: L1_MESSENGER_ADDRESS })),
2310
- {
2311
- ctx: { where: "derive messenger log index", l2TxHash, receipt: raw },
2312
- message: "Failed to derive messenger log index."
2313
- }
2314
- );
2315
- const proof = await wrapAs9(
2316
- "RPC",
2317
- OP_WITHDRAWALS.finalize.fetchParams.proof,
2318
- () => client.zks.getL2ToL1LogProof(l2TxHash, idx),
2319
- {
2320
- ctx: { where: "get L2\u2192L1 log proof", l2TxHash, messengerLogIndex: idx },
2321
- message: "Failed to fetch L2\u2192L1 log proof."
2322
- }
2323
- );
2324
- const chainId = await wrapAs9(
2325
- "RPC",
2326
- OP_WITHDRAWALS.finalize.fetchParams.network,
2327
- () => client.l2.getChainId(),
2328
- { ctx: { where: "l2.getChainId" }, message: "Failed to read L2 chain id." }
2329
- );
2330
- const txIndex = Number(parsed.transactionIndex ?? 0);
2331
- const params = {
2332
- chainId: BigInt(chainId),
2333
- l2BatchNumber: proof.batchNumber,
2334
- l2MessageIndex: proof.id,
2335
- l2Sender: parsed.to,
2336
- l2TxNumberInBatch: txIndex,
2337
- message,
2338
- merkleProof: proof.proof
2339
- };
2340
- const { l1Nullifier } = await client.ensureAddresses();
2341
- return { params, nullifier: l1Nullifier };
2714
+ return { params: resolved.finalization.params, nullifier: resolved.target };
2342
2715
  },
2343
- async simulateFinalizeReadiness(params) {
2344
- const { l1Nullifier } = await client.ensureAddresses();
2716
+ async simulateFinalizeReadiness(finalization) {
2717
+ const target = await finalizationTarget(finalization.protocol);
2345
2718
  const done = await (async () => {
2346
2719
  try {
2347
- const result = await wrapAs9(
2348
- "RPC",
2349
- OP_WITHDRAWALS.finalize.readiness.isFinalized,
2350
- () => client.l1.readContract({
2351
- address: l1Nullifier,
2352
- abi: IL1NullifierMini,
2353
- functionName: "isWithdrawalFinalized",
2354
- args: [params.chainId, params.l2BatchNumber, params.l2MessageIndex]
2355
- }),
2356
- {
2357
- ctx: { where: "isWithdrawalFinalized", params },
2358
- message: "Failed to read finalization status."
2359
- }
2360
- );
2361
- return result;
2720
+ return await isWithdrawalFinalized(finalization);
2362
2721
  } catch {
2363
2722
  return false;
2364
2723
  }
2365
2724
  })();
2366
2725
  if (done) return { kind: "FINALIZED" };
2367
2726
  try {
2368
- await client.l1.simulateContract({
2369
- address: l1Nullifier,
2370
- abi: IL1Nullifier_default,
2371
- functionName: "finalizeDeposit",
2372
- args: [params],
2373
- account: client.account
2374
- });
2727
+ if (finalization.protocol === "legacy-withdrawal") {
2728
+ await client.l1.simulateContract({
2729
+ address: target,
2730
+ abi: IL1Nullifier_default,
2731
+ functionName: "finalizeDeposit",
2732
+ args: [finalization.params],
2733
+ account: client.account
2734
+ });
2735
+ } else {
2736
+ await client.l1.simulateContract({
2737
+ address: target,
2738
+ abi: IInteropHandler_default,
2739
+ functionName: "executeBundle",
2740
+ args: [finalization.params.bundle, finalization.params.proof],
2741
+ account: client.account
2742
+ });
2743
+ }
2375
2744
  return { kind: "READY" };
2376
2745
  } catch (e) {
2377
2746
  return classifyReadinessFromRevert(e);
2378
2747
  }
2379
2748
  },
2380
- async isWithdrawalFinalized(key) {
2381
- const { l1Nullifier } = await client.ensureAddresses();
2382
- return await wrapAs9(
2383
- "RPC",
2384
- OP_WITHDRAWALS.finalize.isFinalized,
2385
- () => client.l1.readContract({
2386
- address: l1Nullifier,
2387
- abi: IL1NullifierMini,
2388
- functionName: "isWithdrawalFinalized",
2389
- args: [key.chainIdL2, key.l2BatchNumber, key.l2MessageIndex]
2390
- }),
2391
- {
2392
- ctx: { where: "isWithdrawalFinalized", key },
2393
- message: "Failed to read finalization status."
2394
- }
2395
- );
2396
- },
2397
- async estimateFinalization(params) {
2398
- const { l1Nullifier } = await client.ensureAddresses();
2399
- const gasLimit = await wrapAs9(
2749
+ async estimateFinalization(finalization) {
2750
+ const target = await finalizationTarget(finalization.protocol);
2751
+ const gasLimit = await wrapAs10(
2400
2752
  "RPC",
2401
2753
  OP_WITHDRAWALS.finalize.estimate,
2402
- () => client.l1.estimateContractGas({
2403
- address: l1Nullifier,
2754
+ () => finalization.protocol === "legacy-withdrawal" ? client.l1.estimateContractGas({
2755
+ address: target,
2404
2756
  abi: IL1Nullifier_default,
2405
2757
  functionName: "finalizeDeposit",
2406
- args: [params],
2758
+ args: [finalization.params],
2759
+ account: client.account
2760
+ }) : client.l1.estimateContractGas({
2761
+ address: target,
2762
+ abi: IInteropHandler_default,
2763
+ functionName: "executeBundle",
2764
+ args: [finalization.params.bundle, finalization.params.proof],
2407
2765
  account: client.account
2408
2766
  }),
2409
2767
  {
2410
2768
  ctx: {
2411
- where: "estimateContractGas(finalizeDeposit)",
2412
- chainIdL2: params.chainId,
2413
- l2BatchNumber: params.l2BatchNumber,
2414
- l2MessageIndex: params.l2MessageIndex,
2415
- l1Nullifier
2769
+ where: "estimateContractGas(finalize)",
2770
+ protocol: finalization.protocol,
2771
+ target
2416
2772
  },
2417
- message: "Failed to estimate gas for finalizeDeposit."
2773
+ message: "Failed to estimate gas for withdrawal finalization."
2418
2774
  }
2419
2775
  );
2420
2776
  let maxFeePerGas;
2421
2777
  let maxPriorityFeePerGas;
2422
2778
  try {
2423
- const fee = await wrapAs9(
2779
+ const fee = await wrapAs10(
2424
2780
  "RPC",
2425
2781
  OP_WITHDRAWALS.finalize.estimate,
2426
2782
  () => client.l1.estimateFeesPerGas(),
@@ -2439,32 +2795,34 @@ function createFinalizationServices(client) {
2439
2795
  })();
2440
2796
  maxPriorityFeePerGas = fee.maxPriorityFeePerGas ?? 0n;
2441
2797
  } catch {
2442
- const gasPrice = await wrapAs9(
2798
+ const gasPrice = await wrapAs10(
2443
2799
  "RPC",
2444
2800
  OP_WITHDRAWALS.finalize.estimate,
2445
2801
  () => client.l1.getGasPrice(),
2446
2802
  {
2447
2803
  ctx: { where: "getGasPrice" },
2448
- message: "Failed to read gas price for finalizeDeposit."
2804
+ message: "Failed to read gas price for withdrawal finalization."
2449
2805
  }
2450
2806
  );
2451
2807
  maxFeePerGas = gasPrice;
2452
2808
  maxPriorityFeePerGas = 0n;
2453
2809
  }
2454
- return {
2455
- gasLimit,
2456
- maxFeePerGas,
2457
- maxPriorityFeePerGas
2458
- };
2810
+ return { gasLimit, maxFeePerGas, maxPriorityFeePerGas };
2459
2811
  },
2460
- async finalizeDeposit(params) {
2461
- const { l1Nullifier } = await client.ensureAddresses();
2812
+ async finalize(finalization) {
2813
+ const target = await finalizationTarget(finalization.protocol);
2462
2814
  try {
2463
- const hash = await client.l1Wallet.writeContract({
2464
- address: l1Nullifier,
2815
+ const hash = finalization.protocol === "legacy-withdrawal" ? await client.l1Wallet.writeContract({
2816
+ address: target,
2465
2817
  abi: IL1Nullifier_default,
2466
2818
  functionName: "finalizeDeposit",
2467
- args: [params],
2819
+ args: [finalization.params],
2820
+ account: client.account
2821
+ }) : await client.l1Wallet.writeContract({
2822
+ address: target,
2823
+ abi: IInteropHandler_default,
2824
+ functionName: "executeBundle",
2825
+ args: [finalization.params.bundle, finalization.params.proof],
2468
2826
  account: client.account
2469
2827
  });
2470
2828
  return {
@@ -2478,8 +2836,8 @@ function createFinalizationServices(client) {
2478
2836
  {
2479
2837
  resource: "withdrawals",
2480
2838
  operation: OP_WITHDRAWALS.finalize.wait,
2481
- message: "Failed while waiting for finalizeDeposit transaction.",
2482
- context: { txHash: hash }
2839
+ message: "Failed while waiting for the withdrawal finalization transaction.",
2840
+ context: { txHash: hash, protocol: finalization.protocol }
2483
2841
  },
2484
2842
  e
2485
2843
  );
@@ -2492,13 +2850,8 @@ function createFinalizationServices(client) {
2492
2850
  {
2493
2851
  resource: "withdrawals",
2494
2852
  operation: OP_WITHDRAWALS.finalize.send,
2495
- message: "Failed to send finalizeDeposit transaction.",
2496
- context: {
2497
- chainIdL2: params.chainId,
2498
- l2BatchNumber: params.l2BatchNumber,
2499
- l2MessageIndex: params.l2MessageIndex,
2500
- l1Nullifier
2501
- }
2853
+ message: "Failed to send the withdrawal finalization transaction.",
2854
+ context: { protocol: finalization.protocol, target }
2502
2855
  },
2503
2856
  e
2504
2857
  );
@@ -2514,15 +2867,28 @@ var ROUTES2 = {
2514
2867
  "erc20-nonbase": routeErc20NonBase2()
2515
2868
  // AssetRouter.withdraw for non-base ERC-20s
2516
2869
  };
2517
- function createWithdrawalsResource(client, tokens, contracts) {
2518
- const svc = createFinalizationServices(client);
2870
+ var INTEROP_ROUTES = {
2871
+ base: routeInteropBundle(),
2872
+ "erc20-nonbase": routeInteropBundle()
2873
+ };
2874
+ function routeStrategy(protocol, route) {
2875
+ return protocol === "interop-bundle" ? INTEROP_ROUTES[route] : ROUTES2[route];
2876
+ }
2877
+ function createWithdrawalsResource(client, tokens, contracts, options) {
2878
+ const protocolService = createWithdrawalProtocolService(
2879
+ client,
2880
+ options?.protocol
2881
+ );
2882
+ const svc = createFinalizationServices(client, protocolService);
2519
2883
  const { wrap: wrap7, toResult: toResult3 } = createErrorHandlers("withdrawals");
2520
2884
  const tokensResource = tokens ?? createTokensResource(client);
2521
2885
  const contractsResource = contracts ?? createContractsResource(client);
2522
2886
  async function buildPlan(p) {
2523
- const ctx = await commonCtx2(p, client, tokensResource, contractsResource);
2524
- await ROUTES2[ctx.route].preflight?.(p, ctx);
2525
- const { steps, approvals, fees } = await ROUTES2[ctx.route].build(p, ctx);
2887
+ const protocol = await protocolService.protocol();
2888
+ const ctx = await commonCtx2(p, client, tokensResource, contractsResource, protocol);
2889
+ const strategy = routeStrategy(protocol, ctx.route);
2890
+ await strategy.preflight?.(p, ctx);
2891
+ const { steps, approvals, fees } = await strategy.build(p, ctx);
2526
2892
  return {
2527
2893
  route: ctx.route,
2528
2894
  summary: {
@@ -2689,24 +3055,22 @@ function createWithdrawalsResource(client, tokens, contracts) {
2689
3055
  if (!l2Rcpt) return { phase: "L2_PENDING", l2TxHash };
2690
3056
  let pack;
2691
3057
  try {
2692
- pack = await svc.fetchFinalizeDepositParams(l2TxHash);
3058
+ pack = await svc.fetchFinalization(l2TxHash);
2693
3059
  } catch {
2694
3060
  return { phase: "PENDING", l2TxHash };
2695
3061
  }
2696
- const key = {
2697
- chainIdL2: pack.params.chainId,
2698
- l2BatchNumber: pack.params.l2BatchNumber,
2699
- l2MessageIndex: pack.params.l2MessageIndex
2700
- };
3062
+ const key = pack.key;
2701
3063
  try {
2702
- const done = await svc.isWithdrawalFinalized(key);
2703
- if (done) return { phase: "FINALIZED", l2TxHash, key };
3064
+ const outcome = await svc.withdrawalOutcome(pack.finalization);
3065
+ if (outcome === "finalized") return { phase: "FINALIZED", l2TxHash, key };
3066
+ if (outcome === "failed") {
3067
+ return { phase: "UNFINALIZABLE", l2TxHash, key, reason: "bundle-cancelled" };
3068
+ }
2704
3069
  } catch {
2705
3070
  }
2706
- const readiness = await svc.simulateFinalizeReadiness(pack.params);
2707
- if (readiness.kind === "FINALIZED") return { phase: "FINALIZED", l2TxHash, key };
2708
- if (readiness.kind === "READY") return { phase: "READY_TO_FINALIZE", l2TxHash, key };
2709
- return { phase: "PENDING", l2TxHash, key };
3071
+ const readiness = await svc.simulateFinalizeReadiness(pack.finalization);
3072
+ const { phase, reason } = phaseFromReadiness(readiness);
3073
+ return { phase, reason, l2TxHash, key };
2710
3074
  },
2711
3075
  {
2712
3076
  message: "Internal error while checking withdrawal status.",
@@ -2754,6 +3118,14 @@ function createWithdrawalsResource(client, tokens, contracts) {
2754
3118
  const deadline = opts.timeoutMs ? Date.now() + opts.timeoutMs : void 0;
2755
3119
  while (true) {
2756
3120
  const s = await status(l2Hash);
3121
+ if (s.phase === "UNFINALIZABLE") {
3122
+ throw createError("STATE", {
3123
+ resource: "withdrawals",
3124
+ operation: OP_WITHDRAWALS.wait,
3125
+ message: "Withdrawal can never be finalized.",
3126
+ context: { l2TxHash: l2Hash, reason: s.reason }
3127
+ });
3128
+ }
2757
3129
  if (opts.for === "ready") {
2758
3130
  if (s.phase === "READY_TO_FINALIZE" || s.phase === "FINALIZED") return null;
2759
3131
  } else {
@@ -2790,7 +3162,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
2790
3162
  async () => {
2791
3163
  const pack = await (async () => {
2792
3164
  try {
2793
- return await svc.fetchFinalizeDepositParams(l2TxHash);
3165
+ return await svc.fetchFinalization(l2TxHash);
2794
3166
  } catch (e) {
2795
3167
  throw createError("STATE", {
2796
3168
  resource: "withdrawals",
@@ -2801,21 +3173,16 @@ function createWithdrawalsResource(client, tokens, contracts) {
2801
3173
  });
2802
3174
  }
2803
3175
  })();
2804
- const { params } = pack;
2805
- const key = {
2806
- chainIdL2: params.chainId,
2807
- l2BatchNumber: params.l2BatchNumber,
2808
- l2MessageIndex: params.l2MessageIndex
2809
- };
3176
+ const { finalization } = pack;
2810
3177
  try {
2811
- const done = await svc.isWithdrawalFinalized(key);
2812
- if (done) {
3178
+ const outcome = await svc.withdrawalOutcome(finalization);
3179
+ if (outcome === "finalized" || outcome === "failed") {
2813
3180
  const statusNow = await status(l2TxHash);
2814
3181
  return { status: statusNow };
2815
3182
  }
2816
3183
  } catch {
2817
3184
  }
2818
- const readiness = await svc.simulateFinalizeReadiness(params);
3185
+ const readiness = await svc.simulateFinalizeReadiness(finalization);
2819
3186
  if (readiness.kind === "FINALIZED") {
2820
3187
  const statusNow = await status(l2TxHash);
2821
3188
  return { status: statusNow };
@@ -2829,7 +3196,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
2829
3196
  });
2830
3197
  }
2831
3198
  try {
2832
- const tx = await svc.finalizeDeposit(params);
3199
+ const tx = await svc.finalize(finalization);
2833
3200
  finalizeCache.set(l2TxHash, tx.hash);
2834
3201
  const rcpt = await tx.wait();
2835
3202
  const statusNow = await status(l2TxHash);
@@ -2838,7 +3205,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
2838
3205
  const statusNow = await status(l2TxHash);
2839
3206
  if (statusNow.phase === "FINALIZED") return { status: statusNow };
2840
3207
  try {
2841
- const again = await svc.simulateFinalizeReadiness(params);
3208
+ const again = await svc.simulateFinalizeReadiness(finalization);
2842
3209
  if (again.kind === "NOT_READY") {
2843
3210
  throw createError("STATE", {
2844
3211
  resource: "withdrawals",
@@ -2896,63 +3263,6 @@ function createWithdrawalsResource(client, tokens, contracts) {
2896
3263
  tryWait
2897
3264
  };
2898
3265
  }
2899
- function getInteropAttributes(params, ctx) {
2900
- const bundleAttributes = [];
2901
- if (params.execution?.only) {
2902
- bundleAttributes.push(ctx.attributes.bundle.executionAddress(params.execution.only));
2903
- }
2904
- if (params.unbundling?.by) {
2905
- bundleAttributes.push(ctx.attributes.bundle.unbundlerAddress(params.unbundling.by));
2906
- }
2907
- bundleAttributes.push(ctx.attributes.bundle.useFixedFee(params.fee?.useFixed ?? false));
2908
- const callAttributes = params.actions.map((action) => {
2909
- switch (action.type) {
2910
- case "sendNative": {
2911
- const baseMatches = ctx.baseTokens.src.toLowerCase() === ctx.baseTokens.dst.toLowerCase();
2912
- if (baseMatches) {
2913
- return [ctx.attributes.call.interopCallValue(action.amount)];
2914
- }
2915
- return [ctx.attributes.call.indirectCall(action.amount)];
2916
- }
2917
- case "call":
2918
- if (action.value && action.value > 0n) {
2919
- return [ctx.attributes.call.interopCallValue(action.value)];
2920
- }
2921
- return [];
2922
- case "sendErc20":
2923
- return [ctx.attributes.call.indirectCall(0n)];
2924
- default:
2925
- assertNever(action);
2926
- }
2927
- });
2928
- return { bundleAttributes, callAttributes };
2929
- }
2930
- function createViemAttributesResource() {
2931
- const encode = (fn, args) => encodeFunctionData({
2932
- abi: IERC7786Attributes_default,
2933
- functionName: fn,
2934
- args
2935
- });
2936
- return createAttributesResource({ encode });
2937
- }
2938
- var PREFIX_EVM_CHAIN = toBytes("0x00010000");
2939
- var PREFIX_EVM_ADDRESS = toBytes("0x000100000014");
2940
- function formatInteropEvmChain(chainId) {
2941
- const chainRef = toBytes(toHex(chainId));
2942
- const chainRefLength = toBytes(toHex(chainRef.length, { size: 1 }));
2943
- const payload = concat([PREFIX_EVM_CHAIN, chainRefLength, chainRef, new Uint8Array([0])]);
2944
- return toHex(payload);
2945
- }
2946
- function formatInteropEvmAddress(address) {
2947
- const normalized = getAddress(address);
2948
- const addrBytes = toBytes(normalized);
2949
- const payload = concat([PREFIX_EVM_ADDRESS, addrBytes]);
2950
- return toHex(payload);
2951
- }
2952
- var interopCodec = {
2953
- formatChain: formatInteropEvmChain,
2954
- formatAddress: formatInteropEvmAddress
2955
- };
2956
3266
  function getErc20Tokens(params) {
2957
3267
  const erc20Tokens = /* @__PURE__ */ new Map();
2958
3268
  for (const action of params.actions) {
@@ -3136,7 +3446,7 @@ function routeIndirect() {
3136
3446
  resolveErc20AssetIds(erc20Tokens, ctx),
3137
3447
  buildFeeInfo(params, ctx, params.actions.length)
3138
3448
  ]);
3139
- const attributes = getInteropAttributes(params, ctx);
3449
+ const attributes2 = getInteropAttributes(params, ctx);
3140
3450
  const starterData = await getStarterData(params, ctx, erc20AssetIds);
3141
3451
  const bundle = buildIndirectBundle(
3142
3452
  params,
@@ -3147,7 +3457,7 @@ function routeIndirect() {
3147
3457
  l2NativeTokenVault: ctx.l2NativeTokenVault,
3148
3458
  codec: interopCodec
3149
3459
  },
3150
- attributes,
3460
+ attributes2,
3151
3461
  starterData,
3152
3462
  feeInfo
3153
3463
  );
@@ -3252,7 +3562,7 @@ async function assertInteropProtocolVersion(client, srcChainId, dstChainId) {
3252
3562
  assertProtocolVersion(srcChainId, srcProtocolVersion);
3253
3563
  assertProtocolVersion(dstChainId, dstProtocolVersion);
3254
3564
  }
3255
- async function commonCtx3(dstPublicClient, params, client, tokens, contracts, attributes) {
3565
+ async function commonCtx3(dstPublicClient, params, client, tokens, contracts, attributes2) {
3256
3566
  const sender = client.account.address;
3257
3567
  const chainId = BigInt(await client.l2.getChainId());
3258
3568
  const dstChainId = BigInt(await dstPublicClient.getChainId());
@@ -3286,7 +3596,7 @@ async function commonCtx3(dstPublicClient, params, client, tokens, contracts, at
3286
3596
  l2AssetRouter,
3287
3597
  l2NativeTokenVault,
3288
3598
  baseTokens: { src: srcBaseToken, dst: dstBaseToken, matches: baseMatches },
3289
- attributes,
3599
+ attributes: attributes2,
3290
3600
  gasOverrides: params.txOverrides ? toGasOverrides(params.txOverrides) : void 0
3291
3601
  };
3292
3602
  }
@@ -3854,7 +4164,7 @@ var ROUTES3 = {
3854
4164
  direct: routeDirect(),
3855
4165
  indirect: routeIndirect()
3856
4166
  };
3857
- function createInteropResource(client, config, tokens, contracts, attributes) {
4167
+ function createInteropResource(client, config, tokens, contracts, attributes2) {
3858
4168
  let gwProviderCache;
3859
4169
  function requireConfig() {
3860
4170
  if (!config)
@@ -3872,7 +4182,7 @@ function createInteropResource(client, config, tokens, contracts, attributes) {
3872
4182
  const svc = createInteropFinalizationServices(client);
3873
4183
  const tokensResource = tokens ?? createTokensResource(client);
3874
4184
  const contractsResource = contracts ?? createContractsResource(client);
3875
- const attributesResource = attributes ?? createViemAttributesResource();
4185
+ const attributesResource = attributes2 ?? createViemAttributesResource();
3876
4186
  async function buildPlanWithCtx(dstPublicClient, params) {
3877
4187
  const ctx = await commonCtx3(
3878
4188
  dstPublicClient,
@@ -4092,11 +4402,11 @@ function createViemSdk(client, options) {
4092
4402
  const interop = createInteropResource(client, options?.interop, tokens, contracts);
4093
4403
  return {
4094
4404
  deposits: createDepositsResource(client, tokens, contracts),
4095
- withdrawals: createWithdrawalsResource(client, tokens, contracts),
4405
+ withdrawals: createWithdrawalsResource(client, tokens, contracts, options?.withdrawals),
4096
4406
  tokens,
4097
4407
  contracts,
4098
4408
  interop
4099
4409
  };
4100
4410
  }
4101
4411
 
4102
- export { buildDirectRequestStruct, createContractsResource, createDepositsResource, createFinalizationServices, createInteropFinalizationServices, createInteropResource, createTokensResource, createViemSdk, createWithdrawalsResource, encodeNativeTokenVaultTransferData, encodeSecondBridgeArgs, encodeSecondBridgeDataV1, encodeSecondBridgeErc20Args, encodeSecondBridgeEthArgs, getL2TransactionHashFromLogs };
4412
+ export { buildDirectRequestStruct, createContractsResource, createDepositsResource, createFinalizationServices, createInteropFinalizationServices, createInteropResource, createTokensResource, createViemSdk, createWithdrawalProtocolService, createWithdrawalsResource, encodeNativeTokenVaultTransferData, encodeSecondBridgeArgs, encodeSecondBridgeDataV1, encodeSecondBridgeErc20Args, encodeSecondBridgeEthArgs, getL2TransactionHashFromLogs };