@matterlabs/zksync-js 0.0.21 → 0.0.23

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 (77) hide show
  1. package/dist/adapters/ethers/client.cjs +31 -8
  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 +1194 -364
  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/deposits/context.d.ts +2 -0
  10. package/dist/adapters/ethers/resources/deposits/services/gas.d.ts +3 -0
  11. package/dist/adapters/ethers/resources/withdrawals/context.d.ts +12 -1
  12. package/dist/adapters/ethers/resources/withdrawals/index.d.ts +17 -1
  13. package/dist/adapters/ethers/resources/withdrawals/routes/interop-bundle.d.ts +2 -0
  14. package/dist/adapters/ethers/resources/withdrawals/services/finalization.d.ts +35 -17
  15. package/dist/adapters/ethers/resources/withdrawals/services/protocol.d.ts +11 -0
  16. package/dist/adapters/ethers/sdk.cjs +1166 -370
  17. package/dist/adapters/ethers/sdk.cjs.map +1 -1
  18. package/dist/adapters/ethers/sdk.d.ts +3 -1
  19. package/dist/adapters/ethers/sdk.js +8 -7
  20. package/dist/adapters/viem/client.cjs +44 -7
  21. package/dist/adapters/viem/client.cjs.map +1 -1
  22. package/dist/adapters/viem/client.d.ts +11 -0
  23. package/dist/adapters/viem/client.js +6 -5
  24. package/dist/adapters/viem/index.cjs +1237 -383
  25. package/dist/adapters/viem/index.cjs.map +1 -1
  26. package/dist/adapters/viem/index.d.ts +2 -1
  27. package/dist/adapters/viem/index.js +10 -8
  28. package/dist/adapters/viem/resources/deposits/context.d.ts +2 -0
  29. package/dist/adapters/viem/resources/deposits/services/gas.d.ts +3 -0
  30. package/dist/adapters/viem/resources/withdrawals/context.d.ts +12 -1
  31. package/dist/adapters/viem/resources/withdrawals/index.d.ts +17 -1
  32. package/dist/adapters/viem/resources/withdrawals/routes/interop-bundle.d.ts +2 -0
  33. package/dist/adapters/viem/resources/withdrawals/services/finalization.d.ts +36 -18
  34. package/dist/adapters/viem/resources/withdrawals/services/protocol.d.ts +11 -0
  35. package/dist/adapters/viem/sdk.cjs +1191 -385
  36. package/dist/adapters/viem/sdk.cjs.map +1 -1
  37. package/dist/adapters/viem/sdk.d.ts +3 -1
  38. package/dist/adapters/viem/sdk.js +8 -7
  39. package/dist/{chunk-UEKFQAOS.js → chunk-2DDJFHHD.js} +304 -9
  40. package/dist/{chunk-MT4X5FEO.js → chunk-3IPSDGHO.js} +19 -1
  41. package/dist/{chunk-JSBMIT4S.js → chunk-4GPIHYVF.js} +1 -1
  42. package/dist/{chunk-SBGBYZJM.js → chunk-4M7VNYGC.js} +2 -2
  43. package/dist/{chunk-CK5UFAZK.js → chunk-6WIAMFIW.js} +37 -3
  44. package/dist/chunk-JJ523MOL.js +157 -0
  45. package/dist/{chunk-7GZDTLHX.js → chunk-NVOFHV3A.js} +666 -304
  46. package/dist/{chunk-LGTYM5XP.js → chunk-OEUDZFXH.js} +1 -1
  47. package/dist/{chunk-NJK325XV.js → chunk-TUN6NH5D.js} +2 -2
  48. package/dist/chunk-UMPAKZCQ.js +19 -0
  49. package/dist/{chunk-24TE2NNJ.js → chunk-URHDNDFN.js} +24 -4
  50. package/dist/{chunk-2CGBLD5H.js → chunk-V2TDNGI5.js} +642 -288
  51. package/dist/{chunk-IDXSGCGF.js → chunk-WPCZNITC.js} +63 -50
  52. package/dist/{chunk-TYYUG5GA.js → chunk-X2JJDQ4O.js} +1 -1
  53. package/dist/core/abi.d.ts +1 -0
  54. package/dist/core/adapters/interfaces.d.ts +2 -0
  55. package/dist/core/constants.cjs +18 -0
  56. package/dist/core/constants.cjs.map +1 -1
  57. package/dist/core/constants.d.ts +17 -0
  58. package/dist/core/constants.js +1 -1
  59. package/dist/core/index.cjs +504 -7
  60. package/dist/core/index.cjs.map +1 -1
  61. package/dist/core/index.d.ts +6 -1
  62. package/dist/core/index.js +6 -4
  63. package/dist/core/internal/abis/IERC7786Attributes.d.ts +10 -0
  64. package/dist/core/internal/abis/IL1NullifierV32.d.ts +221 -0
  65. package/dist/core/internal/abis/IL2AssetRouter.d.ts +0 -14
  66. package/dist/core/resources/deposits/priority.d.ts +30 -0
  67. package/dist/core/resources/interop/attributes/bundle.d.ts +1 -0
  68. package/dist/core/resources/interop/attributes/resource.d.ts +1 -0
  69. package/dist/core/resources/protocol/semver.d.ts +18 -0
  70. package/dist/core/resources/withdrawals/bundle.d.ts +80 -0
  71. package/dist/core/resources/withdrawals/finalization.d.ts +142 -0
  72. package/dist/core/resources/withdrawals/protocol.d.ts +55 -0
  73. package/dist/core/types/flows/withdrawals.d.ts +30 -0
  74. package/dist/index.cjs +320 -7
  75. package/dist/index.cjs.map +1 -1
  76. package/dist/index.js +4 -4
  77. package/package.json +1 -1
@@ -32,6 +32,7 @@ var L2_BASE_TOKEN_ADDRESS = "0x000000000000000000000000000000000000800A";
32
32
  var L2_INTEROP_CENTER_ADDRESS = "0x000000000000000000000000000000000001000d";
33
33
  var L2_INTEROP_HANDLER_ADDRESS = "0x000000000000000000000000000000000001000e";
34
34
  var L2_INTEROP_ROOT_STORAGE_ADDRESS = "0x0000000000000000000000000000000000010008";
35
+ var L2_INTEROP_ATTRIBUTE_PARSER_ADDRESS = "0x0000000000000000000000000000000000010015";
35
36
  var L2_MESSAGE_VERIFICATION_ADDRESS = "0x0000000000000000000000000000000000010009";
36
37
  var BUNDLE_IDENTIFIER = "0x01";
37
38
  var TOPIC_L1_MESSAGE_SENT_NEW = k256hex("L1MessageSent(uint256,bytes32,bytes)");
@@ -52,6 +53,14 @@ var L1_TX_DELTA_FACTORY_DEPS_L2_GAS = 2473n;
52
53
  var L1_TX_DELTA_FACTORY_DEPS_PUBDATA = 64n;
53
54
  var TX_SLOT_OVERHEAD_L2_GAS = 10000n;
54
55
  var PRIORITY_TX_MAX_GAS_LIMIT = 72000000n;
56
+ var L1_TX_INTRINSIC_L2_GAS_ZKSYNC_OS = 21000n;
57
+ var L1_TX_CALLDATA_FLOOR_PRICE_L2_GAS_ZKSYNC_OS = 40n;
58
+ var L1_TX_INTRINSIC_PUBDATA_ZKSYNC_OS = 351n;
59
+ var MAX_NATIVE_COMPUTATIONAL_ZKSYNC_OS = 1n << 35n;
60
+ var L1_TX_NATIVE_PER_GAS = 100000000n;
61
+ var ZKSYNC_OS_PRIORITY_TX_TYPE = "0x7f";
62
+ var REGISTERED_TOKEN_BRIDGE_MINT_EXECUTION_GAS = 140000n;
63
+ var REGISTERED_TOKEN_BRIDGE_MINT_PUBDATA_BYTES = 300n;
55
64
 
56
65
  // src/core/utils/addr.ts
