@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,8 +1,9 @@
1
- import { createErrorHandlers, toZKsyncError, classifyReadinessFromRevert } from './chunk-NJK325XV.js';
2
- 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, quoteL2BaseCost, quoteL1Gas, derivePriorityBodyGasEstimateCap, quoteL2Gas2, assertProtocolVersion } from './chunk-6LYAENO6.js';
3
- import { findL1MessageSentLog, messengerLogIndex, pickWithdrawRoute } from './chunk-3HHUZXSV.js';
4
- import { isHash66, IL1Nullifier_default, OP_WITHDRAWALS, createError, normalizeL1Token, isAddressEq, hexEq, OP_DEPOSITS, IERC20_default, isZKsyncError, isReceiptNotFound, OP_INTEROP, IInteropHandler_default, IERC7786Attributes_default, IInteropRootStorage_default, IInteropCenter_default, sleep, isETH, normalizeAddrEq, IL2AssetRouter_default, L2NativeTokenVault_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';
1
+ import { createErrorHandlers, toZKsyncError, classifyReadinessFromRevert } from './chunk-CPNHKNI4.js';
2
+ 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, quoteL2BaseCost, quoteL1Gas, derivePriorityBodyGasEstimateCap, assertProtocolVersion, quoteL2Gas2 } from './chunk-3SPDWWRD.js';
3
+ import { detectWithdrawalProtocol, buildWithdrawalFinalization, parseBundleHashFromLogs, classifyWithdrawalOutcome, phaseFromReadiness, buildWithdrawalBundle } from './chunk-QUAPG3ZR.js';
4
+ import { findL1MessageSentLog, messengerLogIndex, l1MessageSentSender, pickWithdrawRoute } from './chunk-32N6TI6K.js';
5
+ import { IERC7786Attributes_default, isHash66, IL1Nullifier_default, IInteropHandler_default, createError, OP_WITHDRAWALS, normalizeL1Token, isAddressEq, hexEq, OP_DEPOSITS, IERC20_default, isZKsyncError, isReceiptNotFound, IL1NullifierV32_default, OP_INTEROP, IInteropRootStorage_default, IInteropCenter_default, sleep, isETH, normalizeAddrEq, IL2AssetRouter_default, L2NativeTokenVault_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';
6
7
  import { Interface, keccak256, AbiCoder, ethers, getBytes, Contract, NonceManager, JsonRpcProvider, getAddress, concat, hexlify, toBeArray, toBeHex, isError } from 'ethers';
7
8
 
8
9
  var I_BRIDGEHUB = new Interface([
@@ -1612,7 +1613,7 @@ function createDepositsResource(client, tokens, contracts) {
1612
1613
  }
1613
1614
 
1614
1615
  // src/adapters/ethers/resources/withdrawals/context.ts
1615
- async function commonCtx2(p, client, tokens, contracts) {
1616
+ async function commonCtx2(p, client, tokens, contracts, protocol) {
1616
1617
  const sender = await client.signer.getAddress();
1617
1618
  const {
1618
1619
  bridgehub,
@@ -1620,10 +1621,12 @@ async function commonCtx2(p, client, tokens, contracts) {
1620
1621
  l1Nullifier,
1621
1622
  l2AssetRouter,
1622
1623
  l2NativeTokenVault,
1623
- l2BaseTokenSystem
1624
+ l2BaseTokenSystem,
1625
+ interopCenter
1624
1626
  } = await contracts.addresses();
1625
1627
  const { chainId } = await client.l2.getNetwork();
1626
1628
  const chainIdL2 = BigInt(chainId);
1629
+ const l1ChainId = BigInt((await client.l1.getNetwork()).chainId);
1627
1630
  const resolvedToken = await tokens.resolve(p.token, { chain: "l2" });
1628
1631
  const baseTokenAssetId = resolvedToken.baseTokenAssetId;
1629
1632
  const baseTokenL1 = await tokens.l1TokenFromAssetId(baseTokenAssetId);
@@ -1645,6 +1648,9 @@ async function commonCtx2(p, client, tokens, contracts) {
1645
1648
  l2AssetRouter,
1646
1649
  l2NativeTokenVault,
1647
1650
  l2BaseTokenSystem,
1651
+ interopCenter,
1652
+ protocol,
1653
+ l1ChainId,
1648
1654
  baseIsEth,
1649
1655
  gasOverrides: p.l2TxOverrides ? toGasOverrides(p.l2TxOverrides) : void 0
1650
1656
  };
@@ -1826,174 +1832,492 @@ function routeErc20NonBase2() {
1826
1832
  }
1827
1833
  };
1828
1834
  }
1835
+ var PREFIX_EVM_CHAIN = getBytes("0x00010000");
1836
+ var PREFIX_EVM_ADDRESS = getBytes("0x000100000014");
1837
+ function formatInteropEvmChain(chainId) {
1838
+ const chainRef = toBeArray(chainId);
1839
+ const chainRefLength = getBytes(toBeHex(chainRef.length, 1));
1840
+ const payload = concat([PREFIX_EVM_CHAIN, chainRefLength, chainRef, new Uint8Array([0])]);
1841
+ return hexlify(payload);
1842
+ }
1843
+ function formatInteropEvmAddress(address) {
1844
+ const normalized = getAddress(address);
1845
+ const addrBytes = getBytes(normalized);
1846
+ const payload = concat([PREFIX_EVM_ADDRESS, addrBytes]);
1847
+ return hexlify(payload);
1848
+ }
1849
+ var interopCodec = {
1850
+ formatChain: formatInteropEvmChain,
1851
+ formatAddress: formatInteropEvmAddress
1852
+ };
1853
+ function getInteropAttributes(params, ctx) {
1854
+ const bundleAttributes = [];
1855
+ if (params.execution?.only) {
1856
+ bundleAttributes.push(ctx.attributes.bundle.executionAddress(params.execution.only));
1857
+ }
1858
+ if (params.unbundling?.by) {
1859
+ bundleAttributes.push(ctx.attributes.bundle.unbundlerAddress(params.unbundling.by));
1860
+ }
1861
+ bundleAttributes.push(ctx.attributes.bundle.useFixedFee(params.fee?.useFixed ?? false));
1862
+ const callAttributes = params.actions.map((action) => {
1863
+ switch (action.type) {
1864
+ case "sendNative": {
1865
+ const baseMatches = ctx.baseTokens.src.toLowerCase() === ctx.baseTokens.dst.toLowerCase();
1866
+ if (baseMatches) {
1867
+ return [ctx.attributes.call.interopCallValue(action.amount)];
1868
+ }
1869
+ return [ctx.attributes.call.indirectCall(action.amount)];
1870
+ }
1871
+ case "call":
1872
+ if (action.value && action.value > 0n) {
1873
+ return [ctx.attributes.call.interopCallValue(action.value)];
1874
+ }
1875
+ return [];
1876
+ case "sendErc20":
1877
+ return [ctx.attributes.call.indirectCall(0n)];
1878
+ default:
1879
+ assertNever(action);
1880
+ }
1881
+ });
1882
+ return { bundleAttributes, callAttributes };
1883
+ }
1884
+ function createEthersAttributesResource(opts = {}) {
1885
+ const iface = opts.iface ?? new Interface(IERC7786Attributes_default);
1886
+ const encode2 = (fn, args) => iface.encodeFunctionData(fn, args);
1887
+ return createAttributesResource({ encode: encode2 });
1888
+ }
1889
+
1890
+ // src/adapters/ethers/resources/withdrawals/routes/interop-bundle.ts
1829
1891
  var { wrapAs: wrapAs8 } = createErrorHandlers("withdrawals");
1830
- var IL1NullifierMini = [
1831
- "function isWithdrawalFinalized(uint256,uint256,uint256) view returns (bool)"
1832
- ];
1833
- function createFinalizationServices(client) {
1834
- const { l1, l2, signer } = client;
1892
+ var attributes = createEthersAttributesResource();
1893
+ function saltFor(sender, nonce) {
1894
+ return keccak256(
1895
+ AbiCoder.defaultAbiCoder().encode(["address", "uint256"], [sender, BigInt(nonce)])
1896
+ );
1897
+ }
1898
+ function routeInteropBundle() {
1835
1899
  return {
1836
- async fetchFinalizeDepositParams(l2TxHash) {
1837
- const parsed = await wrapAs8(
1838
- "RPC",
1839
- OP_WITHDRAWALS.finalize.fetchParams.receipt,
1840
- () => client.zks.getReceiptWithL2ToL1(l2TxHash),
1841
- {
1842
- ctx: { where: "getReceiptWithL2ToL1", l2TxHash },
1843
- message: "Failed to fetch L2 receipt (with L2\u2192L1 logs)."
1900
+ async build(p, ctx) {
1901
+ const steps = [];
1902
+ const approvals = [];
1903
+ const isBaseToken = ctx.route === "base";
1904
+ const l1Receiver = p.to ?? ctx.sender;
1905
+ let assetId;
1906
+ let allowanceSufficient = true;
1907
+ if (isBaseToken) {
1908
+ assetId = ctx.baseTokenAssetId;
1909
+ } else {
1910
+ assetId = await wrapAs8(
1911
+ "CONTRACT",
1912
+ OP_WITHDRAWALS.erc20.ensureRegistered,
1913
+ async () => {
1914
+ const ntv = await ctx.contracts.l2NativeTokenVault();
1915
+ return await ntv.getFunction("ensureTokenIsRegistered").staticCall(p.token);
1916
+ },
1917
+ {
1918
+ ctx: { where: "L2NativeTokenVault.ensureTokenIsRegistered", token: p.token },
1919
+ message: "Failed to ensure token is registered in L2NativeTokenVault."
1920
+ }
1921
+ );
1922
+ const erc20 = new Contract(p.token, IERC20_default, ctx.client.l2);
1923
+ const current = await wrapAs8(
1924
+ "CONTRACT",
1925
+ OP_WITHDRAWALS.erc20.allowance,
1926
+ () => erc20.allowance(ctx.sender, ctx.l2NativeTokenVault),
1927
+ {
1928
+ ctx: {
1929
+ where: "erc20.allowance",
1930
+ chain: "L2",
1931
+ token: p.token,
1932
+ spender: ctx.l2NativeTokenVault
1933
+ },
1934
+ message: "Failed to read L2 ERC-20 allowance."
1935
+ }
1936
+ );
1937
+ allowanceSufficient = current >= p.amount;
1938
+ if (!allowanceSufficient) {
1939
+ approvals.push({ token: p.token, spender: ctx.l2NativeTokenVault, amount: p.amount });
1940
+ const approveTx = {
1941
+ to: p.token,
1942
+ data: erc20.interface.encodeFunctionData("approve", [ctx.l2NativeTokenVault, p.amount]),
1943
+ from: ctx.sender
1944
+ };
1945
+ const approveGas = await quoteL2Gas4({ ctx, tx: approveTx });
1946
+ if (approveGas) {
1947
+ approveTx.gasLimit = approveGas.gasLimit;
1948
+ approveTx.maxFeePerGas = approveGas.maxFeePerGas;
1949
+ approveTx.maxPriorityFeePerGas = approveGas.maxPriorityFeePerGas;
1950
+ }
1951
+ steps.push({
1952
+ key: `approve:l2:${p.token}:${ctx.l2NativeTokenVault}`,
1953
+ kind: "approve:l2",
1954
+ description: `Approve ${p.amount} to NativeTokenVault`,
1955
+ tx: approveTx
1956
+ });
1844
1957
  }
1845
- );
1846
- if (!parsed) {
1847
- throw createError("STATE", {
1848
- resource: "withdrawals",
1849
- operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
1850
- message: "L2 receipt not found.",
1851
- context: { l2TxHash }
1852
- });
1853
1958
  }
1854
- const ev = await wrapAs8(
1855
- "INTERNAL",
1856
- OP_WITHDRAWALS.finalize.fetchParams.findMessage,
1857
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
1858
- () => Promise.resolve(findL1MessageSentLog(parsed, { index: 0 })),
1959
+ const nonce = await wrapAs8(
1960
+ "RPC",
1961
+ OP_WITHDRAWALS.prepare,
1962
+ () => ctx.client.l2.getTransactionCount(ctx.sender, "pending"),
1859
1963
  {
1860
- ctx: { l2TxHash, index: 0 },
1861
- message: "Failed to locate L1MessageSent event in L2 receipt."
1964
+ ctx: { where: "l2.getTransactionCount", sender: ctx.sender },
1965
+ message: "Failed to read L2 nonce for the interop bundle salt."
1862
1966
  }
1863
1967
  );
1864
- const message = await wrapAs8(
1968
+ const bundle = buildWithdrawalBundle({
1969
+ assetId,
1970
+ amount: p.amount,
1971
+ l1Receiver,
1972
+ l2Token: isBaseToken ? FORMAL_ETH_ADDRESS : p.token,
1973
+ isBaseToken,
1974
+ l1ChainId: ctx.l1ChainId,
1975
+ l2AssetRouter: ctx.l2AssetRouter,
1976
+ salt: saltFor(ctx.sender, nonce),
1977
+ codec: interopCodec,
1978
+ attributes: {
1979
+ indirectCall: attributes.call.indirectCall,
1980
+ interopCallValue: attributes.call.interopCallValue,
1981
+ interopBundleSalt: attributes.bundle.interopBundleSalt
1982
+ },
1983
+ transferData: {
1984
+ encodeBridgeBurnData: (amount, receiver, token) => encodeNativeTokenVaultTransferData(amount, receiver, token),
1985
+ encodeAssetRouterDepositData: (id, data2) => encodeSecondBridgeDataV1(id, data2)
1986
+ }
1987
+ });
1988
+ const interopCenter = await ctx.contracts.interopCenter();
1989
+ const data = await wrapAs8(
1865
1990
  "INTERNAL",
1866
- OP_WITHDRAWALS.finalize.fetchParams.decodeMessage,
1867
- () => Promise.resolve(AbiCoder.defaultAbiCoder().decode(["bytes"], ev.data)[0]),
1991
+ OP_WITHDRAWALS.erc20.encodeWithdraw,
1992
+ () => Promise.resolve(
1993
+ interopCenter.interface.encodeFunctionData("sendBundle", [
1994
+ bundle.destinationChain,
1995
+ bundle.starters,
1996
+ bundle.bundleAttributes
1997
+ ])
1998
+ ),
1868
1999
  {
1869
- ctx: { where: "decode L1MessageSent", data: ev.data },
1870
- message: "Failed to decode withdrawal message."
2000
+ ctx: { where: "InteropCenter.sendBundle", assetId },
2001
+ message: "Failed to encode sendBundle calldata."
1871
2002
  }
1872
2003
  );
1873
- const raw = await wrapAs8(
1874
- "RPC",
1875
- OP_WITHDRAWALS.finalize.fetchParams.rawReceipt,
1876
- () => client.zks.getReceiptWithL2ToL1(l2TxHash),
1877
- {
1878
- ctx: { where: "getReceiptWithL2ToL1 (raw)", l2TxHash },
1879
- message: "Failed to fetch raw L2 receipt."
2004
+ const sendTx = {
2005
+ to: ctx.interopCenter,
2006
+ data,
2007
+ from: ctx.sender,
2008
+ value: bundle.value
2009
+ };
2010
+ const sendGas = allowanceSufficient ? await quoteL2Gas4({ ctx, tx: sendTx }) : void 0;
2011
+ if (sendGas) {
2012
+ sendTx.gasLimit = sendGas.gasLimit;
2013
+ sendTx.maxFeePerGas = sendGas.maxFeePerGas;
2014
+ sendTx.maxPriorityFeePerGas = sendGas.maxPriorityFeePerGas;
2015
+ }
2016
+ steps.push({
2017
+ key: "interop-center:send-bundle",
2018
+ kind: "interop-center:send-bundle",
2019
+ description: "Burn on L2 & send L2\u2192L1 withdrawal bundle",
2020
+ tx: sendTx
2021
+ });
2022
+ const fees = buildFeeBreakdown2({
2023
+ feeToken: ctx.baseTokenL1 ?? await ctx.client.baseToken(ctx.chainIdL2),
2024
+ l2Gas: sendGas
2025
+ });
2026
+ return { steps, approvals, fees };
2027
+ }
2028
+ };
2029
+ }
2030
+
2031
+ // src/adapters/ethers/resources/withdrawals/services/protocol.ts
2032
+ function createWithdrawalProtocolService(client, override) {
2033
+ let cached;
2034
+ async function hasCodeAt(address) {
2035
+ try {
2036
+ const code = await client.l2.getCode(address);
2037
+ return !!code && code !== "0x";
2038
+ } catch {
2039
+ return false;
2040
+ }
2041
+ }
2042
+ async function protocolVersion() {
2043
+ try {
2044
+ return await client.getChainProtocolVersion();
2045
+ } catch {
2046
+ return void 0;
2047
+ }
2048
+ }
2049
+ function detect() {
2050
+ cached ??= detectWithdrawalProtocol(
2051
+ {
2052
+ protocolVersion,
2053
+ hasCodeAt
2054
+ },
2055
+ override
2056
+ ).catch((e) => {
2057
+ cached = void 0;
2058
+ throw e;
2059
+ });
2060
+ return cached;
2061
+ }
2062
+ return {
2063
+ detect,
2064
+ async protocol() {
2065
+ return (await detect()).protocol;
2066
+ },
2067
+ refresh() {
2068
+ cached = void 0;
2069
+ }
2070
+ };
2071
+ }
2072
+
2073
+ // src/adapters/ethers/resources/withdrawals/services/finalization.ts
2074
+ var { wrapAs: wrapAs9 } = createErrorHandlers("withdrawals");
2075
+ var IL1NullifierMini = [
2076
+ "function isWithdrawalFinalized(uint256,uint256,uint256) view returns (bool)"
2077
+ ];
2078
+ function createFinalizationServices(client, protocolService = createWithdrawalProtocolService(client)) {
2079
+ const { l1, l2, signer } = client;
2080
+ async function finalizationTarget(protocol) {
2081
+ const { l1Nullifier } = await client.ensureAddresses();
2082
+ if (protocol === "legacy-withdrawal") return l1Nullifier;
2083
+ const nullifier = new Contract(l1Nullifier, IL1NullifierV32_default, l1);
2084
+ const handler = await wrapAs9(
2085
+ "CONTRACT",
2086
+ OP_WITHDRAWALS.finalize.fetchParams.receipt,
2087
+ () => nullifier.l1InteropHandler(),
2088
+ {
2089
+ ctx: { where: "L1Nullifier.l1InteropHandler", l1Nullifier },
2090
+ message: "Failed to resolve the L1 interop handler. The chain reports protocol v32+, but its L1Nullifier does not expose `l1InteropHandler()`."
2091
+ }
2092
+ );
2093
+ return handler;
2094
+ }
2095
+ async function fetchMessageAndProof(l2TxHash) {
2096
+ const raw = await wrapAs9(
2097
+ "RPC",
2098
+ OP_WITHDRAWALS.finalize.fetchParams.receipt,
2099
+ () => client.zks.getReceiptWithL2ToL1(l2TxHash),
2100
+ {
2101
+ ctx: { where: "getReceiptWithL2ToL1", l2TxHash },
2102
+ message: "Failed to fetch L2 receipt (with L2\u2192L1 logs)."
2103
+ }
2104
+ );
2105
+ if (!raw) {
2106
+ throw createError("STATE", {
2107
+ resource: "withdrawals",
2108
+ operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
2109
+ message: "L2 receipt not found.",
2110
+ context: { l2TxHash }
2111
+ });
2112
+ }
2113
+ const ev = await wrapAs9(
2114
+ "INTERNAL",
2115
+ OP_WITHDRAWALS.finalize.fetchParams.findMessage,
2116
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
2117
+ () => Promise.resolve(findL1MessageSentLog(raw, { index: 0 })),
2118
+ {
2119
+ ctx: { l2TxHash, index: 0 },
2120
+ message: "Failed to locate L1MessageSent event in L2 receipt."
2121
+ }
2122
+ );
2123
+ const message = await wrapAs9(
2124
+ "INTERNAL",
2125
+ OP_WITHDRAWALS.finalize.fetchParams.decodeMessage,
2126
+ () => Promise.resolve(AbiCoder.defaultAbiCoder().decode(["bytes"], ev.data)[0]),
2127
+ {
2128
+ ctx: { where: "decode L1MessageSent", data: ev.data },
2129
+ message: "Failed to decode withdrawal message."
2130
+ }
2131
+ );
2132
+ const idx = await wrapAs9(
2133
+ "INTERNAL",
2134
+ OP_WITHDRAWALS.finalize.fetchParams.messengerIndex,
2135
+ () => Promise.resolve(messengerLogIndex(raw, { index: 0, messenger: L1_MESSENGER_ADDRESS })),
2136
+ {
2137
+ ctx: { where: "derive messenger log index", l2TxHash, receipt: raw },
2138
+ message: "Failed to derive messenger log index."
2139
+ }
2140
+ );
2141
+ const proof = await wrapAs9(
2142
+ "RPC",
2143
+ OP_WITHDRAWALS.finalize.fetchParams.proof,
2144
+ () => client.zks.getL2ToL1LogProof(l2TxHash, idx),
2145
+ {
2146
+ ctx: { where: "get L2\u2192L1 log proof", l2TxHash, messengerLogIndex: idx },
2147
+ message: "Failed to fetch L2\u2192L1 log proof."
2148
+ }
2149
+ );
2150
+ const { chainId } = await wrapAs9(
2151
+ "RPC",
2152
+ OP_WITHDRAWALS.finalize.fetchParams.network,
2153
+ () => l2.getNetwork(),
2154
+ { ctx: { where: "l2.getNetwork" }, message: "Failed to read L2 network." }
2155
+ );
2156
+ const txNumberInBatch = Number(raw.transactionIndex ?? 0);
2157
+ const l2Sender = l1MessageSentSender(ev);
2158
+ return { raw, message, proof, chainId: BigInt(chainId), txNumberInBatch, l2Sender };
2159
+ }
2160
+ async function fetchFinalization(l2TxHash) {
2161
+ const protocol = await protocolService.protocol();
2162
+ const { raw, message, proof, chainId, txNumberInBatch, l2Sender } = await fetchMessageAndProof(l2TxHash);
2163
+ const target = await finalizationTarget(protocol);
2164
+ if (protocol === "legacy-withdrawal") {
2165
+ const params2 = {
2166
+ chainId,
2167
+ l2BatchNumber: proof.batchNumber,
2168
+ l2MessageIndex: proof.id,
2169
+ l2Sender,
2170
+ l2TxNumberInBatch: txNumberInBatch,
2171
+ message,
2172
+ merkleProof: proof.proof
2173
+ };
2174
+ return {
2175
+ target,
2176
+ finalization: { protocol, params: params2 },
2177
+ key: {
2178
+ chainIdL2: chainId,
2179
+ l2BatchNumber: proof.batchNumber,
2180
+ l2MessageIndex: proof.id
1880
2181
  }
1881
- );
1882
- if (!raw) {
1883
- throw createError("STATE", {
1884
- resource: "withdrawals",
1885
- operation: OP_WITHDRAWALS.finalize.fetchParams.rawReceipt,
1886
- message: "Raw L2 receipt not found.",
1887
- context: { l2TxHash }
1888
- });
2182
+ };
2183
+ }
2184
+ const { interopCenter } = await client.ensureAddresses();
2185
+ const params = buildWithdrawalFinalization({
2186
+ messageData: message,
2187
+ sourceChainId: chainId,
2188
+ txNumberInBatch,
2189
+ proof: { batchNumber: proof.batchNumber, id: proof.id, proof: proof.proof },
2190
+ // Prefer the hash the InteropCenter emitted over recomputing it.
2191
+ bundleHash: parseBundleHashFromLogs(raw.logs ?? [], interopCenter),
2192
+ interopCenter
2193
+ });
2194
+ return {
2195
+ target,
2196
+ finalization: { protocol, params },
2197
+ key: {
2198
+ chainIdL2: chainId,
2199
+ l2BatchNumber: proof.batchNumber,
2200
+ l2MessageIndex: proof.id,
2201
+ bundleHash: params.bundleHash
1889
2202
  }
1890
- const idx = await wrapAs8(
1891
- "INTERNAL",
1892
- OP_WITHDRAWALS.finalize.fetchParams.messengerIndex,
1893
- () => Promise.resolve(messengerLogIndex(raw, { index: 0, messenger: L1_MESSENGER_ADDRESS })),
2203
+ };
2204
+ }
2205
+ async function withdrawalOutcome(finalization) {
2206
+ const target = await finalizationTarget(finalization.protocol);
2207
+ if (finalization.protocol === "legacy-withdrawal") {
2208
+ const c = new Contract(target, IL1NullifierMini, l1);
2209
+ const done = await wrapAs9(
2210
+ "RPC",
2211
+ OP_WITHDRAWALS.finalize.isFinalized,
2212
+ () => c.isWithdrawalFinalized(
2213
+ finalization.params.chainId,
2214
+ finalization.params.l2BatchNumber,
2215
+ finalization.params.l2MessageIndex
2216
+ ),
1894
2217
  {
1895
- ctx: { where: "derive messenger log index", l2TxHash, receipt: raw },
1896
- message: "Failed to derive messenger log index."
2218
+ ctx: { where: "isWithdrawalFinalized", params: finalization.params },
2219
+ message: "Failed to read finalization status."
1897
2220
  }
1898
2221
  );
1899
- const proof = await wrapAs8(
2222
+ return done ? "finalized" : "pending";
2223
+ }
2224
+ const { bundleHash } = finalization.params;
2225
+ const handler = new Contract(target, IInteropHandler_default, l1);
2226
+ const status = Number(
2227
+ await wrapAs9(
1900
2228
  "RPC",
1901
- OP_WITHDRAWALS.finalize.fetchParams.proof,
1902
- () => client.zks.getL2ToL1LogProof(l2TxHash, idx),
2229
+ OP_WITHDRAWALS.finalize.isFinalized,
2230
+ () => handler.bundleStatus(bundleHash),
1903
2231
  {
1904
- ctx: { where: "get L2\u2192L1 log proof", l2TxHash, messengerLogIndex: idx },
1905
- message: "Failed to fetch L2\u2192L1 log proof."
2232
+ ctx: { where: "L1InteropHandler.bundleStatus", bundleHash },
2233
+ message: "Failed to read bundle status."
1906
2234
  }
1907
- );
1908
- const { chainId } = await wrapAs8(
2235
+ )
2236
+ );
2237
+ if (status !== 3 /* Unbundled */) return classifyWithdrawalOutcome(status);
2238
+ const callStatus = Number(
2239
+ await wrapAs9(
1909
2240
  "RPC",
1910
- OP_WITHDRAWALS.finalize.fetchParams.network,
1911
- () => l2.getNetwork(),
2241
+ OP_WITHDRAWALS.finalize.isFinalized,
2242
+ () => handler.callStatus(bundleHash, 0),
1912
2243
  {
1913
- ctx: { where: "l2.getNetwork" },
1914
- message: "Failed to read L2 network."
2244
+ ctx: { where: "L1InteropHandler.callStatus", bundleHash },
2245
+ message: "Failed to read bundle call status."
1915
2246
  }
1916
- );
1917
- const txIndex = Number(parsed.transactionIndex ?? 0);
1918
- const params = {
1919
- chainId: BigInt(chainId),
1920
- l2BatchNumber: proof.batchNumber,
1921
- l2MessageIndex: proof.id,
1922
- l2Sender: parsed.to,
1923
- l2TxNumberInBatch: txIndex,
1924
- message,
1925
- merkleProof: proof.proof
1926
- };
1927
- const { l1Nullifier } = await client.ensureAddresses();
1928
- return { params, nullifier: l1Nullifier };
2247
+ )
2248
+ );
2249
+ return classifyWithdrawalOutcome(status, callStatus);
2250
+ }
2251
+ async function isWithdrawalFinalized(finalization) {
2252
+ return await withdrawalOutcome(finalization) === "finalized";
2253
+ }
2254
+ return {
2255
+ fetchFinalization,
2256
+ isWithdrawalFinalized,
2257
+ withdrawalOutcome,
2258
+ async fetchFinalizeDepositParams(l2TxHash) {
2259
+ const resolved = await fetchFinalization(l2TxHash);
2260
+ if (resolved.finalization.protocol !== "legacy-withdrawal") {
2261
+ throw createError("VALIDATION", {
2262
+ resource: "withdrawals",
2263
+ operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
2264
+ message: "This chain finalizes withdrawals through the L1 interop handler; `finalizeDeposit` params do not exist. Use `fetchFinalization` instead.",
2265
+ context: { l2TxHash, protocol: resolved.finalization.protocol }
2266
+ });
2267
+ }
2268
+ return { params: resolved.finalization.params, nullifier: resolved.target };
1929
2269
  },
1930
- async simulateFinalizeReadiness(params) {
1931
- const { l1Nullifier } = await client.ensureAddresses();
2270
+ async simulateFinalizeReadiness(finalization) {
2271
+ const target = await finalizationTarget(finalization.protocol);
1932
2272
  const done = await (async () => {
1933
2273
  try {
1934
- const cMini = new Contract(l1Nullifier, IL1NullifierMini, l1);
1935
- const isFinalized = await wrapAs8(
1936
- "RPC",
1937
- OP_WITHDRAWALS.finalize.readiness.isFinalized,
1938
- () => cMini.isWithdrawalFinalized(
1939
- params.chainId,
1940
- params.l2BatchNumber,
1941
- params.l2MessageIndex
1942
- ),
1943
- {
1944
- ctx: { where: "isWithdrawalFinalized", params },
1945
- message: "Failed to read finalization status."
1946
- }
1947
- );
1948
- return Boolean(isFinalized);
2274
+ return await isWithdrawalFinalized(finalization);
1949
2275
  } catch {
1950
2276
  return false;
1951
2277
  }
1952
2278
  })();
1953
2279
  if (done) return { kind: "FINALIZED" };
1954
- const c = new Contract(l1Nullifier, IL1Nullifier_default, l1);
1955
2280
  try {
1956
- await c.finalizeDeposit.staticCall(params);
2281
+ if (finalization.protocol === "legacy-withdrawal") {
2282
+ const c = new Contract(target, IL1Nullifier_default, l1);
2283
+ await c.finalizeDeposit.staticCall(finalization.params);
2284
+ } else {
2285
+ const handler = new Contract(target, IInteropHandler_default, l1);
2286
+ await handler.executeBundle.staticCall(
2287
+ finalization.params.bundle,
2288
+ finalization.params.proof
2289
+ );
2290
+ }
1957
2291
  return { kind: "READY" };
1958
2292
  } catch (e) {
1959
2293
  return classifyReadinessFromRevert(e);
1960
2294
  }
1961
2295
  },
1962
- async isWithdrawalFinalized(key) {
1963
- const { l1Nullifier } = await client.ensureAddresses();
1964
- const c = new Contract(l1Nullifier, IL1NullifierMini, l1);
1965
- return await wrapAs8(
1966
- "RPC",
1967
- OP_WITHDRAWALS.finalize.isFinalized,
1968
- () => c.isWithdrawalFinalized(key.chainIdL2, key.l2BatchNumber, key.l2MessageIndex),
1969
- {
1970
- ctx: { where: "isWithdrawalFinalized", key },
1971
- message: "Failed to read finalization status."
1972
- }
1973
- );
1974
- },
1975
- async estimateFinalization(params) {
1976
- const { l1Nullifier } = await client.ensureAddresses();
1977
- const signer2 = client.getL1Signer();
1978
- const c = new Contract(l1Nullifier, IL1Nullifier_default, signer2);
1979
- const gasLimit = await wrapAs8(
2296
+ async estimateFinalization(finalization) {
2297
+ const target = await finalizationTarget(finalization.protocol);
2298
+ const l1Signer = client.getL1Signer();
2299
+ const gasLimit = await wrapAs9(
1980
2300
  "RPC",
1981
2301
  OP_WITHDRAWALS.finalize.estimate,
1982
- () => c.finalizeDeposit.estimateGas(params),
2302
+ () => {
2303
+ if (finalization.protocol === "legacy-withdrawal") {
2304
+ const c = new Contract(target, IL1Nullifier_default, l1Signer);
2305
+ return c.finalizeDeposit.estimateGas(finalization.params);
2306
+ }
2307
+ const handler = new Contract(target, IInteropHandler_default, l1Signer);
2308
+ return handler.executeBundle.estimateGas(
2309
+ finalization.params.bundle,
2310
+ finalization.params.proof
2311
+ );
2312
+ },
1983
2313
  {
1984
- ctx: {
1985
- where: "estimateGas(finalizeDeposit)",
1986
- chainIdL2: params.chainId,
1987
- l2BatchNumber: params.l2BatchNumber,
1988
- l2MessageIndex: params.l2MessageIndex,
1989
- l1Nullifier
1990
- },
1991
- message: "Failed to estimate gas for finalizeDeposit."
2314
+ ctx: { where: "estimateGas(finalize)", protocol: finalization.protocol, target },
2315
+ message: "Failed to estimate gas for withdrawal finalization."
1992
2316
  }
1993
2317
  );
1994
- const feeData = await wrapAs8("RPC", OP_WITHDRAWALS.finalize.estimate, () => l1.getFeeData(), {
2318
+ const feeData = await wrapAs9("RPC", OP_WITHDRAWALS.finalize.estimate, () => l1.getFeeData(), {
1995
2319
  ctx: { where: "l1.getFeeData" },
1996
- message: "Failed to estimate fee data for finalizeDeposit."
2320
+ message: "Failed to estimate fee data for withdrawal finalization."
1997
2321
  });
1998
2322
  const maxFeePerGas = feeData.maxFeePerGas ?? feeData.gasPrice ?? // legacy-style gas price if present
1999
2323
  (() => {
@@ -2004,33 +2328,49 @@ function createFinalizationServices(client) {
2004
2328
  context: { feeData }
2005
2329
  });
2006
2330
  })();
2007
- const maxPriorityFeePerGas = feeData.maxPriorityFeePerGas ?? 0n;
2008
2331
  return {
2009
2332
  gasLimit,
2010
2333
  maxFeePerGas,
2011
- maxPriorityFeePerGas
2334
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ?? 0n
2012
2335
  };
2013
2336
  },
2014
- async finalizeDeposit(params) {
2015
- const { l1Nullifier } = await client.ensureAddresses();
2016
- const c = new Contract(l1Nullifier, IL1Nullifier_default, signer);
2337
+ async finalize(finalization) {
2338
+ const target = await finalizationTarget(finalization.protocol);
2017
2339
  try {
2018
- const receipt = await c.finalizeDeposit(params);
2019
- const hash = receipt.hash;
2340
+ const sent = await (async () => {
2341
+ if (finalization.protocol === "legacy-withdrawal") {
2342
+ const c = new Contract(target, IL1Nullifier_default, signer);
2343
+ return await c.finalizeDeposit(finalization.params);
2344
+ }
2345
+ const handler = new Contract(target, IInteropHandler_default, signer);
2346
+ return await handler.executeBundle(
2347
+ finalization.params.bundle,
2348
+ finalization.params.proof
2349
+ );
2350
+ })();
2351
+ const hash = sent.hash;
2020
2352
  return {
2021
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
2022
2353
  hash,
2023
2354
  wait: async () => {
2024
2355
  try {
2025
- return await receipt.wait();
2356
+ const receipt = await sent.wait();
2357
+ if (!receipt) {
2358
+ throw createError("EXECUTION", {
2359
+ resource: "withdrawals",
2360
+ operation: OP_WITHDRAWALS.finalize.wait,
2361
+ message: "Withdrawal finalization transaction produced no receipt.",
2362
+ context: { txHash: hash, protocol: finalization.protocol }
2363
+ });
2364
+ }
2365
+ return receipt;
2026
2366
  } catch (e) {
2027
2367
  throw toZKsyncError(
2028
2368
  "EXECUTION",
2029
2369
  {
2030
2370
  resource: "withdrawals",
2031
2371
  operation: OP_WITHDRAWALS.finalize.wait,
2032
- message: "Failed while waiting for finalizeDeposit transaction.",
2033
- context: { txHash: hash }
2372
+ message: "Failed while waiting for the withdrawal finalization transaction.",
2373
+ context: { txHash: hash, protocol: finalization.protocol }
2034
2374
  },
2035
2375
  e
2036
2376
  );
@@ -2043,13 +2383,8 @@ function createFinalizationServices(client) {
2043
2383
  {
2044
2384
  resource: "withdrawals",
2045
2385
  operation: OP_WITHDRAWALS.finalize.send,
2046
- message: "Failed to send finalizeDeposit transaction.",
2047
- context: {
2048
- chainIdL2: params.chainId,
2049
- l2BatchNumber: params.l2BatchNumber,
2050
- l2MessageIndex: params.l2MessageIndex,
2051
- l1Nullifier
2052
- }
2386
+ message: "Failed to send the withdrawal finalization transaction.",
2387
+ context: { protocol: finalization.protocol, target }
2053
2388
  },
2054
2389
  e
2055
2390
  );
@@ -2065,15 +2400,28 @@ var ROUTES2 = {
2065
2400
  "erc20-nonbase": routeErc20NonBase2()
2066
2401
  // AssetRouter.withdraw for non-base ERC-20s
2067
2402
  };
2068
- function createWithdrawalsResource(client, tokens, contracts) {
2069
- const svc = createFinalizationServices(client);
2403
+ var INTEROP_ROUTES = {
2404
+ base: routeInteropBundle(),
2405
+ "erc20-nonbase": routeInteropBundle()
2406
+ };
2407
+ function routeStrategy(protocol, route) {
2408
+ return protocol === "interop-bundle" ? INTEROP_ROUTES[route] : ROUTES2[route];
2409
+ }
2410
+ function createWithdrawalsResource(client, tokens, contracts, options) {
2411
+ const protocolService = createWithdrawalProtocolService(
2412
+ client,
2413
+ options?.protocol
2414
+ );
2415
+ const svc = createFinalizationServices(client, protocolService);
2070
2416
  const { wrap: wrap7, toResult: toResult3 } = createErrorHandlers("withdrawals");
2071
2417
  const tokensResource = tokens ?? createTokensResource(client);
2072
2418
  const contractsResource = contracts ?? createContractsResource(client);
2073
2419
  async function buildPlan(p) {
2074
- const ctx = await commonCtx2(p, client, tokensResource, contractsResource);
2075
- await ROUTES2[ctx.route].preflight?.(p, ctx);
2076
- const { steps, approvals, fees } = await ROUTES2[ctx.route].build(p, ctx);
2420
+ const protocol = await protocolService.protocol();
2421
+ const ctx = await commonCtx2(p, client, tokensResource, contractsResource, protocol);
2422
+ const strategy = routeStrategy(protocol, ctx.route);
2423
+ await strategy.preflight?.(p, ctx);
2424
+ const { steps, approvals, fees } = await strategy.build(p, ctx);
2077
2425
  return {
2078
2426
  route: ctx.route,
2079
2427
  summary: {
@@ -2217,24 +2565,22 @@ function createWithdrawalsResource(client, tokens, contracts) {
2217
2565
  if (!l2Rcpt) return { phase: "L2_PENDING", l2TxHash };
2218
2566
  let pack;
2219
2567
  try {
2220
- pack = await svc.fetchFinalizeDepositParams(l2TxHash);
2568
+ pack = await svc.fetchFinalization(l2TxHash);
2221
2569
  } catch {
2222
2570
  return { phase: "PENDING", l2TxHash };
2223
2571
  }
2224
- const key = {
2225
- chainIdL2: pack.params.chainId,
2226
- l2BatchNumber: pack.params.l2BatchNumber,
2227
- l2MessageIndex: pack.params.l2MessageIndex
2228
- };
2572
+ const key = pack.key;
2229
2573
  try {
2230
- const done = await svc.isWithdrawalFinalized(key);
2231
- if (done) return { phase: "FINALIZED", l2TxHash, key };
2574
+ const outcome = await svc.withdrawalOutcome(pack.finalization);
2575
+ if (outcome === "finalized") return { phase: "FINALIZED", l2TxHash, key };
2576
+ if (outcome === "failed") {
2577
+ return { phase: "UNFINALIZABLE", l2TxHash, key, reason: "bundle-cancelled" };
2578
+ }
2232
2579
  } catch {
2233
2580
  }
2234
- const readiness = await svc.simulateFinalizeReadiness(pack.params);
2235
- if (readiness.kind === "FINALIZED") return { phase: "FINALIZED", l2TxHash, key };
2236
- if (readiness.kind === "READY") return { phase: "READY_TO_FINALIZE", l2TxHash, key };
2237
- return { phase: "PENDING", l2TxHash, key };
2581
+ const readiness = await svc.simulateFinalizeReadiness(pack.finalization);
2582
+ const { phase, reason } = phaseFromReadiness(readiness);
2583
+ return { phase, reason, l2TxHash, key };
2238
2584
  },
2239
2585
  {
2240
2586
  message: "Internal error while checking withdrawal status.",
@@ -2278,6 +2624,14 @@ function createWithdrawalsResource(client, tokens, contracts) {
2278
2624
  const deadline = opts.timeoutMs ? Date.now() + opts.timeoutMs : void 0;
2279
2625
  while (true) {
2280
2626
  const s = await status(l2Hash);
2627
+ if (s.phase === "UNFINALIZABLE") {
2628
+ throw createError("STATE", {
2629
+ resource: "withdrawals",
2630
+ operation: OP_WITHDRAWALS.wait,
2631
+ message: "Withdrawal can never be finalized.",
2632
+ context: { l2TxHash: l2Hash, reason: s.reason }
2633
+ });
2634
+ }
2281
2635
  if (opts.for === "ready") {
2282
2636
  if (s.phase === "READY_TO_FINALIZE" || s.phase === "FINALIZED") return null;
2283
2637
  } else {
@@ -2314,7 +2668,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
2314
2668
  async () => {
2315
2669
  const pack = await (async () => {
2316
2670
  try {
2317
- return await svc.fetchFinalizeDepositParams(l2TxHash);
2671
+ return await svc.fetchFinalization(l2TxHash);
2318
2672
  } catch (e) {
2319
2673
  throw createError("STATE", {
2320
2674
  resource: "withdrawals",
@@ -2325,21 +2679,16 @@ function createWithdrawalsResource(client, tokens, contracts) {
2325
2679
  });
2326
2680
  }
2327
2681
  })();
2328
- const { params } = pack;
2329
- const key = {
2330
- chainIdL2: params.chainId,
2331
- l2BatchNumber: params.l2BatchNumber,
2332
- l2MessageIndex: params.l2MessageIndex
2333
- };
2682
+ const { finalization } = pack;
2334
2683
  try {
2335
- const done = await svc.isWithdrawalFinalized(key);
2336
- if (done) {
2684
+ const outcome = await svc.withdrawalOutcome(finalization);
2685
+ if (outcome === "finalized" || outcome === "failed") {
2337
2686
  const statusNow = await status(l2TxHash);
2338
2687
  return { status: statusNow };
2339
2688
  }
2340
2689
  } catch {
2341
2690
  }
2342
- const readiness = await svc.simulateFinalizeReadiness(params);
2691
+ const readiness = await svc.simulateFinalizeReadiness(finalization);
2343
2692
  if (readiness.kind === "FINALIZED") {
2344
2693
  const statusNow = await status(l2TxHash);
2345
2694
  return { status: statusNow };
@@ -2353,7 +2702,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
2353
2702
  });
2354
2703
  }
2355
2704
  try {
2356
- const tx = await svc.finalizeDeposit(params);
2705
+ const tx = await svc.finalize(finalization);
2357
2706
  finalizeCache.set(l2TxHash, tx.hash);
2358
2707
  const rcpt = await tx.wait();
2359
2708
  const statusNow = await status(l2TxHash);
@@ -2362,7 +2711,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
2362
2711
  const statusNow = await status(l2TxHash);
2363
2712
  if (statusNow.phase === "FINALIZED") return { status: statusNow };
2364
2713
  try {
2365
- const again = await svc.simulateFinalizeReadiness(params);
2714
+ const again = await svc.simulateFinalizeReadiness(finalization);
2366
2715
  if (again.kind === "NOT_READY") {
2367
2716
  throw createError("STATE", {
2368
2717
  resource: "withdrawals",
@@ -2420,60 +2769,6 @@ function createWithdrawalsResource(client, tokens, contracts) {
2420
2769
  tryWait
2421
2770
  };
2422
2771
  }
2423
- function getInteropAttributes(params, ctx) {
2424
- const bundleAttributes = [];
2425
- if (params.execution?.only) {
2426
- bundleAttributes.push(ctx.attributes.bundle.executionAddress(params.execution.only));
2427
- }
2428
- if (params.unbundling?.by) {
2429
- bundleAttributes.push(ctx.attributes.bundle.unbundlerAddress(params.unbundling.by));
2430
- }
2431
- bundleAttributes.push(ctx.attributes.bundle.useFixedFee(params.fee?.useFixed ?? false));
2432
- const callAttributes = params.actions.map((action) => {
2433
- switch (action.type) {
2434
- case "sendNative": {
2435
- const baseMatches = ctx.baseTokens.src.toLowerCase() === ctx.baseTokens.dst.toLowerCase();
2436
- if (baseMatches) {
2437
- return [ctx.attributes.call.interopCallValue(action.amount)];
2438
- }
2439
- return [ctx.attributes.call.indirectCall(action.amount)];
2440
- }
2441
- case "call":
2442
- if (action.value && action.value > 0n) {
2443
- return [ctx.attributes.call.interopCallValue(action.value)];
2444
- }
2445
- return [];
2446
- case "sendErc20":
2447
- return [ctx.attributes.call.indirectCall(0n)];
2448
- default:
2449
- assertNever(action);
2450
- }
2451
- });
2452
- return { bundleAttributes, callAttributes };
2453
- }
2454
- function createEthersAttributesResource(opts = {}) {
2455
- const iface = opts.iface ?? new Interface(IERC7786Attributes_default);
2456
- const encode2 = (fn, args) => iface.encodeFunctionData(fn, args);
2457
- return createAttributesResource({ encode: encode2 });
2458
- }
2459
- var PREFIX_EVM_CHAIN = getBytes("0x00010000");
2460
- var PREFIX_EVM_ADDRESS = getBytes("0x000100000014");
2461
- function formatInteropEvmChain(chainId) {
2462
- const chainRef = toBeArray(chainId);
2463
- const chainRefLength = getBytes(toBeHex(chainRef.length, 1));
2464
- const payload = concat([PREFIX_EVM_CHAIN, chainRefLength, chainRef, new Uint8Array([0])]);
2465
- return hexlify(payload);
2466
- }
2467
- function formatInteropEvmAddress(address) {
2468
- const normalized = getAddress(address);
2469
- const addrBytes = getBytes(normalized);
2470
- const payload = concat([PREFIX_EVM_ADDRESS, addrBytes]);
2471
- return hexlify(payload);
2472
- }
2473
- var interopCodec = {
2474
- formatChain: formatInteropEvmChain,
2475
- formatAddress: formatInteropEvmAddress
2476
- };
2477
2772
  function getErc20Tokens(params) {
2478
2773
  const erc20Tokens = /* @__PURE__ */ new Map();
2479
2774
  for (const action of params.actions) {
@@ -2631,7 +2926,7 @@ function routeIndirect() {
2631
2926
  resolveErc20AssetIds(erc20Tokens, ctx),
2632
2927
  buildFeeInfo(params, ctx, params.actions.length)
2633
2928
  ]);
2634
- const attributes = getInteropAttributes(params, ctx);
2929
+ const attributes2 = getInteropAttributes(params, ctx);
2635
2930
  const starterData = await getStarterData(params, ctx, erc20AssetIds);
2636
2931
  const bundle = buildIndirectBundle(
2637
2932
  params,
@@ -2642,7 +2937,7 @@ function routeIndirect() {
2642
2937
  l2NativeTokenVault: ctx.l2NativeTokenVault,
2643
2938
  codec: interopCodec
2644
2939
  },
2645
- attributes,
2940
+ attributes2,
2646
2941
  starterData,
2647
2942
  feeInfo
2648
2943
  );
@@ -2748,7 +3043,7 @@ async function assertInteropProtocolVersion(client, srcChainId, dstChainId) {
2748
3043
  assertProtocolVersion(srcChainId, srcProtocolVersion);
2749
3044
  assertProtocolVersion(dstChainId, dstProtocolVersion);
2750
3045
  }
2751
- async function commonCtx3(dstProvider, params, client, tokens, contracts, attributes) {
3046
+ async function commonCtx3(dstProvider, params, client, tokens, contracts, attributes2) {
2752
3047
  const sender = await client.signer.getAddress();
2753
3048
  const chainId = (await client.l2.getNetwork()).chainId;
2754
3049
  const dstChainId = (await dstProvider.getNetwork()).chainId;
@@ -2785,7 +3080,7 @@ async function commonCtx3(dstProvider, params, client, tokens, contracts, attrib
2785
3080
  l2NativeTokenVault,
2786
3081
  baseTokens: { src: srcBaseToken, dst: dstBaseToken, matches: baseMatches },
2787
3082
  ifaces: { interopCenter: interopCenterIface, interopHandler: interopHandlerIface },
2788
- attributes,
3083
+ attributes: attributes2,
2789
3084
  gasOverrides: params.txOverrides ? toGasOverrides(params.txOverrides) : void 0
2790
3085
  };
2791
3086
  }
@@ -3309,7 +3604,7 @@ var ROUTES3 = {
3309
3604
  direct: routeDirect(),
3310
3605
  indirect: routeIndirect()
3311
3606
  };
3312
- function createInteropResource(client, config, tokens, contracts, attributes) {
3607
+ function createInteropResource(client, config, tokens, contracts, attributes2) {
3313
3608
  let gwProviderCache;
3314
3609
  function requireConfig() {
3315
3610
  if (!config)
@@ -3327,7 +3622,7 @@ function createInteropResource(client, config, tokens, contracts, attributes) {
3327
3622
  const svc = createInteropFinalizationServices(client);
3328
3623
  const tokensResource = tokens ?? createTokensResource(client);
3329
3624
  const contractsResource = contracts ?? createContractsResource(client);
3330
- const attributesResource = attributes ?? createEthersAttributesResource();
3625
+ const attributesResource = attributes2 ?? createEthersAttributesResource();
3331
3626
  async function buildPlanWithCtx(dstProvider, params) {
3332
3627
  const ctx = await commonCtx3(
3333
3628
  dstProvider,
@@ -3540,11 +3835,11 @@ function createEthersSdk(client, options) {
3540
3835
  const interop = createInteropResource(client, options?.interop, tokens, contracts);
3541
3836
  return {
3542
3837
  deposits: createDepositsResource(client, tokens, contracts),
3543
- withdrawals: createWithdrawalsResource(client, tokens, contracts),
3838
+ withdrawals: createWithdrawalsResource(client, tokens, contracts, options?.withdrawals),
3544
3839
  tokens,
3545
3840
  contracts,
3546
3841
  interop
3547
3842
  };
3548
3843
  }
3549
3844
 
3550
- export { buildDirectRequestStruct, createDepositsResource, createEthersSdk, createFinalizationServices, createInteropFinalizationServices, createInteropResource, createTokensResource, createWithdrawalsResource, encodeNativeTokenVaultTransferData, encodeSecondBridgeArgs, encodeSecondBridgeDataV1, encodeSecondBridgeErc20Args, encodeSecondBridgeEthArgs, getL2TransactionHashFromLogs };
3845
+ export { buildDirectRequestStruct, createDepositsResource, createEthersSdk, createFinalizationServices, createInteropFinalizationServices, createInteropResource, createTokensResource, createWithdrawalProtocolService, createWithdrawalsResource, encodeNativeTokenVaultTransferData, encodeSecondBridgeArgs, encodeSecondBridgeDataV1, encodeSecondBridgeErc20Args, encodeSecondBridgeEthArgs, getL2TransactionHashFromLogs };