57
66
  function isAddress(x) {
@@ -3497,6 +3506,294 @@ var IL1NullifierABI = [
3497
3506
  ];
3498
3507
  var IL1Nullifier_default = IL1NullifierABI;
3499
3508
 
3509
+ // src/core/internal/abis/IL1NullifierV32.ts
3510
+ var IL1NullifierV32ABI = [
3511
+ {
3512
+ anonymous: false,
3513
+ inputs: [
3514
+ {
3515
+ indexed: true,
3516
+ internalType: "uint256",
3517
+ name: "chainId",
3518
+ type: "uint256"
3519
+ },
3520
+ {
3521
+ indexed: true,
3522
+ internalType: "bytes32",
3523
+ name: "txDataHash",
3524
+ type: "bytes32"
3525
+ },
3526
+ {
3527
+ indexed: true,
3528
+ internalType: "bytes32",
3529
+ name: "l2DepositTxHash",
3530
+ type: "bytes32"
3531
+ }
3532
+ ],
3533
+ name: "BridgehubDepositFinalized",
3534
+ type: "event"
3535
+ },
3536
+ {
3537
+ inputs: [],
3538
+ name: "BRIDGE_HUB",
3539
+ outputs: [
3540
+ {
3541
+ internalType: "contract IL1Bridgehub",
3542
+ name: "",
3543
+ type: "address"
3544
+ }
3545
+ ],
3546
+ stateMutability: "view",
3547
+ type: "function"
3548
+ },
3549
+ {
3550
+ inputs: [],
3551
+ name: "l1AssetRouter",
3552
+ outputs: [
3553
+ {
3554
+ internalType: "contract IL1AssetRouter",
3555
+ name: "",
3556
+ type: "address"
3557
+ }
3558
+ ],
3559
+ stateMutability: "view",
3560
+ type: "function"
3561
+ },
3562
+ {
3563
+ // The contract that took over withdrawal finalization from the nullifier's own (removed)
3564
+ // `finalizeDeposit`.
3565
+ inputs: [],
3566
+ name: "l1InteropHandler",
3567
+ outputs: [
3568
+ {
3569
+ internalType: "address",
3570
+ name: "",
3571
+ type: "address"
3572
+ }
3573
+ ],
3574
+ stateMutability: "view",
3575
+ type: "function"
3576
+ },
3577
+ {
3578
+ inputs: [],
3579
+ name: "l1NativeTokenVault",
3580
+ outputs: [
3581
+ {
3582
+ internalType: "contract IL1NativeTokenVault",
3583
+ name: "",
3584
+ type: "address"
3585
+ }
3586
+ ],
3587
+ stateMutability: "view",
3588
+ type: "function"
3589
+ },
3590
+ {
3591
+ inputs: [
3592
+ {
3593
+ internalType: "uint256",
3594
+ name: "_chainId",
3595
+ type: "uint256"
3596
+ },
3597
+ {
3598
+ internalType: "bytes32",
3599
+ name: "_l2TxHash",
3600
+ type: "bytes32"
3601
+ }
3602
+ ],
3603
+ name: "depositHappened",
3604
+ outputs: [
3605
+ {
3606
+ internalType: "bytes32",
3607
+ name: "",
3608
+ type: "bytes32"
3609
+ }
3610
+ ],
3611
+ stateMutability: "view",
3612
+ type: "function"
3613
+ },
3614
+ {
3615
+ inputs: [
3616
+ {
3617
+ internalType: "uint256",
3618
+ name: "_chainId",
3619
+ type: "uint256"
3620
+ },
3621
+ {
3622
+ internalType: "bytes32",
3623
+ name: "_txDataHash",
3624
+ type: "bytes32"
3625
+ },
3626
+ {
3627
+ internalType: "bytes32",
3628
+ name: "_txHash",
3629
+ type: "bytes32"
3630
+ }
3631
+ ],
3632
+ name: "bridgehubConfirmL2TransactionForwarded",
3633
+ outputs: [],
3634
+ stateMutability: "nonpayable",
3635
+ type: "function"
3636
+ },
3637
+ {
3638
+ inputs: [
3639
+ {
3640
+ components: [
3641
+ {
3642
+ internalType: "uint256",
3643
+ name: "_chainId",
3644
+ type: "uint256"
3645
+ },
3646
+ {
3647
+ internalType: "address",
3648
+ name: "_depositSender",
3649
+ type: "address"
3650
+ },
3651
+ {
3652
+ internalType: "uint16",
3653
+ name: "_l2TxNumberInBatch",
3654
+ type: "uint16"
3655
+ },
3656
+ {
3657
+ internalType: "enum TxStatus",
3658
+ name: "_txStatus",
3659
+ type: "uint8"
3660
+ },
3661
+ {
3662
+ internalType: "bytes32",
3663
+ name: "_assetId",
3664
+ type: "bytes32"
3665
+ },
3666
+ {
3667
+ internalType: "bytes",
3668
+ name: "_assetData",
3669
+ type: "bytes"
3670
+ },
3671
+ {
3672
+ internalType: "bytes32",
3673
+ name: "_l2TxHash",
3674
+ type: "bytes32"
3675
+ },
3676
+ {
3677
+ internalType: "uint256",
3678
+ name: "_l2BatchNumber",
3679
+ type: "uint256"
3680
+ },
3681
+ {
3682
+ internalType: "uint256",
3683
+ name: "_l2MessageIndex",
3684
+ type: "uint256"
3685
+ },
3686
+ {
3687
+ internalType: "bytes32[]",
3688
+ name: "_merkleProof",
3689
+ type: "bytes32[]"
3690
+ }
3691
+ ],
3692
+ internalType: "struct ConfirmTransferResultData",
3693
+ name: "_confirmTransferResultData",
3694
+ type: "tuple"
3695
+ }
3696
+ ],
3697
+ name: "bridgeConfirmTransferResult",
3698
+ outputs: [],
3699
+ stateMutability: "nonpayable",
3700
+ type: "function"
3701
+ },
3702
+ {
3703
+ inputs: [
3704
+ {
3705
+ internalType: "uint256",
3706
+ name: "_chainId",
3707
+ type: "uint256"
3708
+ },
3709
+ {
3710
+ internalType: "address",
3711
+ name: "_depositSender",
3712
+ type: "address"
3713
+ },
3714
+ {
3715
+ internalType: "bytes32",
3716
+ name: "_assetId",
3717
+ type: "bytes32"
3718
+ },
3719
+ {
3720
+ internalType: "bytes",
3721
+ name: "_assetData",
3722
+ type: "bytes"
3723
+ },
3724
+ {
3725
+ internalType: "bytes32",
3726
+ name: "_l2TxHash",
3727
+ type: "bytes32"
3728
+ },
3729
+ {
3730
+ internalType: "uint256",
3731
+ name: "_l2BatchNumber",
3732
+ type: "uint256"
3733
+ },
3734
+ {
3735
+ internalType: "uint256",
3736
+ name: "_l2MessageIndex",
3737
+ type: "uint256"
3738
+ },
3739
+ {
3740
+ internalType: "uint16",
3741
+ name: "_l2TxNumberInBatch",
3742
+ type: "uint16"
3743
+ },
3744
+ {
3745
+ internalType: "bytes32[]",
3746
+ name: "_merkleProof",
3747
+ type: "bytes32[]"
3748
+ }
3749
+ ],
3750
+ name: "bridgeRecoverFailedTransfer",
3751
+ outputs: [],
3752
+ stateMutability: "nonpayable",
3753
+ type: "function"
3754
+ },
3755
+ {
3756
+ inputs: [
3757
+ {
3758
+ internalType: "contract IL1NativeTokenVault",
3759
+ name: "_nativeTokenVault",
3760
+ type: "address"
3761
+ }
3762
+ ],
3763
+ name: "setL1NativeTokenVault",
3764
+ outputs: [],
3765
+ stateMutability: "nonpayable",
3766
+ type: "function"
3767
+ },
3768
+ {
3769
+ inputs: [
3770
+ {
3771
+ internalType: "address",
3772
+ name: "_l1AssetRouter",
3773
+ type: "address"
3774
+ }
3775
+ ],
3776
+ name: "setL1AssetRouter",
3777
+ outputs: [],
3778
+ stateMutability: "nonpayable",
3779
+ type: "function"
3780
+ },
3781
+ {
3782
+ inputs: [
3783
+ {
3784
+ internalType: "address",
3785
+ name: "_l1InteropHandler",
3786
+ type: "address"
3787
+ }
3788
+ ],
3789
+ name: "setL1InteropHandler",
3790
+ outputs: [],
3791
+ stateMutability: "nonpayable",
3792
+ type: "function"
3793
+ }
3794
+ ];
3795
+ var IL1NullifierV32_default = IL1NullifierV32ABI;
3796
+
3500
3797
  // src/core/internal/abis/IL2AssetRouter.ts
3501
3798
  var IL2AssetRouterABI = [
3502
3799
  {
@@ -3620,13 +3917,6 @@ var IL2AssetRouterABI = [
3620
3917
  outputs: [{ name: "", type: "address", internalType: "address" }],
3621
3918
  stateMutability: "view"
3622
3919
  },
3623
- {
3624
- type: "function",
3625
- name: "l1TokenAddress",
3626
- inputs: [{ name: "_l2Token", type: "address", internalType: "address" }],
3627
- outputs: [{ name: "", type: "address", internalType: "address" }],
3628
- stateMutability: "view"
3629
- },
3630
3920
  {
3631
3921
  type: "function",
3632
3922
  name: "l2TokenAddress",
@@ -5030,6 +5320,19 @@ var IERC7786AttributesABI = [
5030
5320
  outputs: [],
5031
5321
  stateMutability: "pure"
5032
5322
  },
5323
+ {
5324
+ type: "function",
5325
+ name: "interopBundleSalt",
5326
+ inputs: [
5327
+ {
5328
+ name: "_salt",
5329
+ type: "bytes32",
5330
+ internalType: "bytes32"
5331
+ }
5332
+ ],
5333
+ outputs: [],
5334
+ stateMutability: "pure"
5335
+ },
5033
5336
  {
5034
5337
  type: "function",
5035
5338
  name: "unbundlerAddress",
@@ -7180,7 +7483,7 @@ function createErrorOps(decodeRevert2) {
7180
7483
  function wrap8(operation, fn, opts) {
7181
7484
  return run("INTERNAL", operation, fn, opts);
7182
7485
  }
7183
- function wrapAs10(kind, operation, fn, opts) {
7486
+ function wrapAs11(kind, operation, fn, opts) {
7184
7487
  return run(kind, operation, fn, opts);
7185
7488
  }
7186
7489
  async function toResult3(operation, fn, opts) {
@@ -7201,7 +7504,7 @@ function createErrorOps(decodeRevert2) {
7201
7504
  return { ok: false, error: shaped };
7202
7505
  }
7203
7506
  }
7204
- return { wrap: wrap8, wrapAs: wrapAs10, toResult: toResult3 };
7507
+ return { wrap: wrap8, wrapAs: wrapAs11, toResult: toResult3 };
7205
7508
  }
7206
7509
  return { toZKsyncError: toZKsyncError2, createErrorHandlers: createErrorHandlers2 };
7207
7510
  }
@@ -7345,6 +7648,17 @@ function classifyReadinessFromRevert(e) {
7345
7648
  // src/adapters/viem/errors/error-ops.ts
7346
7649
  var { toZKsyncError, createErrorHandlers } = createErrorOps(decodeRevert);
7347
7650
 
7651
+ // src/core/resources/protocol/semver.ts
7652
+ var SEMVER_MINOR_OFFSET = 32n;
7653
+ var SEMVER_MAJOR_OFFSET = 64n;
7654
+ var U32_MASK = 0xffffffffn;
7655
+ function unpackSemver(packed) {
7656
+ const patch = Number(packed & U32_MASK);
7657
+ const minor = Number(packed >> SEMVER_MINOR_OFFSET & U32_MASK);
7658
+ const major = Number(packed >> SEMVER_MAJOR_OFFSET & U32_MASK);
7659
+ return [major, minor, patch];
7660
+ }
7661
+
7348
7662
  // src/adapters/viem/client.ts
7349
7663
  var { wrap } = createErrorHandlers("client");
7350
7664
  var ChainTypeManagerABI = [
@@ -7354,6 +7668,15 @@ var ChainTypeManagerABI = [
7354
7668
  inputs: [],
7355
7669
  outputs: [{ type: "uint32" }, { type: "uint32" }, { type: "uint32" }],
7356
7670
  stateMutability: "view"
7671
+ },
7672
+ {
7673
+ // Per-chain version. `getSemverProtocolVersion` reports the CTM's own (latest) version, which
7674
+ // runs ahead of individual chains mid-upgrade — so capability gating must use this one.
7675
+ type: "function",
7676
+ name: "getProtocolVersion",
7677
+ inputs: [{ name: "_chainId", type: "uint256" }],
7678
+ outputs: [{ type: "uint256" }],
7679
+ stateMutability: "view"
7357
7680
  }
7358
7681
  ];
7359
7682
  function createViemClient(args) {
@@ -7494,6 +7817,29 @@ function createViemClient(args) {
7494
7817
  );
7495
7818
  return semver;
7496
7819
  }
7820
+ async function getChainProtocolVersion(chainId) {
7821
+ try {
7822
+ const targetChainId = chainId ?? BigInt(await l2.getChainId());
7823
+ const { bridgehub } = await ensureAddresses();
7824
+ const chainTypeManager = await l1.readContract({
7825
+ address: bridgehub,
7826
+ abi: IBridgehub_default,
7827
+ functionName: "chainTypeManager",
7828
+ args: [targetChainId]
7829
+ });
7830
+ if (chainTypeManager.toLowerCase() === FORMAL_ETH_ADDRESS.toLowerCase()) return void 0;
7831
+ const packed = await l1.readContract({
7832
+ address: chainTypeManager,
7833
+ abi: ChainTypeManagerABI,
7834
+ functionName: "getProtocolVersion",
7835
+ args: [targetChainId]
7836
+ });
7837
+ if (packed === 0n) return void 0;
7838
+ return unpackSemver(packed);
7839
+ } catch {
7840
+ return void 0;
7841
+ }
7842
+ }
7497
7843
  let lazyL2;
7498
7844
  function getL2Wallet() {
7499
7845
  if (l2Wallet) return l2Wallet;
@@ -7518,6 +7864,7 @@ function createViemClient(args) {
7518
7864
  refresh,
7519
7865
  baseToken,
7520
7866
  getProtocolVersion,
7867
+ getChainProtocolVersion,
7521
7868
  getL2Wallet
7522
7869
  };
7523
7870
  }
@@ -7530,7 +7877,7 @@ function toGasOverrides(overrides) {
7530
7877
 
7531
7878
  // src/adapters/viem/resources/deposits/context.ts
7532
7879
  async function commonCtx(p, client, tokens, contracts) {
7533
- const { bridgehub, l1AssetRouter } = await contracts.addresses();
7880
+ const { bridgehub, l1AssetRouter, l1NativeTokenVault } = await contracts.addresses();
7534
7881
  const chainId = await client.l2.getChainId();
7535
7882
  const sender = client.account.address;
7536
7883
  const gasPerPubdata = p.gasPerPubdata ?? 800n;
@@ -7558,6 +7905,7 @@ async function commonCtx(p, client, tokens, contracts) {
7558
7905
  baseTokenL1,
7559
7906
  baseIsEth,
7560
7907
  l1AssetRouter,
7908
+ l1NativeTokenVault,
7561
7909
  route,
7562
7910
  bridgehub,
7563
7911
  chainIdL2: BigInt(chainId),
@@ -7748,6 +8096,68 @@ async function quoteL2Gas(input) {
7748
8096
  }
7749
8097
  }
7750
8098
 
8099
+ // src/core/resources/deposits/priority.ts
8100
+ var PRIORITY_TX_ENCODING_STEP_BYTES = 544n;
8101
+ var L1_TO_L2_ALIAS_OFFSET = 0x1111000000000000000000000000000000001111n;
8102
+ var DEFAULT_PRIORITY_BODY_GAS_ESTIMATE_MULTIPLIER = 7n;
8103
+ var PRIORITY_L2_GAS_BUFFER = 40n;
8104
+ var maxBigInt2 = (a, b) => a > b ? a : b;
8105
+ var ceilDiv = (a, b) => (a + b - 1n) / b;
8106
+ function applyL1ToL2Alias(address) {
8107
+ return `0x${(BigInt(address) + L1_TO_L2_ALIAS_OFFSET & (1n << 160n) - 1n).toString(16).padStart(40, "0")}`;
8108
+ }
8109
+ function derivePriorityTxGasBreakdown(input) {
8110
+ const factoryDepsCount = input.factoryDepsCount ?? 0n;
8111
+ const minBodyGas = maxBigInt2(
8112
+ L1_TX_INTRINSIC_L2_GAS + ceilDiv(
8113
+ input.encodedLength * L1_TX_DELTA_544_ENCODING_BYTES,
8114
+ PRIORITY_TX_ENCODING_STEP_BYTES
8115
+ ) + factoryDepsCount * L1_TX_DELTA_FACTORY_DEPS_L2_GAS,
8116
+ L1_TX_MIN_L2_GAS_BASE
8117
+ ) + L1_TX_INTRINSIC_PUBDATA * input.gasPerPubdata + factoryDepsCount * L1_TX_DELTA_FACTORY_DEPS_PUBDATA * input.gasPerPubdata;
8118
+ const overhead = maxBigInt2(TX_SLOT_OVERHEAD_L2_GAS, TX_MEMORY_OVERHEAD_GAS * input.encodedLength);
8119
+ const derivedBodyGas = minBodyGas;
8120
+ return {
8121
+ encodedLength: input.encodedLength,
8122
+ minBodyGas,
8123
+ overhead,
8124
+ derivedBodyGas,
8125
+ derivedL2GasLimit: derivedBodyGas + overhead,
8126
+ priorityTxMaxGasLimit: PRIORITY_TX_MAX_GAS_LIMIT,
8127
+ priorityTxMaxGasLimitExceeded: derivedBodyGas > PRIORITY_TX_MAX_GAS_LIMIT
8128
+ };
8129
+ }
8130
+ function derivePriorityBodyGasEstimateCap(input) {
8131
+ return input.minBodyGas * (input.multiplier ?? DEFAULT_PRIORITY_BODY_GAS_ESTIMATE_MULTIPLIER);
8132
+ }
8133
+ function applyPriorityL2GasLimitBuffer(input) {
8134
+ return input.gasLimit * (100n + PRIORITY_L2_GAS_BUFFER) / 100n;
8135
+ }
8136
+ function minimalPriorityTxL2Gas(input) {
8137
+ const intrinsic = L1_TX_INTRINSIC_L2_GAS_ZKSYNC_OS + L1_TX_CALLDATA_FLOOR_PRICE_L2_GAS_ZKSYNC_OS * input.calldataLength;
8138
+ const pubdata = L1_TX_INTRINSIC_PUBDATA_ZKSYNC_OS * input.gasPerPubdata + ceilDiv(MAX_NATIVE_COMPUTATIONAL_ZKSYNC_OS, L1_TX_NATIVE_PER_GAS);
8139
+ return maxBigInt2(intrinsic, pubdata);
8140
+ }
8141
+ function clampPriorityL2GasLimit(input) {
8142
+ return maxBigInt2(
8143
+ input.gasLimit,
8144
+ minimalPriorityTxL2Gas({
8145
+ calldataLength: BigInt(Math.max(input.l2Calldata.length - 2, 0) / 2),
8146
+ gasPerPubdata: input.gasPerPubdata
8147
+ })
8148
+ );
8149
+ }
8150
+ function resolveRegisteredTokenPriorityL2GasLimit(input) {
8151
+ if (input.nodeEstimate != null && input.nodeEstimate > 0n) {
8152
+ return maxBigInt2(input.priorityFloorGasLimit, applyGasBuffer(input.nodeEstimate));
8153
+ }
8154
+ const modeledGas = REGISTERED_TOKEN_BRIDGE_MINT_EXECUTION_GAS + REGISTERED_TOKEN_BRIDGE_MINT_PUBDATA_BYTES * input.gasPerPubdata;
8155
+ return maxBigInt2(
8156
+ input.priorityFloorGasLimit,
8157
+ applyPriorityL2GasLimitBuffer({ gasLimit: modeledGas })
8158
+ );
8159
+ }
8160
+
7751
8161
  // src/adapters/viem/estimator.ts
7752
8162
  function toCoreTx(tx) {
7753
8163
  return {
@@ -7799,6 +8209,20 @@ function viemToGasEstimator(client) {
7799
8209
  maxPriorityFeePerGas: tx.maxPriorityFeePerGas
7800
8210
  });
7801
8211
  },
8212
+ async estimatePriorityTxGas(tx) {
8213
+ const result = await client.request({
8214
+ method: "eth_estimateGas",
8215
+ params: [
8216
+ {
8217
+ from: tx.from,
8218
+ to: tx.to,
8219
+ data: tx.data,
8220
+ type: ZKSYNC_OS_PRIORITY_TX_TYPE
8221
+ }
8222
+ ]
8223
+ });
8224
+ return BigInt(result);
8225
+ },
7802
8226
  async estimateFeesPerGas() {
7803
8227
  try {
7804
8228
  const fees = await client.estimateFeesPerGas();
@@ -7832,6 +8256,14 @@ function viemToGasEstimator(client) {
7832
8256
 
7833
8257
  // src/adapters/viem/resources/deposits/services/gas.ts
7834
8258
  var DEFAULT_SAFE_NONBASE_L2_GAS_LIMIT = 3000000n;
8259
+ async function estimatePriorityTxL2Gas(ctx, leg) {
8260
+ if (!leg) return void 0;
8261
+ try {
8262
+ return await viemToGasEstimator(ctx.client.l2).estimatePriorityTxGas?.(leg);
8263
+ } catch {
8264
+ return void 0;
8265
+ }
8266
+ }
7835
8267
  async function quoteL1Gas2(input) {
7836
8268
  const { ctx, tx, overrides, fallbackGasLimit } = input;
7837
8269
  const estimator = viemToGasEstimator(ctx.client.l1);
@@ -7886,7 +8318,12 @@ async function determineNonBaseL2Gas(input) {
7886
8318
  return quoteL2Gas2({
7887
8319
  ctx,
7888
8320
  route,
7889
- overrideGasLimit: input.priorityFloorGasLimit
8321
+ overrideGasLimit: resolveRegisteredTokenPriorityL2GasLimit({
8322
+ chainIdL2: ctx.chainIdL2,
8323
+ priorityFloorGasLimit: input.priorityFloorGasLimit,
8324
+ gasPerPubdata: ctx.gasPerPubdata,
8325
+ nodeEstimate: await estimatePriorityTxL2Gas(ctx, input.priorityTxL2Leg)
8326
+ })
7890
8327
  });
7891
8328
  }
7892
8329
  const modelTx = {
@@ -7923,6 +8360,7 @@ async function determineEthNonBaseL2Gas(input) {
7923
8360
  knownL2Token: input.ctx.resolvedToken?.l2,
7924
8361
  modelTx: input.modelTx,
7925
8362
  priorityFloorGasLimit: input.priorityFloorGasLimit,
8363
+ priorityTxL2Leg: input.priorityTxL2Leg,
7926
8364
  undeployedGasLimit: input.undeployedGasLimit
7927
8365
  });
7928
8366
  }
@@ -7976,40 +8414,6 @@ function buildFeeBreakdown(p) {
7976
8414
  l2
7977
8415
  };
7978
8416
  }
7979
-
7980
- // src/core/resources/deposits/priority.ts
7981
- var PRIORITY_TX_ENCODING_STEP_BYTES = 544n;
7982
- var DEFAULT_PRIORITY_BODY_GAS_ESTIMATE_MULTIPLIER = 7n;
7983
- var PRIORITY_L2_GAS_BUFFER = 40n;
7984
- var maxBigInt2 = (a, b) => a > b ? a : b;
7985
- var ceilDiv = (a, b) => (a + b - 1n) / b;
7986
- function derivePriorityTxGasBreakdown(input) {
7987
- const factoryDepsCount = input.factoryDepsCount ?? 0n;
7988
- const minBodyGas = maxBigInt2(
7989
- L1_TX_INTRINSIC_L2_GAS + ceilDiv(
7990
- input.encodedLength * L1_TX_DELTA_544_ENCODING_BYTES,
7991
- PRIORITY_TX_ENCODING_STEP_BYTES
7992
- ) + factoryDepsCount * L1_TX_DELTA_FACTORY_DEPS_L2_GAS,
7993
- L1_TX_MIN_L2_GAS_BASE
7994
- ) + L1_TX_INTRINSIC_PUBDATA * input.gasPerPubdata + factoryDepsCount * L1_TX_DELTA_FACTORY_DEPS_PUBDATA * input.gasPerPubdata;
7995
- const overhead = maxBigInt2(TX_SLOT_OVERHEAD_L2_GAS, TX_MEMORY_OVERHEAD_GAS * input.encodedLength);
7996
- const derivedBodyGas = minBodyGas;
7997
- return {
7998
- encodedLength: input.encodedLength,
7999
- minBodyGas,
8000
- overhead,
8001
- derivedBodyGas,
8002
- derivedL2GasLimit: derivedBodyGas + overhead,
8003
- priorityTxMaxGasLimit: PRIORITY_TX_MAX_GAS_LIMIT,
8004
- priorityTxMaxGasLimitExceeded: derivedBodyGas > PRIORITY_TX_MAX_GAS_LIMIT
8005
- };
8006
- }
8007
- function derivePriorityBodyGasEstimateCap(input) {
8008
- return input.minBodyGas * (input.multiplier ?? DEFAULT_PRIORITY_BODY_GAS_ESTIMATE_MULTIPLIER);
8009
- }
8010
- function applyPriorityL2GasLimitBuffer(input) {
8011
- return input.gasLimit * (100n + PRIORITY_L2_GAS_BUFFER) / 100n;
8012
- }
8013
8417
  var EMPTY_BYTES = "0x";
8014
8418
  var ZERO_RESERVED_WORDS = [0n, 0n, 0n, 0n];
8015
8419
  var L2_CANONICAL_TRANSACTION_PARAMETER = {
@@ -8086,9 +8490,13 @@ function routeEthDirect() {
8086
8490
  l2Calldata,
8087
8491
  gasPerPubdata: ctx.gasPerPubdata
8088
8492
  });
8089
- const quotedL2GasLimit = ctx.l2GasLimit ?? applyPriorityL2GasLimitBuffer({
8090
- chainIdL2: ctx.chainIdL2,
8091
- gasLimit: priorityFloorBreakdown.derivedL2GasLimit
8493
+ const quotedL2GasLimit = ctx.l2GasLimit ?? clampPriorityL2GasLimit({
8494
+ gasLimit: applyPriorityL2GasLimitBuffer({
8495
+ chainIdL2: ctx.chainIdL2,
8496
+ gasLimit: priorityFloorBreakdown.derivedL2GasLimit
8497
+ }),
8498
+ l2Calldata,
8499
+ gasPerPubdata: ctx.gasPerPubdata
8092
8500
  });
8093
8501
  const l2GasParams = await quoteL2Gas2({
8094
8502
  ctx,
@@ -8248,26 +8656,18 @@ var ntvCodec = createNTVCodec({
8248
8656
  keccak256: viem.keccak256
8249
8657
  });
8250
8658
  async function encodeSecondBridgeErc20DepositCalldata(input) {
8251
- if (!input.ctx.resolvedToken) {
8252
- return encodeSecondBridgeErc20Args(input.token, input.amount, input.receiver);
8253
- }
8254
- const l1ChainId = BigInt(await input.ctx.client.l1.getChainId());
8255
- const expectedL1AssetId = ntvCodec.encodeAssetId(
8256
- l1ChainId,
8659
+ const registeredAssetId = input.ctx.resolvedToken?.assetId;
8660
+ const assetId = registeredAssetId && registeredAssetId.toLowerCase() !== ZERO_ASSET_ID ? registeredAssetId : ntvCodec.encodeAssetId(
8661
+ BigInt(await input.ctx.client.l1.getChainId()),
8257
8662
  L2_NATIVE_TOKEN_VAULT_ADDRESS,
8258
8663
  input.token
8259
8664
  );
8260
- const assetId = input.ctx.resolvedToken.assetId.toLowerCase();
8261
- const isL1Origin = assetId === ZERO_ASSET_ID || assetId === expectedL1AssetId.toLowerCase();
8262
- if (isL1Origin) {
8263
- return encodeSecondBridgeErc20Args(input.token, input.amount, input.receiver);
8264
- }
8265
8665
  const transferData = encodeNativeTokenVaultTransferData(
8266
8666
  input.amount,
8267
8667
  input.receiver,
8268
8668
  input.token
8269
8669
  );
8270
- return encodeSecondBridgeDataV1(input.ctx.resolvedToken.assetId, transferData);
8670
+ return encodeSecondBridgeDataV1(assetId, transferData);
8271
8671
  }
8272
8672
  async function getPriorityGasModel(input) {
8273
8673
  try {
@@ -8309,9 +8709,18 @@ async function getPriorityGasModel(input) {
8309
8709
  gasPerPubdata: input.ctx.gasPerPubdata
8310
8710
  });
8311
8711
  const model = {
8312
- priorityFloorGasLimit: applyPriorityL2GasLimitBuffer({
8313
- chainIdL2: input.ctx.chainIdL2,
8314
- gasLimit: priorityFloorBreakdown.derivedL2GasLimit
8712
+ priorityTxL2Leg: {
8713
+ from: applyL1ToL2Alias(input.ctx.l1AssetRouter),
8714
+ to: L2_ASSET_ROUTER_ADDRESS,
8715
+ data: l2Calldata
8716
+ },
8717
+ priorityFloorGasLimit: clampPriorityL2GasLimit({
8718
+ gasLimit: applyPriorityL2GasLimitBuffer({
8719
+ chainIdL2: input.ctx.chainIdL2,
8720
+ gasLimit: priorityFloorBreakdown.derivedL2GasLimit
8721
+ }),
8722
+ l2Calldata,
8723
+ gasPerPubdata: input.ctx.gasPerPubdata
8315
8724
  })
8316
8725
  };
8317
8726
  if (isFirstBridge || input.ctx.resolvedToken.l2.toLowerCase() === viem.zeroAddress) {
@@ -8354,6 +8763,7 @@ function routeErc20NonBase() {
8354
8763
  const baseToken = ctx.baseTokenL1 ?? await ctx.client.baseToken(ctx.chainIdL2);
8355
8764
  const baseIsEth = ctx.baseIsEth ?? isETH(baseToken);
8356
8765
  const assetRouter = ctx.l1AssetRouter;
8766
+ const nativeTokenVault = ctx.l1NativeTokenVault;
8357
8767
  const receiver = p.to ?? ctx.sender;
8358
8768
  const secondBridgeCalldata = await wrapAs3(
8359
8769
  "INTERNAL",
@@ -8383,6 +8793,7 @@ function routeErc20NonBase() {
8383
8793
  ctx,
8384
8794
  l1Token: p.token,
8385
8795
  priorityFloorGasLimit: priorityGasModel.priorityFloorGasLimit,
8796
+ priorityTxL2Leg: priorityGasModel.priorityTxL2Leg,
8386
8797
  undeployedGasLimit: priorityGasModel.undeployedGasLimit,
8387
8798
  modelTx: {
8388
8799
  to: receiver,
@@ -8403,10 +8814,10 @@ function routeErc20NonBase() {
8403
8814
  address: p.token,
8404
8815
  abi: IERC20_default,
8405
8816
  functionName: "allowance",
8406
- args: [ctx.sender, assetRouter]
8817
+ args: [ctx.sender, nativeTokenVault]
8407
8818
  }),
8408
8819
  {
8409
- ctx: { where: "erc20.allowance", token: p.token, spender: assetRouter },
8820
+ ctx: { where: "erc20.allowance", token: p.token, spender: nativeTokenVault },
8410
8821
  message: "Failed to read deposit-token allowance."
8411
8822
  }
8412
8823
  );
@@ -8417,7 +8828,7 @@ function routeErc20NonBase() {
8417
8828
  () => buildApprovalRequest({
8418
8829
  ctx,
8419
8830
  token: p.token,
8420
- spender: assetRouter,
8831
+ spender: nativeTokenVault,
8421
8832
  amount: p.amount
8422
8833
  }),
8423
8834
  {
@@ -8425,9 +8836,9 @@ function routeErc20NonBase() {
8425
8836
  message: "Failed to simulate deposit token approve."
8426
8837
  }
8427
8838
  );
8428
- approvals.push({ token: p.token, spender: assetRouter, amount: p.amount });
8839
+ approvals.push({ token: p.token, spender: nativeTokenVault, amount: p.amount });
8429
8840
  steps.push({
8430
- key: `approve:${p.token}:${assetRouter}`,
8841
+ key: `approve:${p.token}:${nativeTokenVault}`,
8431
8842
  kind: "approve",
8432
8843
  description: `Approve deposit token for amount`,
8433
8844
  tx: approveTx
@@ -8441,10 +8852,10 @@ function routeErc20NonBase() {
8441
8852
  address: baseToken,
8442
8853
  abi: IERC20_default,
8443
8854
  functionName: "allowance",
8444
- args: [ctx.sender, assetRouter]
8855
+ args: [ctx.sender, nativeTokenVault]
8445
8856
  }),
8446
8857
  {
8447
- ctx: { where: "erc20.allowance", token: baseToken, spender: assetRouter },
8858
+ ctx: { where: "erc20.allowance", token: baseToken, spender: nativeTokenVault },
8448
8859
  message: "Failed to read base-token allowance."
8449
8860
  }
8450
8861
  );
@@ -8455,7 +8866,7 @@ function routeErc20NonBase() {
8455
8866
  () => buildApprovalRequest({
8456
8867
  ctx,
8457
8868
  token: baseToken,
8458
- spender: assetRouter,
8869
+ spender: nativeTokenVault,
8459
8870
  amount: mintValue
8460
8871
  }),
8461
8872
  {
@@ -8463,9 +8874,9 @@ function routeErc20NonBase() {
8463
8874
  message: "Failed to simulate base token approve."
8464
8875
  }
8465
8876
  );
8466
- approvals.push({ token: baseToken, spender: assetRouter, amount: mintValue });
8877
+ approvals.push({ token: baseToken, spender: nativeTokenVault, amount: mintValue });
8467
8878
  steps.push({
8468
- key: `approve:${baseToken}:${assetRouter}`,
8879
+ key: `approve:${baseToken}:${nativeTokenVault}`,
8469
8880
  kind: "approve",
8470
8881
  description: `Approve base token for mintValue`,
8471
8882
  tx: approveBaseTx
@@ -8604,9 +9015,18 @@ async function getPriorityGasModel2(input) {
8604
9015
  gasPerPubdata: input.ctx.gasPerPubdata
8605
9016
  });
8606
9017
  const model = {
8607
- priorityFloorGasLimit: applyPriorityL2GasLimitBuffer({
8608
- chainIdL2: input.ctx.chainIdL2,
8609
- gasLimit: priorityFloorBreakdown.derivedL2GasLimit
9018
+ priorityTxL2Leg: {
9019
+ from: applyL1ToL2Alias(input.ctx.l1AssetRouter),
9020
+ to: L2_ASSET_ROUTER_ADDRESS,
9021
+ data: l2Calldata
9022
+ },
9023
+ priorityFloorGasLimit: clampPriorityL2GasLimit({
9024
+ gasLimit: applyPriorityL2GasLimitBuffer({
9025
+ chainIdL2: input.ctx.chainIdL2,
9026
+ gasLimit: priorityFloorBreakdown.derivedL2GasLimit
9027
+ }),
9028
+ l2Calldata,
9029
+ gasPerPubdata: input.ctx.gasPerPubdata
8610
9030
  })
8611
9031
  };
8612
9032
  if (input.ctx.resolvedToken.l2.toLowerCase() === viem.zeroAddress) {
@@ -8681,6 +9101,7 @@ function routeEthNonBase() {
8681
9101
  ctx,
8682
9102
  modelTx: l2TxModel,
8683
9103
  priorityFloorGasLimit: priorityGasModel.priorityFloorGasLimit,
9104
+ priorityTxL2Leg: priorityGasModel.priorityTxL2Leg,
8684
9105
  undeployedGasLimit: priorityGasModel.undeployedGasLimit
8685
9106
  });
8686
9107
  if (!l2Gas) throw new Error("Failed to estimate L2 gas parameters.");
@@ -8695,10 +9116,10 @@ function routeEthNonBase() {
8695
9116
  address: baseToken,
8696
9117
  abi: IERC20_default,
8697
9118
  functionName: "allowance",
8698
- args: [ctx.sender, ctx.l1AssetRouter]
9119
+ args: [ctx.sender, ctx.l1NativeTokenVault]
8699
9120
  }),
8700
9121
  {
8701
- ctx: { where: "erc20.allowance", token: baseToken, spender: ctx.l1AssetRouter },
9122
+ ctx: { where: "erc20.allowance", token: baseToken, spender: ctx.l1NativeTokenVault },
8702
9123
  message: "Failed to read base-token allowance."
8703
9124
  }
8704
9125
  );
@@ -8710,7 +9131,7 @@ function routeEthNonBase() {
8710
9131
  () => buildApprovalRequest({
8711
9132
  ctx,
8712
9133
  token: baseToken,
8713
- spender: ctx.l1AssetRouter,
9134
+ spender: ctx.l1NativeTokenVault,
8714
9135
  amount: mintValue
8715
9136
  }),
8716
9137
  {
@@ -8718,9 +9139,9 @@ function routeEthNonBase() {
8718
9139
  message: "Failed to simulate base-token approve."
8719
9140
  }
8720
9141
  );
8721
- approvals.push({ token: baseToken, spender: ctx.l1AssetRouter, amount: mintValue });
9142
+ approvals.push({ token: baseToken, spender: ctx.l1NativeTokenVault, amount: mintValue });
8722
9143
  steps.push({
8723
- key: `approve:${baseToken}:${ctx.l1AssetRouter}`,
9144
+ key: `approve:${baseToken}:${ctx.l1NativeTokenVault}`,
8724
9145
  kind: "approve",
8725
9146
  description: `Approve base token for fees (mintValue)`,
8726
9147
  tx: approveTx
@@ -8873,9 +9294,13 @@ function routeErc20Base() {
8873
9294
  l2Calldata,
8874
9295
  gasPerPubdata: ctx.gasPerPubdata
8875
9296
  });
8876
- const quotedL2GasLimit = ctx.l2GasLimit ?? applyPriorityL2GasLimitBuffer({
8877
- chainIdL2: ctx.chainIdL2,
8878
- gasLimit: priorityFloorBreakdown.derivedL2GasLimit
9297
+ const quotedL2GasLimit = ctx.l2GasLimit ?? clampPriorityL2GasLimit({
9298
+ gasLimit: applyPriorityL2GasLimitBuffer({
9299
+ chainIdL2: ctx.chainIdL2,
9300
+ gasLimit: priorityFloorBreakdown.derivedL2GasLimit
9301
+ }),
9302
+ l2Calldata,
9303
+ gasPerPubdata: ctx.gasPerPubdata
8879
9304
  });
8880
9305
  const l2Gas = await quoteL2Gas2({
8881
9306
  ctx,
@@ -8894,10 +9319,10 @@ function routeErc20Base() {
8894
9319
  address: baseToken,
8895
9320
  abi: IERC20_default,
8896
9321
  functionName: "allowance",
8897
- args: [ctx.sender, ctx.l1AssetRouter]
9322
+ args: [ctx.sender, ctx.l1NativeTokenVault]
8898
9323
  }),
8899
9324
  {
8900
- ctx: { where: "erc20.allowance", token: baseToken, spender: ctx.l1AssetRouter },
9325
+ ctx: { where: "erc20.allowance", token: baseToken, spender: ctx.l1NativeTokenVault },
8901
9326
  message: "Failed to read base-token allowance."
8902
9327
  }
8903
9328
  );
@@ -8909,7 +9334,7 @@ function routeErc20Base() {
8909
9334
  () => buildApprovalRequest({
8910
9335
  ctx,
8911
9336
  token: baseToken,
8912
- spender: ctx.l1AssetRouter,
9337
+ spender: ctx.l1NativeTokenVault,
8913
9338
  amount: mintValue
8914
9339
  }),
8915
9340
  {
@@ -8917,9 +9342,9 @@ function routeErc20Base() {
8917
9342
  message: "Failed to simulate ERC-20 approve."
8918
9343
  }
8919
9344
  );
8920
- approvals.push({ token: baseToken, spender: ctx.l1AssetRouter, amount: mintValue });
9345
+ approvals.push({ token: baseToken, spender: ctx.l1NativeTokenVault, amount: mintValue });
8921
9346
  steps.push({
8922
- key: `approve:${baseToken}:${ctx.l1AssetRouter}`,
9347
+ key: `approve:${baseToken}:${ctx.l1NativeTokenVault}`,
8923
9348
  kind: "approve",
8924
9349
  description: "Approve base token for mintValue",
8925
9350
  tx: approveTx
@@ -9165,8 +9590,17 @@ function createTokensResource(client) {
9165
9590
  const chainId = BigInt(await client.l2.getChainId());
9166
9591
  return await client.baseToken(chainId);
9167
9592
  }
9168
- const { l2AssetRouter } = await client.contracts();
9169
- const l1Token = await l2AssetRouter.read.l1TokenAddress([l2Token]);
9593
+ const { l2NativeTokenVault, l1NativeTokenVault } = await client.contracts();
9594
+ const assetId = await l2NativeTokenVault.read.assetId([l2Token]);
9595
+ if (BigInt(assetId) === 0n) {
9596
+ throw new Error(`Token ${l2Token} is not registered in the L2 NativeTokenVault.`);
9597
+ }
9598
+ const l1Token = await l1NativeTokenVault.read.tokenAddress([assetId]);
9599
+ if (BigInt(l1Token) === 0n) {
9600
+ throw new Error(
9601
+ `Token ${l2Token} has no L1 counterpart registered in the L1 NativeTokenVault.`
9602
+ );
9603
+ }
9170
9604
  return l1Token;
9171
9605
  });
9172
9606
  }
@@ -9691,7 +10125,7 @@ function pickWithdrawRoute(args) {
9691
10125
  }
9692
10126
 
9693
10127
  // src/adapters/viem/resources/withdrawals/context.ts
9694
- async function commonCtx2(p, client, tokens, contracts) {
10128
+ async function commonCtx2(p, client, tokens, contracts, protocol) {
9695
10129
  const sender = client.account.address;
9696
10130
  const {
9697
10131
  bridgehub,
@@ -9699,9 +10133,11 @@ async function commonCtx2(p, client, tokens, contracts) {
9699
10133
  l1Nullifier,
9700
10134
  l2AssetRouter,
9701
10135
  l2NativeTokenVault,
9702
- l2BaseTokenSystem
10136
+ l2BaseTokenSystem,
10137
+ interopCenter
9703
10138
  } = await contracts.addresses();
9704
10139
  const chainIdL2 = BigInt(await client.l2.getChainId());
10140
+ const l1ChainId = BigInt(await client.l1.getChainId());
9705
10141
  const resolvedToken = await tokens.resolve(p.token, { chain: "l2" });
9706
10142
  const baseTokenAssetId = resolvedToken.baseTokenAssetId;
9707
10143
  const baseTokenL1 = await tokens.l1TokenFromAssetId(baseTokenAssetId);
@@ -9723,6 +10159,9 @@ async function commonCtx2(p, client, tokens, contracts) {
9723
10159
  l2AssetRouter,
9724
10160
  l2NativeTokenVault,
9725
10161
  l2BaseTokenSystem,
10162
+ interopCenter,
10163
+ protocol,
10164
+ l1ChainId,
9726
10165
  baseIsEth,
9727
10166
  gasOverrides: p.l2TxOverrides ? toGasOverrides(p.l2TxOverrides) : void 0
9728
10167
  };
@@ -10032,6 +10471,285 @@ function routeErc20NonBase2() {
10032
10471
  }
10033
10472
  };
10034
10473
  }
10474
+ var PREFIX_EVM_CHAIN = viem.toBytes("0x00010000");
10475
+ var PREFIX_EVM_ADDRESS = viem.toBytes("0x000100000014");
10476
+ function formatInteropEvmChain(chainId) {
10477
+ const chainRef = viem.toBytes(viem.toHex(chainId));
10478
+ const chainRefLength = viem.toBytes(viem.toHex(chainRef.length, { size: 1 }));
10479
+ const payload = viem.concat([PREFIX_EVM_CHAIN, chainRefLength, chainRef, new Uint8Array([0])]);
10480
+ return viem.toHex(payload);
10481
+ }
10482
+ function formatInteropEvmAddress(address) {
10483
+ const normalized = viem.getAddress(address);
10484
+ const addrBytes = viem.toBytes(normalized);
10485
+ const payload = viem.concat([PREFIX_EVM_ADDRESS, addrBytes]);
10486
+ return viem.toHex(payload);
10487
+ }
10488
+ var interopCodec = {
10489
+ formatChain: formatInteropEvmChain,
10490
+ formatAddress: formatInteropEvmAddress
10491
+ };
10492
+
10493
+ // src/core/resources/interop/attributes/call.ts
10494
+ function createCallAttributes(codec) {
10495
+ const indirectCall = (messageValue) => codec.encode("indirectCall", [messageValue]);
10496
+ const interopCallValue = (bridgedAmount) => codec.encode("interopCallValue", [bridgedAmount]);
10497
+ return {
10498
+ indirectCall,
10499
+ interopCallValue
10500
+ };
10501
+ }
10502
+
10503
+ // src/core/resources/interop/attributes/bundle.ts
10504
+ function createBundleAttributes(codec) {
10505
+ const executionAddress = (executor) => codec.encode("executionAddress", [executor]);
10506
+ const unbundlerAddress = (addr) => codec.encode("unbundlerAddress", [addr]);
10507
+ const useFixedFee = (enabled) => codec.encode("useFixedFee", [enabled]);
10508
+ const interopBundleSalt = (salt) => codec.encode("interopBundleSalt", [salt]);
10509
+ return {
10510
+ executionAddress,
10511
+ unbundlerAddress,
10512
+ useFixedFee,
10513
+ interopBundleSalt
10514
+ };
10515
+ }
10516
+
10517
+ // src/core/resources/interop/attributes/resource.ts
10518
+ function createAttributesResource(codec) {
10519
+ return {
10520
+ call: createCallAttributes(codec),
10521
+ bundle: createBundleAttributes(codec)
10522
+ };
10523
+ }
10524
+
10525
+ // src/adapters/viem/resources/interop/attributes/resource.ts
10526
+ function getInteropAttributes(params, ctx) {
10527
+ const bundleAttributes = [];
10528
+ if (params.execution?.only) {
10529
+ bundleAttributes.push(ctx.attributes.bundle.executionAddress(params.execution.only));
10530
+ }
10531
+ if (params.unbundling?.by) {
10532
+ bundleAttributes.push(ctx.attributes.bundle.unbundlerAddress(params.unbundling.by));
10533
+ }
10534
+ bundleAttributes.push(ctx.attributes.bundle.useFixedFee(params.fee?.useFixed ?? false));
10535
+ const callAttributes = params.actions.map((action) => {
10536
+ switch (action.type) {
10537
+ case "sendNative": {
10538
+ const baseMatches = ctx.baseTokens.src.toLowerCase() === ctx.baseTokens.dst.toLowerCase();
10539
+ if (baseMatches) {
10540
+ return [ctx.attributes.call.interopCallValue(action.amount)];
10541
+ }
10542
+ return [ctx.attributes.call.indirectCall(action.amount)];
10543
+ }
10544
+ case "call":
10545
+ if (action.value && action.value > 0n) {
10546
+ return [ctx.attributes.call.interopCallValue(action.value)];
10547
+ }
10548
+ return [];
10549
+ case "sendErc20":
10550
+ return [ctx.attributes.call.indirectCall(0n)];
10551
+ default:
10552
+ assertNever(action);
10553
+ }
10554
+ });
10555
+ return { bundleAttributes, callAttributes };
10556
+ }
10557
+ function createViemAttributesResource() {
10558
+ const encode = (fn, args) => viem.encodeFunctionData({
10559
+ abi: IERC7786Attributes_default,
10560
+ functionName: fn,
10561
+ args
10562
+ });
10563
+ return createAttributesResource({ encode });
10564
+ }
10565
+
10566
+ // src/core/resources/withdrawals/bundle.ts
10567
+ function buildWithdrawalBundle(input) {
10568
+ const {
10569
+ assetId,
10570
+ amount,
10571
+ l1Receiver,
10572
+ l2Token,
10573
+ isBaseToken,
10574
+ l1ChainId,
10575
+ l2AssetRouter,
10576
+ salt,
10577
+ codec,
10578
+ attributes: attributes2,
10579
+ transferData
10580
+ } = input;
10581
+ const burnData = transferData.encodeBridgeBurnData(amount, l1Receiver, l2Token);
10582
+ const depositData = transferData.encodeAssetRouterDepositData(assetId, burnData);
10583
+ const indirectCallMessageValue = isBaseToken ? amount : 0n;
10584
+ const starter = [
10585
+ codec.formatAddress(l2AssetRouter),
10586
+ depositData,
10587
+ [attributes2.indirectCall(indirectCallMessageValue), attributes2.interopCallValue(0n)]
10588
+ ];
10589
+ return {
10590
+ destinationChain: codec.formatChain(l1ChainId),
10591
+ starters: [starter],
10592
+ // No `atomicBundle` attribute: L2 -> L1 withdrawals are non-atomic and are published to L1 as a
10593
+ // `BUNDLE_IDENTIFIER`-prefixed message, which is what the L1 handler proves inclusion of.
10594
+ bundleAttributes: [attributes2.interopBundleSalt(salt)],
10595
+ value: indirectCallMessageValue
10596
+ };
10597
+ }
10598
+
10599
+ // src/adapters/viem/resources/withdrawals/routes/interop-bundle.ts
10600
+ var { wrapAs: wrapAs9 } = createErrorHandlers("withdrawals");
10601
+ var attributes = createViemAttributesResource();
10602
+ function saltFor(sender, nonce) {
10603
+ return viem.keccak256(
10604
+ viem.encodeAbiParameters(
10605
+ [
10606
+ { type: "address", name: "sender" },
10607
+ { type: "uint256", name: "nonce" }
10608
+ ],
10609
+ [sender, BigInt(nonce)]
10610
+ )
10611
+ );
10612
+ }
10613
+ function routeInteropBundle() {
10614
+ return {
10615
+ async build(p, ctx) {
10616
+ const steps = [];
10617
+ const approvals = [];
10618
+ const isBaseToken = ctx.route === "base";
10619
+ const l1Receiver = p.to ?? ctx.sender;
10620
+ let assetId;
10621
+ let allowanceSufficient = true;
10622
+ if (isBaseToken) {
10623
+ assetId = ctx.baseTokenAssetId;
10624
+ } else {
10625
+ assetId = (await wrapAs9(
10626
+ "CONTRACT",
10627
+ OP_WITHDRAWALS.erc20.ensureRegistered,
10628
+ () => ctx.client.l2.simulateContract({
10629
+ address: ctx.l2NativeTokenVault,
10630
+ abi: L2NativeTokenVault_default,
10631
+ functionName: "ensureTokenIsRegistered",
10632
+ args: [p.token],
10633
+ account: ctx.client.account
10634
+ }),
10635
+ {
10636
+ ctx: { where: "L2NativeTokenVault.ensureTokenIsRegistered", token: p.token },
10637
+ message: "Failed to ensure token is registered in L2NativeTokenVault."
10638
+ }
10639
+ )).result;
10640
+ const current = await wrapAs9(
10641
+ "CONTRACT",
10642
+ OP_WITHDRAWALS.erc20.allowance,
10643
+ () => ctx.client.l2.readContract({
10644
+ address: p.token,
10645
+ abi: IERC20_default,
10646
+ functionName: "allowance",
10647
+ args: [ctx.sender, ctx.l2NativeTokenVault],
10648
+ account: ctx.client.account
10649
+ }),
10650
+ {
10651
+ ctx: {
10652
+ where: "erc20.allowance",
10653
+ chain: "L2",
10654
+ token: p.token,
10655
+ spender: ctx.l2NativeTokenVault
10656
+ },
10657
+ message: "Failed to read L2 ERC-20 allowance."
10658
+ }
10659
+ );
10660
+ allowanceSufficient = current >= p.amount;
10661
+ if (!allowanceSufficient) {
10662
+ approvals.push({ token: p.token, spender: ctx.l2NativeTokenVault, amount: p.amount });
10663
+ const approveTxCandidate = {
10664
+ to: p.token,
10665
+ data: viem.encodeFunctionData({
10666
+ abi: IERC20_default,
10667
+ functionName: "approve",
10668
+ args: [ctx.l2NativeTokenVault, p.amount]
10669
+ }),
10670
+ value: 0n,
10671
+ from: ctx.sender
10672
+ };
10673
+ const approveGas = await quoteL2Gas4({ ctx, tx: approveTxCandidate });
10674
+ steps.push({
10675
+ key: `approve:l2:${p.token}:${ctx.l2NativeTokenVault}`,
10676
+ kind: "approve:l2",
10677
+ description: `Approve ${p.amount} to NativeTokenVault`,
10678
+ tx: {
10679
+ address: p.token,
10680
+ abi: IERC20_default,
10681
+ functionName: "approve",
10682
+ args: [ctx.l2NativeTokenVault, p.amount],
10683
+ account: ctx.client.account,
10684
+ ...approveGas
10685
+ }
10686
+ });
10687
+ }
10688
+ }
10689
+ const nonce = await wrapAs9(
10690
+ "RPC",
10691
+ OP_WITHDRAWALS.prepare,
10692
+ () => ctx.client.l2.getTransactionCount({ address: ctx.sender, blockTag: "pending" }),
10693
+ {
10694
+ ctx: { where: "l2.getTransactionCount", sender: ctx.sender },
10695
+ message: "Failed to read L2 nonce for the interop bundle salt."
10696
+ }
10697
+ );
10698
+ const bundle = buildWithdrawalBundle({
10699
+ assetId,
10700
+ amount: p.amount,
10701
+ l1Receiver,
10702
+ l2Token: isBaseToken ? FORMAL_ETH_ADDRESS : p.token,
10703
+ isBaseToken,
10704
+ l1ChainId: ctx.l1ChainId,
10705
+ l2AssetRouter: ctx.l2AssetRouter,
10706
+ salt: saltFor(ctx.sender, nonce),
10707
+ codec: interopCodec,
10708
+ attributes: {
10709
+ indirectCall: attributes.call.indirectCall,
10710
+ interopCallValue: attributes.call.interopCallValue,
10711
+ interopBundleSalt: attributes.bundle.interopBundleSalt
10712
+ },
10713
+ transferData: {
10714
+ encodeBridgeBurnData: encodeNativeTokenVaultTransferData,
10715
+ encodeAssetRouterDepositData: encodeSecondBridgeDataV1
10716
+ }
10717
+ });
10718
+ const sendArgs = [bundle.destinationChain, bundle.starters, bundle.bundleAttributes];
10719
+ const sendTxCandidate = {
10720
+ to: ctx.interopCenter,
10721
+ data: viem.encodeFunctionData({
10722
+ abi: IInteropCenter_default,
10723
+ functionName: "sendBundle",
10724
+ args: sendArgs
10725
+ }),
10726
+ value: bundle.value,
10727
+ from: ctx.sender
10728
+ };
10729
+ const sendGas = allowanceSufficient ? await quoteL2Gas4({ ctx, tx: sendTxCandidate }) : void 0;
10730
+ const sendTx = {
10731
+ address: ctx.interopCenter,
10732
+ abi: IInteropCenter_default,
10733
+ functionName: "sendBundle",
10734
+ args: sendArgs,
10735
+ account: ctx.client.account,
10736
+ value: bundle.value,
10737
+ ...sendGas
10738
+ };
10739
+ steps.push({
10740
+ key: "interop-center:send-bundle",
10741
+ kind: "interop-center:send-bundle",
10742
+ description: "Burn on L2 & send L2\u2192L1 withdrawal bundle",
10743
+ tx: sendTx
10744
+ });
10745
+ const fees = buildFeeBreakdown2({
10746
+ feeToken: ctx.baseTokenL1 ?? await ctx.client.baseToken(ctx.chainIdL2),
10747
+ l2Gas: sendGas
10748
+ });
10749
+ return { steps, approvals, fees };
10750
+ }
10751
+ };
10752
+ }
10035
10753
 
10036
10754
  // src/core/utils/events.ts
10037
10755
  function extractPreferAddress(opts) {
@@ -10066,21 +10784,145 @@ function l1MessageSentSender(log) {
10066
10784
  if (!sender) {
10067
10785
  throw new Error("L1MessageSent log has no valid sender topic.");
10068
10786
  }
10069
- return `0x${sender.toLowerCase()}`;
10787
+ return `0x${sender.toLowerCase()}`;
10788
+ }
10789
+
10790
+ // src/core/resources/withdrawals/logs.ts
10791
+ function messengerLogIndex(raw, opts) {
10792
+ const index = opts?.index;
10793
+ const messenger = (opts?.messenger).toLowerCase();
10794
+ const arr = Array.isArray(raw?.l2ToL1Logs) ? raw.l2ToL1Logs : [];
10795
+ const hits = arr.map((lg, i) => ({ i, lg })).filter(({ lg }) => (lg?.sender ?? "").toLowerCase() === messenger);
10796
+ if (!hits.length) {
10797
+ throw new Error("No L2->L1 messenger logs found in receipt.");
10798
+ }
10799
+ return (hits[index] ?? hits[0]).i;
10800
+ }
10801
+ function keccakHex(data) {
10802
+ return `0x${utils.bytesToHex(sha3.keccak_256(utils.hexToBytes(data.slice(2))))}`;
10803
+ }
10804
+ function stripBundleIdentifier(messageData) {
10805
+ const prefix = `0x${messageData.slice(2, 4)}`;
10806
+ if (prefix !== BUNDLE_IDENTIFIER) {
10807
+ throw createError("STATE", {
10808
+ resource: "withdrawals",
10809
+ operation: OP_WITHDRAWALS.finalize.fetchParams.decodeMessage,
10810
+ message: "L2\u2192L1 message is not an interop bundle. This withdrawal was most likely initiated before the chain upgraded to protocol v32 and cannot be finalized through the interop handler.",
10811
+ context: { prefix, expected: BUNDLE_IDENTIFIER }
10812
+ });
10813
+ }
10814
+ return `0x${messageData.slice(4)}`;
10815
+ }
10816
+ function parseBundleHashFromLogs(logs, interopCenter = L2_INTEROP_CENTER_ADDRESS) {
10817
+ const center = interopCenter.toLowerCase();
10818
+ for (const log of logs) {
10819
+ if (log.address?.toLowerCase() !== center) continue;
10820
+ if (log.topics?.length !== 1) continue;
10821
+ if (!log.data || (log.data.length - 2) / 64 < 3) continue;
10822
+ return `0x${log.data.slice(66, 130)}`;
10823
+ }
10824
+ return void 0;
10825
+ }
10826
+ function buildWithdrawalFinalization(input) {
10827
+ const { messageData, sourceChainId, txNumberInBatch, proof } = input;
10828
+ const bundle = stripBundleIdentifier(messageData);
10829
+ return {
10830
+ bundle,
10831
+ bundleHash: input.bundleHash ?? keccakHex(bundle),
10832
+ proof: {
10833
+ chainId: sourceChainId,
10834
+ l1BatchNumber: proof.batchNumber,
10835
+ l2MessageIndex: proof.id,
10836
+ message: {
10837
+ txNumberInBatch,
10838
+ sender: input.interopCenter ?? L2_INTEROP_CENTER_ADDRESS,
10839
+ data: messageData
10840
+ },
10841
+ proof: proof.proof
10842
+ }
10843
+ };
10844
+ }
10845
+ function classifyWithdrawalOutcome(bundleStatus, callStatus) {
10846
+ if (bundleStatus === 2 /* FullyExecuted */) return "finalized";
10847
+ if (bundleStatus !== 3 /* Unbundled */) return "pending";
10848
+ switch (callStatus) {
10849
+ case 1 /* Executed */:
10850
+ return "finalized";
10851
+ case 2 /* Cancelled */:
10852
+ return "failed";
10853
+ default:
10854
+ return "pending";
10855
+ }
10856
+ }
10857
+
10858
+ // src/core/resources/withdrawals/protocol.ts
10859
+ var MIN_INTEROP_WITHDRAWAL_MINOR = 32;
10860
+ function protocolFromVersion(version) {
10861
+ const [, minor] = version;
10862
+ return minor >= MIN_INTEROP_WITHDRAWAL_MINOR ? "interop-bundle" : "legacy-withdrawal";
10863
+ }
10864
+ async function detectWithdrawalProtocol(probes, override) {
10865
+ if (override) {
10866
+ return { protocol: override, source: { via: "override" } };
10867
+ }
10868
+ const version = await probes.protocolVersion();
10869
+ if (version) {
10870
+ return { protocol: protocolFromVersion(version), source: { via: "protocol-version", version } };
10871
+ }
10872
+ if (await probes.hasCodeAt(L2_INTEROP_ATTRIBUTE_PARSER_ADDRESS)) {
10873
+ return {
10874
+ protocol: "interop-bundle",
10875
+ source: { via: "code-probe", address: L2_INTEROP_ATTRIBUTE_PARSER_ADDRESS }
10876
+ };
10877
+ }
10878
+ return {
10879
+ protocol: "legacy-withdrawal",
10880
+ source: { via: "code-probe", address: L2_INTEROP_ATTRIBUTE_PARSER_ADDRESS }
10881
+ };
10070
10882
  }
10071
10883
 
10072
- // src/core/resources/withdrawals/logs.ts
10073
- function messengerLogIndex(raw, opts) {
10074
- const index = opts?.index;
10075
- const messenger = (opts?.messenger).toLowerCase();
10076
- const arr = Array.isArray(raw?.l2ToL1Logs) ? raw.l2ToL1Logs : [];
10077
- const hits = arr.map((lg, i) => ({ i, lg })).filter(({ lg }) => (lg?.sender ?? "").toLowerCase() === messenger);
10078
- if (!hits.length) {
10079
- throw new Error("No L2->L1 messenger logs found in receipt.");
10884
+ // src/adapters/viem/resources/withdrawals/services/protocol.ts
10885
+ function createWithdrawalProtocolService(client, override) {
10886
+ let cached;
10887
+ async function hasCodeAt(address) {
10888
+ try {
10889
+ const code = await client.l2.getCode({ address });
10890
+ return !!code && code !== "0x";
10891
+ } catch {
10892
+ return false;
10893
+ }
10080
10894
  }
10081
- return (hits[index] ?? hits[0]).i;
10895
+ async function protocolVersion() {
10896
+ try {
10897
+ return await client.getChainProtocolVersion();
10898
+ } catch {
10899
+ return void 0;
10900
+ }
10901
+ }
10902
+ function detect() {
10903
+ cached ??= detectWithdrawalProtocol(
10904
+ {
10905
+ protocolVersion,
10906
+ hasCodeAt
10907
+ },
10908
+ override
10909
+ ).catch((e) => {
10910
+ cached = void 0;
10911
+ throw e;
10912
+ });
10913
+ return cached;
10914
+ }
10915
+ return {
10916
+ detect,
10917
+ async protocol() {
10918
+ return (await detect()).protocol;
10919
+ },
10920
+ refresh() {
10921
+ cached = void 0;
10922
+ }
10923
+ };
10082
10924
  }
10083
- var { wrapAs: wrapAs9 } = createErrorHandlers("withdrawals");
10925
+ var { wrapAs: wrapAs10 } = createErrorHandlers("withdrawals");
10084
10926
  var IL1NullifierMini = [
10085
10927
  {
10086
10928
  type: "function",
@@ -10094,183 +10936,279 @@ var IL1NullifierMini = [
10094
10936
  outputs: [{ type: "bool" }]
10095
10937
  }
10096
10938
  ];
10097
- function createFinalizationServices(client) {
10098
- return {
10099
- async fetchFinalizeDepositParams(l2TxHash) {
10100
- const parsed = await wrapAs9(
10101
- "RPC",
10102
- OP_WITHDRAWALS.finalize.fetchParams.receipt,
10103
- () => client.zks.getReceiptWithL2ToL1(l2TxHash),
10104
- {
10105
- ctx: { where: "getReceiptWithL2ToL1", l2TxHash },
10106
- message: "Failed to fetch L2 receipt (with L2\u2192L1 logs)."
10939
+ function createFinalizationServices(client, protocolService = createWithdrawalProtocolService(client)) {
10940
+ async function finalizationTarget(protocol) {
10941
+ const { l1Nullifier } = await client.ensureAddresses();
10942
+ if (protocol === "legacy-withdrawal") return l1Nullifier;
10943
+ return await wrapAs10(
10944
+ "CONTRACT",
10945
+ OP_WITHDRAWALS.finalize.fetchParams.receipt,
10946
+ () => client.l1.readContract({
10947
+ address: l1Nullifier,
10948
+ abi: IL1NullifierV32_default,
10949
+ functionName: "l1InteropHandler"
10950
+ }),
10951
+ {
10952
+ ctx: { where: "L1Nullifier.l1InteropHandler", l1Nullifier },
10953
+ message: "Failed to resolve the L1 interop handler. The chain reports protocol v32+, but its L1Nullifier does not expose `l1InteropHandler()`."
10954
+ }
10955
+ );
10956
+ }
10957
+ async function fetchMessageAndProof(l2TxHash) {
10958
+ const raw = await wrapAs10(
10959
+ "RPC",
10960
+ OP_WITHDRAWALS.finalize.fetchParams.receipt,
10961
+ () => client.zks.getReceiptWithL2ToL1(l2TxHash),
10962
+ {
10963
+ ctx: { where: "getReceiptWithL2ToL1", l2TxHash },
10964
+ message: "Failed to fetch L2 receipt (with L2\u2192L1 logs)."
10965
+ }
10966
+ );
10967
+ if (!raw) {
10968
+ throw createError("STATE", {
10969
+ resource: "withdrawals",
10970
+ operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
10971
+ message: "L2 receipt not found.",
10972
+ context: { l2TxHash }
10973
+ });
10974
+ }
10975
+ const ev = await wrapAs10(
10976
+ "INTERNAL",
10977
+ OP_WITHDRAWALS.finalize.fetchParams.findMessage,
10978
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
10979
+ () => Promise.resolve(findL1MessageSentLog(raw, { index: 0 })),
10980
+ {
10981
+ ctx: { l2TxHash, index: 0 },
10982
+ message: "Failed to locate L1MessageSent event in L2 receipt."
10983
+ }
10984
+ );
10985
+ const message = await wrapAs10(
10986
+ "INTERNAL",
10987
+ OP_WITHDRAWALS.finalize.fetchParams.decodeMessage,
10988
+ () => {
10989
+ const [decoded] = viem.decodeAbiParameters([{ type: "bytes" }], ev.data);
10990
+ return Promise.resolve(decoded);
10991
+ },
10992
+ {
10993
+ ctx: { where: "decode L1MessageSent", data: ev.data },
10994
+ message: "Failed to decode withdrawal message."
10995
+ }
10996
+ );
10997
+ const idx = await wrapAs10(
10998
+ "INTERNAL",
10999
+ OP_WITHDRAWALS.finalize.fetchParams.messengerIndex,
11000
+ () => Promise.resolve(messengerLogIndex(raw, { index: 0, messenger: L1_MESSENGER_ADDRESS })),
11001
+ {
11002
+ ctx: { where: "derive messenger log index", l2TxHash, receipt: raw },
11003
+ message: "Failed to derive messenger log index."
11004
+ }
11005
+ );
11006
+ const proof = await wrapAs10(
11007
+ "RPC",
11008
+ OP_WITHDRAWALS.finalize.fetchParams.proof,
11009
+ () => client.zks.getL2ToL1LogProof(l2TxHash, idx),
11010
+ {
11011
+ ctx: { where: "get L2\u2192L1 log proof", l2TxHash, messengerLogIndex: idx },
11012
+ message: "Failed to fetch L2\u2192L1 log proof."
11013
+ }
11014
+ );
11015
+ const chainId = await wrapAs10(
11016
+ "RPC",
11017
+ OP_WITHDRAWALS.finalize.fetchParams.network,
11018
+ () => client.l2.getChainId(),
11019
+ { ctx: { where: "l2.getChainId" }, message: "Failed to read L2 chain id." }
11020
+ );
11021
+ const txNumberInBatch = Number(raw.transactionIndex ?? 0);
11022
+ const l2Sender = l1MessageSentSender(ev);
11023
+ return { raw, message, proof, chainId: BigInt(chainId), txNumberInBatch, l2Sender };
11024
+ }
11025
+ async function fetchFinalization(l2TxHash) {
11026
+ const protocol = await protocolService.protocol();
11027
+ const { raw, message, proof, chainId, txNumberInBatch, l2Sender } = await fetchMessageAndProof(l2TxHash);
11028
+ const target = await finalizationTarget(protocol);
11029
+ if (protocol === "legacy-withdrawal") {
11030
+ const params2 = {
11031
+ chainId,
11032
+ l2BatchNumber: proof.batchNumber,
11033
+ l2MessageIndex: proof.id,
11034
+ l2Sender,
11035
+ l2TxNumberInBatch: txNumberInBatch,
11036
+ message,
11037
+ merkleProof: proof.proof
11038
+ };
11039
+ return {
11040
+ target,
11041
+ finalization: { protocol, params: params2 },
11042
+ key: {
11043
+ chainIdL2: chainId,
11044
+ l2BatchNumber: proof.batchNumber,
11045
+ l2MessageIndex: proof.id
10107
11046
  }
10108
- );
10109
- if (!parsed) {
10110
- throw createError("STATE", {
10111
- resource: "withdrawals",
10112
- operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
10113
- message: "L2 receipt not found.",
10114
- context: { l2TxHash }
10115
- });
11047
+ };
11048
+ }
11049
+ const { interopCenter } = await client.ensureAddresses();
11050
+ const params = buildWithdrawalFinalization({
11051
+ messageData: message,
11052
+ sourceChainId: chainId,
11053
+ txNumberInBatch,
11054
+ proof: { batchNumber: proof.batchNumber, id: proof.id, proof: proof.proof },
11055
+ // Prefer the hash the InteropCenter emitted over recomputing it.
11056
+ bundleHash: parseBundleHashFromLogs(raw.logs ?? [], interopCenter),
11057
+ interopCenter
11058
+ });
11059
+ return {
11060
+ target,
11061
+ finalization: { protocol, params },
11062
+ key: {
11063
+ chainIdL2: chainId,
11064
+ l2BatchNumber: proof.batchNumber,
11065
+ l2MessageIndex: proof.id,
11066
+ bundleHash: params.bundleHash
10116
11067
  }
10117
- const ev = await wrapAs9(
10118
- "INTERNAL",
10119
- OP_WITHDRAWALS.finalize.fetchParams.findMessage,
10120
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
10121
- () => Promise.resolve(findL1MessageSentLog(parsed, { index: 0 })),
11068
+ };
11069
+ }
11070
+ async function withdrawalOutcome(finalization) {
11071
+ const target = await finalizationTarget(finalization.protocol);
11072
+ if (finalization.protocol === "legacy-withdrawal") {
11073
+ const done = await wrapAs10(
11074
+ "RPC",
11075
+ OP_WITHDRAWALS.finalize.isFinalized,
11076
+ () => client.l1.readContract({
11077
+ address: target,
11078
+ abi: IL1NullifierMini,
11079
+ functionName: "isWithdrawalFinalized",
11080
+ args: [
11081
+ finalization.params.chainId,
11082
+ finalization.params.l2BatchNumber,
11083
+ finalization.params.l2MessageIndex
11084
+ ]
11085
+ }),
10122
11086
  {
10123
- ctx: { l2TxHash, index: 0 },
10124
- message: "Failed to locate L1MessageSent event in L2 receipt."
11087
+ ctx: { where: "isWithdrawalFinalized", params: finalization.params },
11088
+ message: "Failed to read finalization status."
10125
11089
  }
10126
11090
  );
10127
- const message = await wrapAs9(
10128
- "INTERNAL",
10129
- OP_WITHDRAWALS.finalize.fetchParams.decodeMessage,
10130
- () => {
10131
- const [decoded] = viem.decodeAbiParameters([{ type: "bytes" }], ev.data);
10132
- return decoded;
10133
- },
11091
+ return done ? "finalized" : "pending";
11092
+ }
11093
+ const { bundleHash } = finalization.params;
11094
+ const status = Number(
11095
+ await wrapAs10(
11096
+ "RPC",
11097
+ OP_WITHDRAWALS.finalize.isFinalized,
11098
+ () => client.l1.readContract({
11099
+ address: target,
11100
+ abi: IInteropHandler_default,
11101
+ functionName: "bundleStatus",
11102
+ args: [bundleHash]
11103
+ }),
10134
11104
  {
10135
- ctx: { where: "decode L1MessageSent", data: ev.data },
10136
- message: "Failed to decode withdrawal message."
11105
+ ctx: { where: "L1InteropHandler.bundleStatus", bundleHash },
11106
+ message: "Failed to read bundle status."
10137
11107
  }
10138
- );
10139
- const raw = await wrapAs9(
11108
+ )
11109
+ );
11110
+ if (status !== 3 /* Unbundled */) return classifyWithdrawalOutcome(status);
11111
+ const callStatus = Number(
11112
+ await wrapAs10(
10140
11113
  "RPC",
10141
- OP_WITHDRAWALS.finalize.fetchParams.rawReceipt,
10142
- () => client.zks.getReceiptWithL2ToL1(l2TxHash),
11114
+ OP_WITHDRAWALS.finalize.isFinalized,
11115
+ () => client.l1.readContract({
11116
+ address: target,
11117
+ abi: IInteropHandler_default,
11118
+ functionName: "callStatus",
11119
+ args: [bundleHash, 0n]
11120
+ }),
10143
11121
  {
10144
- ctx: { where: "getReceiptWithL2ToL1 (raw)", l2TxHash },
10145
- message: "Failed to fetch raw L2 receipt."
11122
+ ctx: { where: "L1InteropHandler.callStatus", bundleHash },
11123
+ message: "Failed to read bundle call status."
10146
11124
  }
10147
- );
10148
- if (!raw) {
10149
- throw createError("STATE", {
11125
+ )
11126
+ );
11127
+ return classifyWithdrawalOutcome(status, callStatus);
11128
+ }
11129
+ async function isWithdrawalFinalized(finalization) {
11130
+ return await withdrawalOutcome(finalization) === "finalized";
11131
+ }
11132
+ return {
11133
+ fetchFinalization,
11134
+ isWithdrawalFinalized,
11135
+ withdrawalOutcome,
11136
+ async fetchFinalizeDepositParams(l2TxHash) {
11137
+ const resolved = await fetchFinalization(l2TxHash);
11138
+ if (resolved.finalization.protocol !== "legacy-withdrawal") {
11139
+ throw createError("VALIDATION", {
10150
11140
  resource: "withdrawals",
10151
- operation: OP_WITHDRAWALS.finalize.fetchParams.rawReceipt,
10152
- message: "Raw L2 receipt not found.",
10153
- context: { l2TxHash }
11141
+ operation: OP_WITHDRAWALS.finalize.fetchParams.receipt,
11142
+ message: "This chain finalizes withdrawals through the L1 interop handler; `finalizeDeposit` params do not exist. Use `fetchFinalization` instead.",
11143
+ context: { l2TxHash, protocol: resolved.finalization.protocol }
10154
11144
  });
10155
11145
  }
10156
- const idx = await wrapAs9(
10157
- "INTERNAL",
10158
- OP_WITHDRAWALS.finalize.fetchParams.messengerIndex,
10159
- () => Promise.resolve(messengerLogIndex(raw, { index: 0, messenger: L1_MESSENGER_ADDRESS })),
10160
- {
10161
- ctx: { where: "derive messenger log index", l2TxHash, receipt: raw },
10162
- message: "Failed to derive messenger log index."
10163
- }
10164
- );
10165
- const proof = await wrapAs9(
10166
- "RPC",
10167
- OP_WITHDRAWALS.finalize.fetchParams.proof,
10168
- () => client.zks.getL2ToL1LogProof(l2TxHash, idx),
10169
- {
10170
- ctx: { where: "get L2\u2192L1 log proof", l2TxHash, messengerLogIndex: idx },
10171
- message: "Failed to fetch L2\u2192L1 log proof."
10172
- }
10173
- );
10174
- const chainId = await wrapAs9(
10175
- "RPC",
10176
- OP_WITHDRAWALS.finalize.fetchParams.network,
10177
- () => client.l2.getChainId(),
10178
- { ctx: { where: "l2.getChainId" }, message: "Failed to read L2 chain id." }
10179
- );
10180
- const txIndex = Number(parsed.transactionIndex ?? 0);
10181
- const params = {
10182
- chainId: BigInt(chainId),
10183
- l2BatchNumber: proof.batchNumber,
10184
- l2MessageIndex: proof.id,
10185
- l2Sender: l1MessageSentSender(ev),
10186
- l2TxNumberInBatch: txIndex,
10187
- message,
10188
- merkleProof: proof.proof
10189
- };
10190
- const { l1Nullifier } = await client.ensureAddresses();
10191
- return { params, nullifier: l1Nullifier };
11146
+ return { params: resolved.finalization.params, nullifier: resolved.target };
10192
11147
  },
10193
- async simulateFinalizeReadiness(params) {
10194
- const { l1Nullifier } = await client.ensureAddresses();
11148
+ async simulateFinalizeReadiness(finalization) {
11149
+ const target = await finalizationTarget(finalization.protocol);
10195
11150
  const done = await (async () => {
10196
11151
  try {
10197
- const result = await wrapAs9(
10198
- "RPC",
10199
- OP_WITHDRAWALS.finalize.readiness.isFinalized,
10200
- () => client.l1.readContract({
10201
- address: l1Nullifier,
10202
- abi: IL1NullifierMini,
10203
- functionName: "isWithdrawalFinalized",
10204
- args: [params.chainId, params.l2BatchNumber, params.l2MessageIndex]
10205
- }),
10206
- {
10207
- ctx: { where: "isWithdrawalFinalized", params },
10208
- message: "Failed to read finalization status."
10209
- }
10210
- );
10211
- return result;
11152
+ return await isWithdrawalFinalized(finalization);
10212
11153
  } catch {
10213
11154
  return false;
10214
11155
  }
10215
11156
  })();
10216
11157
  if (done) return { kind: "FINALIZED" };
10217
11158
  try {
10218
- await client.l1.simulateContract({
10219
- address: l1Nullifier,
10220
- abi: IL1Nullifier_default,
10221
- functionName: "finalizeDeposit",
10222
- args: [params],
10223
- account: client.account
10224
- });
11159
+ if (finalization.protocol === "legacy-withdrawal") {
11160
+ await client.l1.simulateContract({
11161
+ address: target,
11162
+ abi: IL1Nullifier_default,
11163
+ functionName: "finalizeDeposit",
11164
+ args: [finalization.params],
11165
+ account: client.account
11166
+ });
11167
+ } else {
11168
+ await client.l1.simulateContract({
11169
+ address: target,
11170
+ abi: IInteropHandler_default,
11171
+ functionName: "executeBundle",
11172
+ args: [finalization.params.bundle, finalization.params.proof],
11173
+ account: client.account
11174
+ });
11175
+ }
10225
11176
  return { kind: "READY" };
10226
11177
  } catch (e) {
10227
11178
  return classifyReadinessFromRevert(e);
10228
11179
  }
10229
11180
  },
10230
- async isWithdrawalFinalized(key) {
10231
- const { l1Nullifier } = await client.ensureAddresses();
10232
- return await wrapAs9(
10233
- "RPC",
10234
- OP_WITHDRAWALS.finalize.isFinalized,
10235
- () => client.l1.readContract({
10236
- address: l1Nullifier,
10237
- abi: IL1NullifierMini,
10238
- functionName: "isWithdrawalFinalized",
10239
- args: [key.chainIdL2, key.l2BatchNumber, key.l2MessageIndex]
10240
- }),
10241
- {
10242
- ctx: { where: "isWithdrawalFinalized", key },
10243
- message: "Failed to read finalization status."
10244
- }
10245
- );
10246
- },
10247
- async estimateFinalization(params) {
10248
- const { l1Nullifier } = await client.ensureAddresses();
10249
- const gasLimit = await wrapAs9(
11181
+ async estimateFinalization(finalization) {
11182
+ const target = await finalizationTarget(finalization.protocol);
11183
+ const gasLimit = await wrapAs10(
10250
11184
  "RPC",
10251
11185
  OP_WITHDRAWALS.finalize.estimate,
10252
- () => client.l1.estimateContractGas({
10253
- address: l1Nullifier,
11186
+ () => finalization.protocol === "legacy-withdrawal" ? client.l1.estimateContractGas({
11187
+ address: target,
10254
11188
  abi: IL1Nullifier_default,
10255
11189
  functionName: "finalizeDeposit",
10256
- args: [params],
11190
+ args: [finalization.params],
11191
+ account: client.account
11192
+ }) : client.l1.estimateContractGas({
11193
+ address: target,
11194
+ abi: IInteropHandler_default,
11195
+ functionName: "executeBundle",
11196
+ args: [finalization.params.bundle, finalization.params.proof],
10257
11197
  account: client.account
10258
11198
  }),
10259
11199
  {
10260
11200
  ctx: {
10261
- where: "estimateContractGas(finalizeDeposit)",
10262
- chainIdL2: params.chainId,
10263
- l2BatchNumber: params.l2BatchNumber,
10264
- l2MessageIndex: params.l2MessageIndex,
10265
- l1Nullifier
11201
+ where: "estimateContractGas(finalize)",
11202
+ protocol: finalization.protocol,
11203
+ target
10266
11204
  },
10267
- message: "Failed to estimate gas for finalizeDeposit."
11205
+ message: "Failed to estimate gas for withdrawal finalization."
10268
11206
  }
10269
11207
  );
10270
11208
  let maxFeePerGas;
10271
11209
  let maxPriorityFeePerGas;
10272
11210
  try {
10273
- const fee = await wrapAs9(
11211
+ const fee = await wrapAs10(
10274
11212
  "RPC",
10275
11213
  OP_WITHDRAWALS.finalize.estimate,
10276
11214
  () => client.l1.estimateFeesPerGas(),
@@ -10289,32 +11227,34 @@ function createFinalizationServices(client) {
10289
11227
  })();
10290
11228
  maxPriorityFeePerGas = fee.maxPriorityFeePerGas ?? 0n;
10291
11229
  } catch {
10292
- const gasPrice = await wrapAs9(
11230
+ const gasPrice = await wrapAs10(
10293
11231
  "RPC",
10294
11232
  OP_WITHDRAWALS.finalize.estimate,
10295
11233
  () => client.l1.getGasPrice(),
10296
11234
  {
10297
11235
  ctx: { where: "getGasPrice" },
10298
- message: "Failed to read gas price for finalizeDeposit."
11236
+ message: "Failed to read gas price for withdrawal finalization."
10299
11237
  }
10300
11238
  );
10301
11239
  maxFeePerGas = gasPrice;
10302
11240
  maxPriorityFeePerGas = 0n;
10303
11241
  }
10304
- return {
10305
- gasLimit,
10306
- maxFeePerGas,
10307
- maxPriorityFeePerGas
10308
- };
11242
+ return { gasLimit, maxFeePerGas, maxPriorityFeePerGas };
10309
11243
  },
10310
- async finalizeDeposit(params) {
10311
- const { l1Nullifier } = await client.ensureAddresses();
11244
+ async finalize(finalization) {
11245
+ const target = await finalizationTarget(finalization.protocol);
10312
11246
  try {
10313
- const hash = await client.l1Wallet.writeContract({
10314
- address: l1Nullifier,
11247
+ const hash = finalization.protocol === "legacy-withdrawal" ? await client.l1Wallet.writeContract({
11248
+ address: target,
10315
11249
  abi: IL1Nullifier_default,
10316
11250
  functionName: "finalizeDeposit",
10317
- args: [params],
11251
+ args: [finalization.params],
11252
+ account: client.account
11253
+ }) : await client.l1Wallet.writeContract({
11254
+ address: target,
11255
+ abi: IInteropHandler_default,
11256
+ functionName: "executeBundle",
11257
+ args: [finalization.params.bundle, finalization.params.proof],
10318
11258
  account: client.account
10319
11259
  });
10320
11260
  return {
@@ -10328,8 +11268,8 @@ function createFinalizationServices(client) {
10328
11268
  {
10329
11269
  resource: "withdrawals",
10330
11270
  operation: OP_WITHDRAWALS.finalize.wait,
10331
- message: "Failed while waiting for finalizeDeposit transaction.",
10332
- context: { txHash: hash }
11271
+ message: "Failed while waiting for the withdrawal finalization transaction.",
11272
+ context: { txHash: hash, protocol: finalization.protocol }
10333
11273
  },
10334
11274
  e
10335
11275
  );
@@ -10342,13 +11282,8 @@ function createFinalizationServices(client) {
10342
11282
  {
10343
11283
  resource: "withdrawals",
10344
11284
  operation: OP_WITHDRAWALS.finalize.send,
10345
- message: "Failed to send finalizeDeposit transaction.",
10346
- context: {
10347
- chainIdL2: params.chainId,
10348
- l2BatchNumber: params.l2BatchNumber,
10349
- l2MessageIndex: params.l2MessageIndex,
10350
- l1Nullifier
10351
- }
11285
+ message: "Failed to send the withdrawal finalization transaction.",
11286
+ context: { protocol: finalization.protocol, target }
10352
11287
  },
10353
11288
  e
10354
11289
  );
@@ -10381,15 +11316,28 @@ var ROUTES2 = {
10381
11316
  "erc20-nonbase": routeErc20NonBase2()
10382
11317
  // AssetRouter.withdraw for non-base ERC-20s
10383
11318
  };
10384
- function createWithdrawalsResource(client, tokens, contracts) {
10385
- const svc = createFinalizationServices(client);
11319
+ var INTEROP_ROUTES = {
11320
+ base: routeInteropBundle(),
11321
+ "erc20-nonbase": routeInteropBundle()
11322
+ };
11323
+ function routeStrategy(protocol, route) {
11324
+ return protocol === "interop-bundle" ? INTEROP_ROUTES[route] : ROUTES2[route];
11325
+ }
11326
+ function createWithdrawalsResource(client, tokens, contracts, options) {
11327
+ const protocolService = createWithdrawalProtocolService(
11328
+ client,
11329
+ options?.protocol
11330
+ );
11331
+ const svc = createFinalizationServices(client, protocolService);
10386
11332
  const { wrap: wrap8, toResult: toResult3 } = createErrorHandlers("withdrawals");
10387
11333
  const tokensResource = tokens ?? createTokensResource(client);
10388
11334
  const contractsResource = contracts ?? createContractsResource(client);
10389
11335
  async function buildPlan(p) {
10390
- const ctx = await commonCtx2(p, client, tokensResource, contractsResource);
10391
- await ROUTES2[ctx.route].preflight?.(p, ctx);
10392
- const { steps, approvals, fees } = await ROUTES2[ctx.route].build(p, ctx);
11336
+ const protocol = await protocolService.protocol();
11337
+ const ctx = await commonCtx2(p, client, tokensResource, contractsResource, protocol);
11338
+ const strategy = routeStrategy(protocol, ctx.route);
11339
+ await strategy.preflight?.(p, ctx);
11340
+ const { steps, approvals, fees } = await strategy.build(p, ctx);
10393
11341
  return {
10394
11342
  route: ctx.route,
10395
11343
  summary: {
@@ -10556,21 +11504,20 @@ function createWithdrawalsResource(client, tokens, contracts) {
10556
11504
  if (!l2Rcpt) return { phase: "L2_PENDING", l2TxHash };
10557
11505
  let pack;
10558
11506
  try {
10559
- pack = await svc.fetchFinalizeDepositParams(l2TxHash);
11507
+ pack = await svc.fetchFinalization(l2TxHash);
10560
11508
  } catch {
10561
11509
  return { phase: "PENDING", l2TxHash };
10562
11510
  }
10563
- const key = {
10564
- chainIdL2: pack.params.chainId,
10565
- l2BatchNumber: pack.params.l2BatchNumber,
10566
- l2MessageIndex: pack.params.l2MessageIndex
10567
- };
11511
+ const key = pack.key;
10568
11512
  try {
10569
- const done = await svc.isWithdrawalFinalized(key);
10570
- if (done) return { phase: "FINALIZED", l2TxHash, key };
11513
+ const outcome = await svc.withdrawalOutcome(pack.finalization);
11514
+ if (outcome === "finalized") return { phase: "FINALIZED", l2TxHash, key };
11515
+ if (outcome === "failed") {
11516
+ return { phase: "UNFINALIZABLE", l2TxHash, key, reason: "bundle-cancelled" };
11517
+ }
10571
11518
  } catch {
10572
11519
  }
10573
- const readiness = await svc.simulateFinalizeReadiness(pack.params);
11520
+ const readiness = await svc.simulateFinalizeReadiness(pack.finalization);
10574
11521
  const { phase, reason } = phaseFromReadiness(readiness);
10575
11522
  return { phase, reason, l2TxHash, key };
10576
11523
  },
@@ -10664,7 +11611,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
10664
11611
  async () => {
10665
11612
  const pack = await (async () => {
10666
11613
  try {
10667
- return await svc.fetchFinalizeDepositParams(l2TxHash);
11614
+ return await svc.fetchFinalization(l2TxHash);
10668
11615
  } catch (e) {
10669
11616
  throw createError("STATE", {
10670
11617
  resource: "withdrawals",
@@ -10675,21 +11622,16 @@ function createWithdrawalsResource(client, tokens, contracts) {
10675
11622
  });
10676
11623
  }
10677
11624
  })();
10678
- const { params } = pack;
10679
- const key = {
10680
- chainIdL2: params.chainId,
10681
- l2BatchNumber: params.l2BatchNumber,
10682
- l2MessageIndex: params.l2MessageIndex
10683
- };
11625
+ const { finalization } = pack;
10684
11626
  try {
10685
- const done = await svc.isWithdrawalFinalized(key);
10686
- if (done) {
11627
+ const outcome = await svc.withdrawalOutcome(finalization);
11628
+ if (outcome === "finalized" || outcome === "failed") {
10687
11629
  const statusNow = await status(l2TxHash);
10688
11630
  return { status: statusNow };
10689
11631
  }
10690
11632
  } catch {
10691
11633
  }
10692
- const readiness = await svc.simulateFinalizeReadiness(params);
11634
+ const readiness = await svc.simulateFinalizeReadiness(finalization);
10693
11635
  if (readiness.kind === "FINALIZED") {
10694
11636
  const statusNow = await status(l2TxHash);
10695
11637
  return { status: statusNow };
@@ -10703,7 +11645,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
10703
11645
  });
10704
11646
  }
10705
11647
  try {
10706
- const tx = await svc.finalizeDeposit(params);
11648
+ const tx = await svc.finalize(finalization);
10707
11649
  finalizeCache.set(l2TxHash, tx.hash);
10708
11650
  const rcpt = await tx.wait();
10709
11651
  const statusNow = await status(l2TxHash);
@@ -10712,7 +11654,7 @@ function createWithdrawalsResource(client, tokens, contracts) {
10712
11654
  const statusNow = await status(l2TxHash);
10713
11655
  if (statusNow.phase === "FINALIZED") return { status: statusNow };
10714
11656
  try {
10715
- const again = await svc.simulateFinalizeReadiness(params);
11657
+ const again = await svc.simulateFinalizeReadiness(finalization);
10716
11658
  if (again.kind === "NOT_READY") {
10717
11659
  throw createError("STATE", {
10718
11660
  resource: "withdrawals",
@@ -10771,77 +11713,6 @@ function createWithdrawalsResource(client, tokens, contracts) {
10771
11713
  };
10772
11714
  }
10773
11715
 
10774
- // src/core/resources/interop/attributes/call.ts
10775
- function createCallAttributes(codec) {
10776
- const indirectCall = (messageValue) => codec.encode("indirectCall", [messageValue]);
10777
- const interopCallValue = (bridgedAmount) => codec.encode("interopCallValue", [bridgedAmount]);
10778
- return {
10779
- indirectCall,
10780
- interopCallValue
10781
- };
10782
- }
10783
-
10784
- // src/core/resources/interop/attributes/bundle.ts
10785
- function createBundleAttributes(codec) {
10786
- const executionAddress = (executor) => codec.encode("executionAddress", [executor]);
10787
- const unbundlerAddress = (addr) => codec.encode("unbundlerAddress", [addr]);
10788
- const useFixedFee = (enabled) => codec.encode("useFixedFee", [enabled]);
10789
- return {
10790
- executionAddress,
10791
- unbundlerAddress,
10792
- useFixedFee
10793
- };
10794
- }
10795
-
10796
- // src/core/resources/interop/attributes/resource.ts
10797
- function createAttributesResource(codec) {
10798
- return {
10799
- call: createCallAttributes(codec),
10800
- bundle: createBundleAttributes(codec)
10801
- };
10802
- }
10803
-
10804
- // src/adapters/viem/resources/interop/attributes/resource.ts
10805
- function getInteropAttributes(params, ctx) {
10806
- const bundleAttributes = [];
10807
- if (params.execution?.only) {
10808
- bundleAttributes.push(ctx.attributes.bundle.executionAddress(params.execution.only));
10809
- }
10810
- if (params.unbundling?.by) {
10811
- bundleAttributes.push(ctx.attributes.bundle.unbundlerAddress(params.unbundling.by));
10812
- }
10813
- bundleAttributes.push(ctx.attributes.bundle.useFixedFee(params.fee?.useFixed ?? false));
10814
- const callAttributes = params.actions.map((action) => {
10815
- switch (action.type) {
10816
- case "sendNative": {
10817
- const baseMatches = ctx.baseTokens.src.toLowerCase() === ctx.baseTokens.dst.toLowerCase();
10818
- if (baseMatches) {
10819
- return [ctx.attributes.call.interopCallValue(action.amount)];
10820
- }
10821
- return [ctx.attributes.call.indirectCall(action.amount)];
10822
- }
10823
- case "call":
10824
- if (action.value && action.value > 0n) {
10825
- return [ctx.attributes.call.interopCallValue(action.value)];
10826
- }
10827
- return [];
10828
- case "sendErc20":
10829
- return [ctx.attributes.call.indirectCall(0n)];
10830
- default:
10831
- assertNever(action);
10832
- }
10833
- });
10834
- return { bundleAttributes, callAttributes };
10835
- }
10836
- function createViemAttributesResource() {
10837
- const encode = (fn, args) => viem.encodeFunctionData({
10838
- abi: IERC7786Attributes_default,
10839
- functionName: fn,
10840
- args
10841
- });
10842
- return createAttributesResource({ encode });
10843
- }
10844
-
10845
11716
  // src/core/types/flows/interop.ts
10846
11717
  function isInteropMessageProof(obj) {
10847
11718
  if (typeof obj !== "object" || obj === null) return false;
@@ -11018,24 +11889,6 @@ function buildIndirectBundle(params, ctx, attrs, starterData, interopFeeInfo) {
11018
11889
  }
11019
11890
  };
11020
11891
  }
11021
- var PREFIX_EVM_CHAIN = viem.toBytes("0x00010000");
11022
- var PREFIX_EVM_ADDRESS = viem.toBytes("0x000100000014");
11023
- function formatInteropEvmChain(chainId) {
11024
- const chainRef = viem.toBytes(viem.toHex(chainId));
11025
- const chainRefLength = viem.toBytes(viem.toHex(chainRef.length, { size: 1 }));
11026
- const payload = viem.concat([PREFIX_EVM_CHAIN, chainRefLength, chainRef, new Uint8Array([0])]);
11027
- return viem.toHex(payload);
11028
- }
11029
- function formatInteropEvmAddress(address) {
11030
- const normalized = viem.getAddress(address);
11031
- const addrBytes = viem.toBytes(normalized);
11032
- const payload = viem.concat([PREFIX_EVM_ADDRESS, addrBytes]);
11033
- return viem.toHex(payload);
11034
- }
11035
- var interopCodec = {
11036
- formatChain: formatInteropEvmChain,
11037
- formatAddress: formatInteropEvmAddress
11038
- };
11039
11892
  function getErc20Tokens(params) {
11040
11893
  const erc20Tokens = /* @__PURE__ */ new Map();
11041
11894
  for (const action of params.actions) {
@@ -11217,7 +12070,7 @@ function routeIndirect() {
11217
12070
  resolveErc20AssetIds(erc20Tokens, ctx),
11218
12071
  buildFeeInfo(params, ctx, params.actions.length)
11219
12072
  ]);
11220
- const attributes = getInteropAttributes(params, ctx);
12073
+ const attributes2 = getInteropAttributes(params, ctx);
11221
12074
  const starterData = await getStarterData(params, ctx, erc20AssetIds);
11222
12075
  const bundle = buildIndirectBundle(
11223
12076
  params,
@@ -11228,7 +12081,7 @@ function routeIndirect() {
11228
12081
  l2NativeTokenVault: ctx.l2NativeTokenVault,
11229
12082
  codec: interopCodec
11230
12083
  },
11231
- attributes,
12084
+ attributes2,
11232
12085
  starterData,
11233
12086
  feeInfo
11234
12087
  );
@@ -11348,7 +12201,7 @@ async function assertInteropProtocolVersion(client, srcChainId, dstChainId) {
11348
12201
  assertProtocolVersion(srcChainId, srcProtocolVersion);
11349
12202
  assertProtocolVersion(dstChainId, dstProtocolVersion);
11350
12203
  }
11351
- async function commonCtx3(dstPublicClient, params, client, tokens, contracts, attributes) {
12204
+ async function commonCtx3(dstPublicClient, params, client, tokens, contracts, attributes2) {
11352
12205
  const sender = client.account.address;
11353
12206
  const chainId = BigInt(await client.l2.getChainId());
11354
12207
  const dstChainId = BigInt(await dstPublicClient.getChainId());
@@ -11382,7 +12235,7 @@ async function commonCtx3(dstPublicClient, params, client, tokens, contracts, at
11382
12235
  l2AssetRouter,
11383
12236
  l2NativeTokenVault,
11384
12237
  baseTokens: { src: srcBaseToken, dst: dstBaseToken, matches: baseMatches },
11385
- attributes,
12238
+ attributes: attributes2,
11386
12239
  gasOverrides: params.txOverrides ? toGasOverrides(params.txOverrides) : void 0
11387
12240
  };
11388
12241
  }
@@ -12082,7 +12935,7 @@ var ROUTES3 = {
12082
12935
  direct: routeDirect(),
12083
12936
  indirect: routeIndirect()
12084
12937
  };
12085
- function createInteropResource(client, config, tokens, contracts, attributes) {
12938
+ function createInteropResource(client, config, tokens, contracts, attributes2) {
12086
12939
  let gwProviderCache;
12087
12940
  function requireConfig() {
12088
12941
  if (!config)
@@ -12100,7 +12953,7 @@ function createInteropResource(client, config, tokens, contracts, attributes) {
12100
12953
  const svc = createInteropFinalizationServices(client);
12101
12954
  const tokensResource = tokens ?? createTokensResource(client);
12102
12955
  const contractsResource = contracts ?? createContractsResource(client);
12103
- const attributesResource = attributes ?? createViemAttributesResource();
12956
+ const attributesResource = attributes2 ?? createViemAttributesResource();
12104
12957
  async function buildPlanWithCtx(dstPublicClient, params) {
12105
12958
  const ctx = await commonCtx3(
12106
12959
  dstPublicClient,
@@ -12320,7 +13173,7 @@ function createViemSdk(client, options) {
12320
13173
  const interop = createInteropResource(client, options?.interop, tokens, contracts);
12321
13174
  return {
12322
13175
  deposits: createDepositsResource(client, tokens, contracts),
12323
- withdrawals: createWithdrawalsResource(client, tokens, contracts),
13176
+ withdrawals: createWithdrawalsResource(client, tokens, contracts, options?.withdrawals),
12324
13177
  tokens,
12325
13178
  contracts,
12326
13179
  interop
@@ -12339,6 +13192,7 @@ exports.createInteropResource = createInteropResource;
12339
13192
  exports.createTokensResource = createTokensResource;
12340
13193
  exports.createViemClient = createViemClient;
12341
13194
  exports.createViemSdk = createViemSdk;
13195
+ exports.createWithdrawalProtocolService = createWithdrawalProtocolService;
12342
13196
  exports.createWithdrawalsResource = createWithdrawalsResource;
12343
13197
  exports.decodeRevert = decodeRevert;
12344
13198
  exports.encodeNativeTokenVaultTransferData = encodeNativeTokenVaultTransferData;