@sodax/sdk 2.2.0-rc.5 → 2.2.0-rc.7

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.
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var tx_js = require('cosmjs-types/cosmos/tx/v1beta1/tx.js');
21
21
  var networks = require('@injectivelabs/networks');
22
22
  var v = require('valibot');
23
23
  var swapsApi = require('@sodax/swaps-api');
24
+ var bridgeApi = require('@sodax/bridge-api');
24
25
  var BigNumber5 = require('bignumber.js');
25
26
  var swapSdkCore = require('@pancakeswap/swap-sdk-core');
26
27
  var v3Sdk = require('@pancakeswap/v3-sdk');
@@ -122,8 +123,8 @@ function serializeCause(cause, depth) {
122
123
  }
123
124
  function sanitizeContext(value, depth) {
124
125
  const out = {};
125
- for (const [key, v12] of Object.entries(value)) {
126
- out[key] = sanitizeValue(v12, depth + 1);
126
+ for (const [key, v10] of Object.entries(value)) {
127
+ out[key] = sanitizeValue(v10, depth + 1);
127
128
  }
128
129
  return out;
129
130
  }
@@ -134,13 +135,13 @@ function sanitizeValue(value, depth) {
134
135
  if (t === "bigint") return value.toString();
135
136
  if (t === "string" || t === "number" || t === "boolean") return value;
136
137
  if (t === "function" || t === "symbol") return safeString(value);
137
- if (Array.isArray(value)) return value.map((v12) => sanitizeValue(v12, depth + 1));
138
+ if (Array.isArray(value)) return value.map((v10) => sanitizeValue(v10, depth + 1));
138
139
  if (value instanceof Date) return value.toISOString();
139
140
  if (value instanceof Map) {
140
- return Array.from(value.entries()).map(([k, v12]) => [sanitizeValue(k, depth + 1), sanitizeValue(v12, depth + 1)]);
141
+ return Array.from(value.entries()).map(([k, v10]) => [sanitizeValue(k, depth + 1), sanitizeValue(v10, depth + 1)]);
141
142
  }
142
143
  if (value instanceof Set) {
143
- return Array.from(value.values()).map((v12) => sanitizeValue(v12, depth + 1));
144
+ return Array.from(value.values()).map((v10) => sanitizeValue(v10, depth + 1));
144
145
  }
145
146
  if (value instanceof Error) return { name: value.name, message: value.message };
146
147
  if (t === "object") {
@@ -152,9 +153,9 @@ function sanitizeValue(value, depth) {
152
153
  }
153
154
  return safeString(value);
154
155
  }
155
- function safeString(v12) {
156
+ function safeString(v10) {
156
157
  try {
157
- return String(v12);
158
+ return String(v10);
158
159
  } catch {
159
160
  return "[unserializable]";
160
161
  }
@@ -366,7 +367,18 @@ var HubVaultSymbols = [
366
367
  "QQQ",
367
368
  "SGOV",
368
369
  "USO",
369
- "SLV"
370
+ "SLV",
371
+ "GOOGL",
372
+ "AMZN",
373
+ "MSFT",
374
+ "META",
375
+ "CRCL",
376
+ "COIN",
377
+ "PLTR",
378
+ "TSM",
379
+ "AMD",
380
+ "INTC",
381
+ "BABA"
370
382
  ];
371
383
  var SodaTokens = {
372
384
  sodaBNB: {
@@ -759,6 +771,116 @@ var SodaTokens = {
759
771
  chainKey: ChainKeys.SONIC_MAINNET,
760
772
  hubAsset: "0x690B92c27ac80015E57DB8cc02A81255814f49A2",
761
773
  vault: "0x690B92c27ac80015E57DB8cc02A81255814f49A2"
774
+ },
775
+ GOOGL: {
776
+ symbol: "GOOGL",
777
+ isRwa: true,
778
+ name: "Alphabet Class A \u2022 Robinhood Token",
779
+ decimals: 18,
780
+ address: "0xBdB4445a05726E26C26EA30dF0C1970DF4Cf4Be3",
781
+ chainKey: ChainKeys.SONIC_MAINNET,
782
+ hubAsset: "0xBdB4445a05726E26C26EA30dF0C1970DF4Cf4Be3",
783
+ vault: "0xBdB4445a05726E26C26EA30dF0C1970DF4Cf4Be3"
784
+ },
785
+ AMZN: {
786
+ symbol: "AMZN",
787
+ isRwa: true,
788
+ name: "Amazon \u2022 Robinhood Token",
789
+ decimals: 18,
790
+ address: "0xc467cAC3e69C2eb41Cc9b32Aa1A7a54F942243Ba",
791
+ chainKey: ChainKeys.SONIC_MAINNET,
792
+ hubAsset: "0xc467cAC3e69C2eb41Cc9b32Aa1A7a54F942243Ba",
793
+ vault: "0xc467cAC3e69C2eb41Cc9b32Aa1A7a54F942243Ba"
794
+ },
795
+ MSFT: {
796
+ symbol: "MSFT",
797
+ isRwa: true,
798
+ name: "Microsoft \u2022 Robinhood Token",
799
+ decimals: 18,
800
+ address: "0x66A3bc5a66D3c66dc42031775Ea3eedc37347FeC",
801
+ chainKey: ChainKeys.SONIC_MAINNET,
802
+ hubAsset: "0x66A3bc5a66D3c66dc42031775Ea3eedc37347FeC",
803
+ vault: "0x66A3bc5a66D3c66dc42031775Ea3eedc37347FeC"
804
+ },
805
+ META: {
806
+ symbol: "META",
807
+ isRwa: true,
808
+ name: "Meta Platforms \u2022 Robinhood Token",
809
+ decimals: 18,
810
+ address: "0xB7686E0a03542230927CAC76Fe7566656439F3c6",
811
+ chainKey: ChainKeys.SONIC_MAINNET,
812
+ hubAsset: "0xB7686E0a03542230927CAC76Fe7566656439F3c6",
813
+ vault: "0xB7686E0a03542230927CAC76Fe7566656439F3c6"
814
+ },
815
+ CRCL: {
816
+ symbol: "CRCL",
817
+ isRwa: true,
818
+ name: "Circle Internet Group \u2022 Robinhood Token",
819
+ decimals: 18,
820
+ address: "0x1e264ceEEb59F7425D64362Bf12A5b2648B6e66d",
821
+ chainKey: ChainKeys.SONIC_MAINNET,
822
+ hubAsset: "0x1e264ceEEb59F7425D64362Bf12A5b2648B6e66d",
823
+ vault: "0x1e264ceEEb59F7425D64362Bf12A5b2648B6e66d"
824
+ },
825
+ COIN: {
826
+ symbol: "COIN",
827
+ isRwa: true,
828
+ name: "Coinbase \u2022 Robinhood Token",
829
+ decimals: 18,
830
+ address: "0x5540d60F879F5D470bF9Ed7d23FFd59Acc10da0c",
831
+ chainKey: ChainKeys.SONIC_MAINNET,
832
+ hubAsset: "0x5540d60F879F5D470bF9Ed7d23FFd59Acc10da0c",
833
+ vault: "0x5540d60F879F5D470bF9Ed7d23FFd59Acc10da0c"
834
+ },
835
+ PLTR: {
836
+ symbol: "PLTR",
837
+ isRwa: true,
838
+ name: "Palantir Technologies \u2022 Robinhood Token",
839
+ decimals: 18,
840
+ address: "0xA24710Ab6A5e1ef3a7CF3a0333d8bE2bf22782DC",
841
+ chainKey: ChainKeys.SONIC_MAINNET,
842
+ hubAsset: "0xA24710Ab6A5e1ef3a7CF3a0333d8bE2bf22782DC",
843
+ vault: "0xA24710Ab6A5e1ef3a7CF3a0333d8bE2bf22782DC"
844
+ },
845
+ TSM: {
846
+ symbol: "TSM",
847
+ isRwa: true,
848
+ name: "Taiwan Semiconductor Manufacturing \u2022 Robinhood Token",
849
+ decimals: 18,
850
+ address: "0xAF9992b0cA54e014ff1EC7fA77AADE973Dba793e",
851
+ chainKey: ChainKeys.SONIC_MAINNET,
852
+ hubAsset: "0xAF9992b0cA54e014ff1EC7fA77AADE973Dba793e",
853
+ vault: "0xAF9992b0cA54e014ff1EC7fA77AADE973Dba793e"
854
+ },
855
+ AMD: {
856
+ symbol: "AMD",
857
+ isRwa: true,
858
+ name: "AMD \u2022 Robinhood Token",
859
+ decimals: 18,
860
+ address: "0xc8124Db156d8F6C7446C040c503FFEAe82383D1B",
861
+ chainKey: ChainKeys.SONIC_MAINNET,
862
+ hubAsset: "0xc8124Db156d8F6C7446C040c503FFEAe82383D1B",
863
+ vault: "0xc8124Db156d8F6C7446C040c503FFEAe82383D1B"
864
+ },
865
+ INTC: {
866
+ symbol: "INTC",
867
+ isRwa: true,
868
+ name: "Intel \u2022 Robinhood Token",
869
+ decimals: 18,
870
+ address: "0x5352F9Bf2f58720f8a8CC4D4eDEE56700Bd3d053",
871
+ chainKey: ChainKeys.SONIC_MAINNET,
872
+ hubAsset: "0x5352F9Bf2f58720f8a8CC4D4eDEE56700Bd3d053",
873
+ vault: "0x5352F9Bf2f58720f8a8CC4D4eDEE56700Bd3d053"
874
+ },
875
+ BABA: {
876
+ symbol: "BABA",
877
+ isRwa: true,
878
+ name: "Alibaba \u2022 Robinhood Token",
879
+ decimals: 18,
880
+ address: "0x1BeD0547D76F6424e9A3465b36F6dcDCF798A5cf",
881
+ chainKey: ChainKeys.SONIC_MAINNET,
882
+ hubAsset: "0x1BeD0547D76F6424e9A3465b36F6dcDCF798A5cf",
883
+ vault: "0x1BeD0547D76F6424e9A3465b36F6dcDCF798A5cf"
762
884
  }
763
885
  };
764
886
  var LsodaSymbols = ["lsodaWEETH", "lsodaWSTETH", "lsodaJITOSOL", "lsodaSUSDS"];
@@ -1552,6 +1674,15 @@ var baseSupportedTokens = {
1552
1674
  chainKey: ChainKeys.BASE_MAINNET,
1553
1675
  hubAsset: "0x348e086ab6f424dfc575a325c28624ed23973173",
1554
1676
  vault: "0x348e086ab6f424dfc575a325c28624ed23973173"
1677
+ },
1678
+ sUSDS: {
1679
+ symbol: "sUSDS",
1680
+ name: "staked USDS",
1681
+ decimals: 18,
1682
+ address: "0x5875eEE11Cf8398102FdAd704C9E96607675467a",
1683
+ chainKey: ChainKeys.BASE_MAINNET,
1684
+ hubAsset: "0x807cC73f69F1aCCC50511a0390A8544cEA71baA9",
1685
+ vault: SodaTokens.sodaSUSDS.address
1555
1686
  }
1556
1687
  };
1557
1688
  var optimismSupportedTokens = {
@@ -1635,6 +1766,15 @@ var optimismSupportedTokens = {
1635
1766
  chainKey: ChainKeys.OPTIMISM_MAINNET,
1636
1767
  hubAsset: "0xd08375176410febee9cf4591532455a4cdfe4463",
1637
1768
  vault: "0xd08375176410febee9cf4591532455a4cdfe4463"
1769
+ },
1770
+ sUSDS: {
1771
+ symbol: "sUSDS",
1772
+ name: "staked USDS",
1773
+ decimals: 18,
1774
+ address: "0xb5B2dc7fd34C249F4be7fB1fCea07950784229e0",
1775
+ chainKey: ChainKeys.OPTIMISM_MAINNET,
1776
+ hubAsset: "0xb9a9cb8A61D30a8F6b7E24491ab83f43E817b0E2",
1777
+ vault: SodaTokens.sodaSUSDS.address
1638
1778
  }
1639
1779
  };
1640
1780
  var bscSupportedTokens = {
@@ -2499,6 +2639,116 @@ var stellarSupportedTokens = {
2499
2639
  chainKey: ChainKeys.STELLAR_MAINNET,
2500
2640
  hubAsset: "0x7eaF987431ce072feBEB2124fEB4d1cEf8Cf4e2e",
2501
2641
  vault: SodaTokens.SLV.address
2642
+ },
2643
+ GOOGL: {
2644
+ symbol: "GOOGL",
2645
+ isRwa: true,
2646
+ name: "Alphabet Class A",
2647
+ decimals: 7,
2648
+ address: "CCZLQHO22HLQARS26KNSJ4DU3FCFG45VG6RZQOQDQ4MHTSUVGRX57VWD",
2649
+ chainKey: ChainKeys.STELLAR_MAINNET,
2650
+ hubAsset: "0x3DE82bcf9D6a1CE8CB9b9eBCD6fC2916c548CD19",
2651
+ vault: SodaTokens.GOOGL.address
2652
+ },
2653
+ AMZN: {
2654
+ symbol: "AMZN",
2655
+ isRwa: true,
2656
+ name: "Amazon",
2657
+ decimals: 7,
2658
+ address: "CBN6JFMCVKXOIRRERGPH7CGY7RIIHGRLVSFJCD3KBMYSUEZAQR3MJ7TF",
2659
+ chainKey: ChainKeys.STELLAR_MAINNET,
2660
+ hubAsset: "0x30A6383A1d39b40B038EB82fd0F1fb7F77580623",
2661
+ vault: SodaTokens.AMZN.address
2662
+ },
2663
+ MSFT: {
2664
+ symbol: "MSFT",
2665
+ isRwa: true,
2666
+ name: "Microsoft",
2667
+ decimals: 7,
2668
+ address: "CA53FXC2RF3BNIGLCPE3PNS3SZ2AONVRKH46AIHPEJOA54LGI2DYSOAD",
2669
+ chainKey: ChainKeys.STELLAR_MAINNET,
2670
+ hubAsset: "0xDb89f97afc524c95a02a001aE16fe946e2f2e4A6",
2671
+ vault: SodaTokens.MSFT.address
2672
+ },
2673
+ META: {
2674
+ symbol: "META",
2675
+ isRwa: true,
2676
+ name: "Meta",
2677
+ decimals: 7,
2678
+ address: "CA4AXIRO72PC566XUIYVN2365347I7TVGYULXW7QDVCIXBOEFFRXGP67",
2679
+ chainKey: ChainKeys.STELLAR_MAINNET,
2680
+ hubAsset: "0xd2ff91513Cc08b5Bf4A07F1829A04273Bb902445",
2681
+ vault: SodaTokens.META.address
2682
+ },
2683
+ CRCL: {
2684
+ symbol: "CRCL",
2685
+ isRwa: true,
2686
+ name: "Circle",
2687
+ decimals: 7,
2688
+ address: "CDMRGHCY23UVTFYYW6U2NBYGME2VVPDO6OJXLZMM7FNGVFX3V42SAA4C",
2689
+ chainKey: ChainKeys.STELLAR_MAINNET,
2690
+ hubAsset: "0x1599b2754f0fC9429b3CDA12823B19eb2463F1cc",
2691
+ vault: SodaTokens.CRCL.address
2692
+ },
2693
+ COIN: {
2694
+ symbol: "COIN",
2695
+ isRwa: true,
2696
+ name: "Coinbase",
2697
+ decimals: 7,
2698
+ address: "CAKCNNQFIYAQBU7RXWPW3ZH4IWDXGMXUB6WTGCEZSI2EZ6WSTCCCEFHO",
2699
+ chainKey: ChainKeys.STELLAR_MAINNET,
2700
+ hubAsset: "0xaaB281239e25d7E637b4053C832D9b3b495c0261",
2701
+ vault: SodaTokens.COIN.address
2702
+ },
2703
+ PLTR: {
2704
+ symbol: "PLTR",
2705
+ isRwa: true,
2706
+ name: "Palantir",
2707
+ decimals: 7,
2708
+ address: "CC3EVVVQAB2BZFAJHPZWVRANTVVS37OJXNJKR2DVPAMG5FOYRPIIGCEV",
2709
+ chainKey: ChainKeys.STELLAR_MAINNET,
2710
+ hubAsset: "0x948195294e506cd42C00418269ab0E53EFAE5171",
2711
+ vault: SodaTokens.PLTR.address
2712
+ },
2713
+ TSM: {
2714
+ symbol: "TSM",
2715
+ isRwa: true,
2716
+ name: "Taiwan Semiconductor",
2717
+ decimals: 7,
2718
+ address: "CBZFBO44J4RSRZZ7PT7BHLLID6L7C4HL77YLVFCNIIXZQKVLNL6VEAD6",
2719
+ chainKey: ChainKeys.STELLAR_MAINNET,
2720
+ hubAsset: "0x276a0aB35C5eBD286076F69c58dA6AbB22c326Bf",
2721
+ vault: SodaTokens.TSM.address
2722
+ },
2723
+ AMD: {
2724
+ symbol: "AMD",
2725
+ isRwa: true,
2726
+ name: "AMD",
2727
+ decimals: 7,
2728
+ address: "CCIE4OXPJUPLNRLGAENNSDEZTQUXTXKAPU322Z3HMATZSR2S2DAAGYQD",
2729
+ chainKey: ChainKeys.STELLAR_MAINNET,
2730
+ hubAsset: "0x16a8d54d04Ee9cbcC57Fe7C4838bEA83294Fb646",
2731
+ vault: SodaTokens.AMD.address
2732
+ },
2733
+ INTC: {
2734
+ symbol: "INTC",
2735
+ isRwa: true,
2736
+ name: "Intel",
2737
+ decimals: 7,
2738
+ address: "CBD7GPTTHNFWBX7CYOM7O3N2TCZIAYT6FT4LCAXKX4JCZ3ZJL2IF7E4B",
2739
+ chainKey: ChainKeys.STELLAR_MAINNET,
2740
+ hubAsset: "0x34FC8F280c7C345A9aFC6E00F652F75b1fB2bd22",
2741
+ vault: SodaTokens.INTC.address
2742
+ },
2743
+ BABA: {
2744
+ symbol: "BABA",
2745
+ isRwa: true,
2746
+ name: "Alibaba",
2747
+ decimals: 7,
2748
+ address: "CDARDTMGSEXTYJDSKDEAA52DCYX3OZEP7SOLSF5CT3QSSAGBETWH7LO3",
2749
+ chainKey: ChainKeys.STELLAR_MAINNET,
2750
+ hubAsset: "0x83ac05C492188B46dd15d5611dEEFA6b23c7D479",
2751
+ vault: SodaTokens.BABA.address
2502
2752
  }
2503
2753
  };
2504
2754
  var suiSupportedTokens = {
@@ -2989,6 +3239,15 @@ var ethereumSupportedTokens = {
2989
3239
  chainKey: ChainKeys.ETHEREUM_MAINNET,
2990
3240
  hubAsset: "0x40bea4f921355a749f460760ba6f8edd78888164",
2991
3241
  vault: "0x40bea4f921355a749f460760ba6f8edd78888164"
3242
+ },
3243
+ sUSDS: {
3244
+ symbol: "sUSDS",
3245
+ name: "staked USDS",
3246
+ decimals: 18,
3247
+ address: "0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD",
3248
+ chainKey: ChainKeys.ETHEREUM_MAINNET,
3249
+ hubAsset: "0x1Bb5128A4837A78cb60bc52cc19079eD3F00A624",
3250
+ vault: SodaTokens.sodaSUSDS.address
2992
3251
  }
2993
3252
  };
2994
3253
  var kaiaSupportedTokens = {
@@ -3303,6 +3562,116 @@ var hederaSupportedTokens = {
3303
3562
  chainKey: ChainKeys.HEDERA_MAINNET,
3304
3563
  hubAsset: "0x914672C5336f5E00126e431368005f7C22aCe952",
3305
3564
  vault: SodaTokens.SLV.address
3565
+ },
3566
+ GOOGL: {
3567
+ symbol: "GOOGL",
3568
+ isRwa: true,
3569
+ name: "Alphabet Class A",
3570
+ decimals: 8,
3571
+ address: "0x0000000000000000000000000000000000a605ce",
3572
+ chainKey: ChainKeys.HEDERA_MAINNET,
3573
+ hubAsset: "0xA4942e1edE99034b11657C8a0978f8E2342980b4",
3574
+ vault: SodaTokens.GOOGL.address
3575
+ },
3576
+ AMZN: {
3577
+ symbol: "AMZN",
3578
+ isRwa: true,
3579
+ name: "Amazon",
3580
+ decimals: 8,
3581
+ address: "0x0000000000000000000000000000000000a605d0",
3582
+ chainKey: ChainKeys.HEDERA_MAINNET,
3583
+ hubAsset: "0x13E3E4eaaa02bbD0A32094c6C7078D4ABa24cd04",
3584
+ vault: SodaTokens.AMZN.address
3585
+ },
3586
+ MSFT: {
3587
+ symbol: "MSFT",
3588
+ isRwa: true,
3589
+ name: "Microsoft",
3590
+ decimals: 8,
3591
+ address: "0x0000000000000000000000000000000000a605d2",
3592
+ chainKey: ChainKeys.HEDERA_MAINNET,
3593
+ hubAsset: "0x5b9838715bbeFF2E8752961C418f64CAB3e7B2eD",
3594
+ vault: SodaTokens.MSFT.address
3595
+ },
3596
+ META: {
3597
+ symbol: "META",
3598
+ isRwa: true,
3599
+ name: "Meta",
3600
+ decimals: 8,
3601
+ address: "0x0000000000000000000000000000000000a605d3",
3602
+ chainKey: ChainKeys.HEDERA_MAINNET,
3603
+ hubAsset: "0xbe8a7cAFABe2399b4d751A5545017cc09D83FFc9",
3604
+ vault: SodaTokens.META.address
3605
+ },
3606
+ CRCL: {
3607
+ symbol: "CRCL",
3608
+ isRwa: true,
3609
+ name: "Circle",
3610
+ decimals: 8,
3611
+ address: "0x0000000000000000000000000000000000a605d4",
3612
+ chainKey: ChainKeys.HEDERA_MAINNET,
3613
+ hubAsset: "0x13c16a6a19a637fBf370CcA8d7f4bD38d207b620",
3614
+ vault: SodaTokens.CRCL.address
3615
+ },
3616
+ COIN: {
3617
+ symbol: "COIN",
3618
+ isRwa: true,
3619
+ name: "Coinbase",
3620
+ decimals: 8,
3621
+ address: "0x0000000000000000000000000000000000a605d6",
3622
+ chainKey: ChainKeys.HEDERA_MAINNET,
3623
+ hubAsset: "0x4d82303a0cf66f3D98E8140a1668567E748685De",
3624
+ vault: SodaTokens.COIN.address
3625
+ },
3626
+ PLTR: {
3627
+ symbol: "PLTR",
3628
+ isRwa: true,
3629
+ name: "Palantir",
3630
+ decimals: 8,
3631
+ address: "0x0000000000000000000000000000000000a605d7",
3632
+ chainKey: ChainKeys.HEDERA_MAINNET,
3633
+ hubAsset: "0xEC98d565853064667Ec5512bc6B7183D54b9EF40",
3634
+ vault: SodaTokens.PLTR.address
3635
+ },
3636
+ TSM: {
3637
+ symbol: "TSM",
3638
+ isRwa: true,
3639
+ name: "Taiwan Semiconductor",
3640
+ decimals: 8,
3641
+ address: "0x0000000000000000000000000000000000a605d9",
3642
+ chainKey: ChainKeys.HEDERA_MAINNET,
3643
+ hubAsset: "0x87FB178434B5832Df1Defa3E3E51dA3e4F1ECb10",
3644
+ vault: SodaTokens.TSM.address
3645
+ },
3646
+ AMD: {
3647
+ symbol: "AMD",
3648
+ isRwa: true,
3649
+ name: "AMD",
3650
+ decimals: 8,
3651
+ address: "0x0000000000000000000000000000000000a605db",
3652
+ chainKey: ChainKeys.HEDERA_MAINNET,
3653
+ hubAsset: "0x26b9C3af52e764b8362cDD273b443E576F960e36",
3654
+ vault: SodaTokens.AMD.address
3655
+ },
3656
+ INTC: {
3657
+ symbol: "INTC",
3658
+ isRwa: true,
3659
+ name: "Intel",
3660
+ decimals: 8,
3661
+ address: "0x0000000000000000000000000000000000a605dc",
3662
+ chainKey: ChainKeys.HEDERA_MAINNET,
3663
+ hubAsset: "0xb4Fe614a0566e64A0352645485BB4EbCaf8F3a9E",
3664
+ vault: SodaTokens.INTC.address
3665
+ },
3666
+ BABA: {
3667
+ symbol: "BABA",
3668
+ isRwa: true,
3669
+ name: "Alibaba",
3670
+ decimals: 8,
3671
+ address: "0x0000000000000000000000000000000000a605dd",
3672
+ chainKey: ChainKeys.HEDERA_MAINNET,
3673
+ hubAsset: "0x5e69df859F7c2b170E5fdAdbD59d06C2CD287753",
3674
+ vault: SodaTokens.BABA.address
3306
3675
  }
3307
3676
  };
3308
3677
  var robinhoodSupportedTokens = {
@@ -3476,6 +3845,116 @@ var robinhoodSupportedTokens = {
3476
3845
  chainKey: ChainKeys.ROBINHOOD_MAINNET,
3477
3846
  hubAsset: "0x17348849806c8b1b5d1d3abbcb527d05d21d09d5",
3478
3847
  vault: SodaTokens.SLV.address
3848
+ },
3849
+ GOOGL: {
3850
+ symbol: "GOOGL",
3851
+ isRwa: true,
3852
+ name: "Alphabet Class A",
3853
+ decimals: 18,
3854
+ address: "0x2e0847E8910a9732eB3fb1bb4b70a580ADAD4FE3",
3855
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3856
+ hubAsset: "0xb99725463347b57cb6b38e3670e79bae68361178",
3857
+ vault: SodaTokens.GOOGL.address
3858
+ },
3859
+ AMZN: {
3860
+ symbol: "AMZN",
3861
+ isRwa: true,
3862
+ name: "Amazon",
3863
+ decimals: 18,
3864
+ address: "0x12f190a9F9d7D37a250758b26824B97CE941bF54",
3865
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3866
+ hubAsset: "0x191b01f7816f927eede6603bae14979a80880f2e",
3867
+ vault: SodaTokens.AMZN.address
3868
+ },
3869
+ MSFT: {
3870
+ symbol: "MSFT",
3871
+ isRwa: true,
3872
+ name: "Microsoft",
3873
+ decimals: 18,
3874
+ address: "0xe93237C50D904957Cf27E7B1133b510C669c2e74",
3875
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3876
+ hubAsset: "0x54cd74d27c647cccc7d151c198a82a8f3371ca35",
3877
+ vault: SodaTokens.MSFT.address
3878
+ },
3879
+ META: {
3880
+ symbol: "META",
3881
+ isRwa: true,
3882
+ name: "Meta",
3883
+ decimals: 18,
3884
+ address: "0xc0D6457C16Cc70d6790Dd43521C899C87ce02f35",
3885
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3886
+ hubAsset: "0xf5661eefaebb0ed9f33c543fa606ad77646eb1f9",
3887
+ vault: SodaTokens.META.address
3888
+ },
3889
+ CRCL: {
3890
+ symbol: "CRCL",
3891
+ isRwa: true,
3892
+ name: "Circle",
3893
+ decimals: 18,
3894
+ address: "0xdF0992E440dD0be65BD8439b609d6D4366bf1CB5",
3895
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3896
+ hubAsset: "0x18f4018af0bf9fc42cbf8c0b458a838bc2dccf43",
3897
+ vault: SodaTokens.CRCL.address
3898
+ },
3899
+ COIN: {
3900
+ symbol: "COIN",
3901
+ isRwa: true,
3902
+ name: "Coinbase",
3903
+ decimals: 18,
3904
+ address: "0x6330D8C3178a418788dF01a47479c0ce7CCF450b",
3905
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3906
+ hubAsset: "0x91789d24454c40c753bdd5bc7ada7bb91848d13c",
3907
+ vault: SodaTokens.COIN.address
3908
+ },
3909
+ PLTR: {
3910
+ symbol: "PLTR",
3911
+ isRwa: true,
3912
+ name: "Palantir",
3913
+ decimals: 18,
3914
+ address: "0x894E1EC2D74FFE5AEF8Dc8A9e84686acCB964F2A",
3915
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3916
+ hubAsset: "0x99864e96d71860e6e5d25887a10da823685af1ee",
3917
+ vault: SodaTokens.PLTR.address
3918
+ },
3919
+ TSM: {
3920
+ symbol: "TSM",
3921
+ isRwa: true,
3922
+ name: "Taiwan Semiconductor",
3923
+ decimals: 18,
3924
+ address: "0x58FfE4a942d3885bAa22D7520691F611EF09e7AA",
3925
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3926
+ hubAsset: "0x5912b35ed196b129f4ad36ffd8717f2913df09bf",
3927
+ vault: SodaTokens.TSM.address
3928
+ },
3929
+ AMD: {
3930
+ symbol: "AMD",
3931
+ isRwa: true,
3932
+ name: "AMD",
3933
+ decimals: 18,
3934
+ address: "0x86923f96303D656E4aa86D9d42D1e57ad2023fdC",
3935
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3936
+ hubAsset: "0x433d44c65f20e4a776aed6c23838739d3155a692",
3937
+ vault: SodaTokens.AMD.address
3938
+ },
3939
+ INTC: {
3940
+ symbol: "INTC",
3941
+ isRwa: true,
3942
+ name: "Intel",
3943
+ decimals: 18,
3944
+ address: "0xc72b96e0E48ecd4DC75E1e45396e26300BC39681",
3945
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3946
+ hubAsset: "0xd20c60e725317c7873964a6b1d345b2507526e59",
3947
+ vault: SodaTokens.INTC.address
3948
+ },
3949
+ BABA: {
3950
+ symbol: "BABA",
3951
+ isRwa: true,
3952
+ name: "Alibaba",
3953
+ decimals: 18,
3954
+ address: "0xad25Ac6C84D497db898fa1E8387bf6Af3532a1c4",
3955
+ chainKey: ChainKeys.ROBINHOOD_MAINNET,
3956
+ hubAsset: "0xf721a074bd9fc05ba1f7cb432149a74acfb49d73",
3957
+ vault: SodaTokens.BABA.address
3479
3958
  }
3480
3959
  };
3481
3960
  var stacksSupportedTokens = {
@@ -4314,6 +4793,61 @@ var spokeChainConfig = {
4314
4793
  assetCode: "SLV",
4315
4794
  contractId: "CBY3U32O5T2B555HNJLX6C6HW3O2FLRSJGH472UOOHT6H6ZMGMSSZTLW",
4316
4795
  assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4796
+ },
4797
+ {
4798
+ assetCode: "GOOGL",
4799
+ contractId: "CCZLQHO22HLQARS26KNSJ4DU3FCFG45VG6RZQOQDQ4MHTSUVGRX57VWD",
4800
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4801
+ },
4802
+ {
4803
+ assetCode: "AMZN",
4804
+ contractId: "CBN6JFMCVKXOIRRERGPH7CGY7RIIHGRLVSFJCD3KBMYSUEZAQR3MJ7TF",
4805
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4806
+ },
4807
+ {
4808
+ assetCode: "MSFT",
4809
+ contractId: "CA53FXC2RF3BNIGLCPE3PNS3SZ2AONVRKH46AIHPEJOA54LGI2DYSOAD",
4810
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4811
+ },
4812
+ {
4813
+ assetCode: "META",
4814
+ contractId: "CA4AXIRO72PC566XUIYVN2365347I7TVGYULXW7QDVCIXBOEFFRXGP67",
4815
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4816
+ },
4817
+ {
4818
+ assetCode: "CRCL",
4819
+ contractId: "CDMRGHCY23UVTFYYW6U2NBYGME2VVPDO6OJXLZMM7FNGVFX3V42SAA4C",
4820
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4821
+ },
4822
+ {
4823
+ assetCode: "COIN",
4824
+ contractId: "CAKCNNQFIYAQBU7RXWPW3ZH4IWDXGMXUB6WTGCEZSI2EZ6WSTCCCEFHO",
4825
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4826
+ },
4827
+ {
4828
+ assetCode: "PLTR",
4829
+ contractId: "CC3EVVVQAB2BZFAJHPZWVRANTVVS37OJXNJKR2DVPAMG5FOYRPIIGCEV",
4830
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4831
+ },
4832
+ {
4833
+ assetCode: "TSM",
4834
+ contractId: "CBZFBO44J4RSRZZ7PT7BHLLID6L7C4HL77YLVFCNIIXZQKVLNL6VEAD6",
4835
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4836
+ },
4837
+ {
4838
+ assetCode: "AMD",
4839
+ contractId: "CCIE4OXPJUPLNRLGAENNSDEZTQUXTXKAPU322Z3HMATZSR2S2DAAGYQD",
4840
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4841
+ },
4842
+ {
4843
+ assetCode: "INTC",
4844
+ contractId: "CBD7GPTTHNFWBX7CYOM7O3N2TCZIAYT6FT4LCAXKX4JCZ3ZJL2IF7E4B",
4845
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4846
+ },
4847
+ {
4848
+ assetCode: "BABA",
4849
+ contractId: "CDARDTMGSEXTYJDSKDEAA52DCYX3OZEP7SOLSF5CT3QSSAGBETWH7LO3",
4850
+ assetIssuer: "GDYUTHY75A7WUZJQDPOP66FB32BOYGZRXHWTWO4Q6LQTANT5X3V5HNFA"
4317
4851
  }
4318
4852
  ],
4319
4853
  supportedTokens: stellarSupportedTokens,
@@ -4597,7 +5131,8 @@ var moneyMarketSupportedTokens = {
4597
5131
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.cbBTC,
4598
5132
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.SODA,
4599
5133
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDT,
4600
- spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDS
5134
+ spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDS,
5135
+ spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.sUSDS
4601
5136
  ],
4602
5137
  [ChainKeys.OPTIMISM_MAINNET]: [
4603
5138
  spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.ETH,
@@ -4606,7 +5141,8 @@ var moneyMarketSupportedTokens = {
4606
5141
  spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.wstETH,
4607
5142
  spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.weETH,
4608
5143
  spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDT,
4609
- spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.SODA
5144
+ spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.SODA,
5145
+ spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.sUSDS
4610
5146
  ],
4611
5147
  [ChainKeys.POLYGON_MAINNET]: [
4612
5148
  spokeChainConfig[ChainKeys.POLYGON_MAINNET].supportedTokens.POL,
@@ -4728,7 +5264,8 @@ var moneyMarketSupportedTokens = {
4728
5264
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.WBTC,
4729
5265
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.WBTC_LEGACY,
4730
5266
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.LL,
4731
- spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDS
5267
+ spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDS,
5268
+ spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.sUSDS
4732
5269
  ],
4733
5270
  [ChainKeys.REDBELLY_MAINNET]: [
4734
5271
  spokeChainConfig[ChainKeys.REDBELLY_MAINNET].supportedTokens.bnUSD,
@@ -4961,9 +5498,10 @@ var swapSupportedTokens = {
4961
5498
  spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.USDT,
4962
5499
  spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.wS,
4963
5500
  spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.SODA,
4964
- // spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.USSD, // NOTE: Not Implemented
4965
- // Swap membership is per-vault, not every SodaTokens entry: sodaSUSDS is staging-only,
4966
- // and sodaUSDS / sodaUSSD are parked until the solver fills them.
5501
+ spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.USSD,
5502
+ // Swap membership is per-vault, not every SodaTokens entry: sodaUSDS is the one wrapper the
5503
+ // production solver cannot route — a `/quote` against it returns `No path was found`, where
5504
+ // USSD, sodaUSSD and sodaSUSDS all return real prices — so it stays out until a path exists.
4967
5505
  SodaTokens.sodaBNB,
4968
5506
  SodaTokens.sodaAVAX,
4969
5507
  SodaTokens.sodaETH,
@@ -4988,8 +5526,10 @@ var swapSupportedTokens = {
4988
5526
  SodaTokens.sodaNEAR,
4989
5527
  SodaTokens.sodaKAIA,
4990
5528
  SodaTokens.sodaSTX,
5529
+ SodaTokens.sodaSUSDS,
4991
5530
  SodaTokens.sodaHBAR,
4992
5531
  SodaTokens.sodaJITOSOL,
5532
+ SodaTokens.sodaUSSD,
4993
5533
  ...Object.values(LsodaTokens),
4994
5534
  // Robinhood tokenized equities — swap-only, deliberately absent from the money market.
4995
5535
  SodaTokens.SPCX,
@@ -5004,7 +5544,18 @@ var swapSupportedTokens = {
5004
5544
  SodaTokens.QQQ,
5005
5545
  SodaTokens.SGOV,
5006
5546
  SodaTokens.USO,
5007
- SodaTokens.SLV
5547
+ SodaTokens.SLV,
5548
+ SodaTokens.GOOGL,
5549
+ SodaTokens.AMZN,
5550
+ SodaTokens.MSFT,
5551
+ SodaTokens.META,
5552
+ SodaTokens.CRCL,
5553
+ SodaTokens.COIN,
5554
+ SodaTokens.PLTR,
5555
+ SodaTokens.TSM,
5556
+ SodaTokens.AMD,
5557
+ SodaTokens.INTC,
5558
+ SodaTokens.BABA
5008
5559
  ],
5009
5560
  [ChainKeys.AVALANCHE_MAINNET]: [
5010
5561
  spokeChainConfig[ChainKeys.AVALANCHE_MAINNET].supportedTokens.AVAX,
@@ -5023,6 +5574,7 @@ var swapSupportedTokens = {
5023
5574
  spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.tBTC,
5024
5575
  spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.USDC,
5025
5576
  spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.USDT,
5577
+ spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.sUSDS,
5026
5578
  spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.ARB,
5027
5579
  spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.AAVE,
5028
5580
  spokeChainConfig[ChainKeys.ARBITRUM_MAINNET].supportedTokens.LINK,
@@ -5037,6 +5589,7 @@ var swapSupportedTokens = {
5037
5589
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.ETH,
5038
5590
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.weETH,
5039
5591
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.USDC,
5592
+ spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.sUSDS,
5040
5593
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.wstETH,
5041
5594
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.cbBTC,
5042
5595
  spokeChainConfig[ChainKeys.BASE_MAINNET].supportedTokens.VIRTUAL,
@@ -5047,6 +5600,7 @@ var swapSupportedTokens = {
5047
5600
  [ChainKeys.OPTIMISM_MAINNET]: [
5048
5601
  spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.ETH,
5049
5602
  spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDC,
5603
+ spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.sUSDS,
5050
5604
  spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.wstETH,
5051
5605
  // spokeChainConfig[OPTIMISM_MAINNET_CHAIN_ID].supportedTokens.weETH, // NOTE: Not Implemented
5052
5606
  spokeChainConfig[ChainKeys.OPTIMISM_MAINNET].supportedTokens.USDT,
@@ -5176,7 +5730,18 @@ var swapSupportedTokens = {
5176
5730
  spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.QQQ,
5177
5731
  spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.SGOV,
5178
5732
  spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.USO,
5179
- spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.SLV
5733
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.SLV,
5734
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.GOOGL,
5735
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.AMZN,
5736
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.MSFT,
5737
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.META,
5738
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.CRCL,
5739
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.COIN,
5740
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.PLTR,
5741
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.TSM,
5742
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.AMD,
5743
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.INTC,
5744
+ spokeChainConfig[ChainKeys.STELLAR_MAINNET].supportedTokens.BABA
5180
5745
  ],
5181
5746
  [ChainKeys.SUI_MAINNET]: [
5182
5747
  spokeChainConfig[ChainKeys.SUI_MAINNET].supportedTokens.SUI,
@@ -5214,6 +5779,7 @@ var swapSupportedTokens = {
5214
5779
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.ETH,
5215
5780
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.bnUSD,
5216
5781
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDC,
5782
+ spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.sUSDS,
5217
5783
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDT,
5218
5784
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.SODA,
5219
5785
  spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.LL,
@@ -5295,7 +5861,18 @@ var swapSupportedTokens = {
5295
5861
  spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.QQQ,
5296
5862
  spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.SGOV,
5297
5863
  spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.USO,
5298
- spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.SLV
5864
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.SLV,
5865
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.GOOGL,
5866
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.AMZN,
5867
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.MSFT,
5868
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.META,
5869
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.CRCL,
5870
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.COIN,
5871
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.PLTR,
5872
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.TSM,
5873
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.AMD,
5874
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.INTC,
5875
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.BABA
5299
5876
  ],
5300
5877
  [ChainKeys.ROBINHOOD_MAINNET]: [
5301
5878
  spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.ETH,
@@ -5316,11 +5893,22 @@ var swapSupportedTokens = {
5316
5893
  spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.QQQ,
5317
5894
  spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.SGOV,
5318
5895
  spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.USO,
5319
- spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.SLV
5896
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.SLV,
5897
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.GOOGL,
5898
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.AMZN,
5899
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.MSFT,
5900
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.META,
5901
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.CRCL,
5902
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.COIN,
5903
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.PLTR,
5904
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.TSM,
5905
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.AMD,
5906
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.INTC,
5907
+ spokeChainConfig[ChainKeys.ROBINHOOD_MAINNET].supportedTokens.BABA
5320
5908
  ]
5321
5909
  };
5322
5910
  var stagingSwapSupportedTokens = {
5323
- [ChainKeys.SONIC_MAINNET]: [SodaTokens.sodaSUSDS],
5911
+ [ChainKeys.SONIC_MAINNET]: [],
5324
5912
  [ChainKeys.AVALANCHE_MAINNET]: [],
5325
5913
  [ChainKeys.ARBITRUM_MAINNET]: [],
5326
5914
  [ChainKeys.BASE_MAINNET]: [
@@ -5427,7 +6015,8 @@ var leverageYieldVaults = [
5427
6015
  }
5428
6016
  ];
5429
6017
  var leverageYieldConfig = {
5430
- vaults: leverageYieldVaults
6018
+ vaults: leverageYieldVaults,
6019
+ positionFactory: "0xF8fB7F200B6545295e1729Cf254482d7c116031C"
5431
6020
  };
5432
6021
 
5433
6022
  // ../types/dist/sodax-config/sodax-config.js
@@ -5660,7 +6249,45 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
5660
6249
  }
5661
6250
 
5662
6251
  // ../types/dist/index.js
5663
- var CONFIG_VERSION = 235;
6252
+ var CONFIG_VERSION = 2020007;
6253
+ var RC_STABLE = 99;
6254
+ var MIN_CONFIG_VERSION = 1e6;
6255
+ var MAX_CONFIG_VERSION = 99999999;
6256
+ var VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-rc\.(0|[1-9]\d*))?$/;
6257
+ function configVersionFor(version) {
6258
+ const match = typeof version === "string" ? version.match(VERSION_PATTERN) : null;
6259
+ if (!match)
6260
+ return null;
6261
+ const major = Number(match[1]);
6262
+ const minor = Number(match[2]);
6263
+ const patch = Number(match[3]);
6264
+ const rc = match[4] === void 0 ? null : Number(match[4]);
6265
+ if (major < 1 || major > 99 || minor > 99 || patch > 99)
6266
+ return null;
6267
+ if (rc !== null && rc > 98)
6268
+ return null;
6269
+ return major * 1e6 + minor * 1e4 + patch * 100 + (rc === null ? RC_STABLE : rc);
6270
+ }
6271
+ var unpack = (value) => {
6272
+ const slot = value % 100;
6273
+ return {
6274
+ major: Math.floor(value / 1e6),
6275
+ minor: Math.floor(value / 1e4) % 100,
6276
+ patch: Math.floor(value / 100) % 100,
6277
+ rc: slot === RC_STABLE ? null : slot
6278
+ };
6279
+ };
6280
+ var render = ({ major, minor, patch, rc }) => `${major}.${minor}.${patch}${rc === null ? "" : `-rc.${rc}`}`;
6281
+ function parseConfigVersion(value) {
6282
+ if (!Number.isInteger(value) || value < MIN_CONFIG_VERSION || value > MAX_CONFIG_VERSION)
6283
+ return null;
6284
+ return unpack(value);
6285
+ }
6286
+ function formatConfigVersion(value) {
6287
+ const parsed = parseConfigVersion(value);
6288
+ return parsed === null ? null : render(parsed);
6289
+ }
6290
+ var SDK_VERSION = render(unpack(CONFIG_VERSION));
5664
6291
 
5665
6292
  // src/shared/utils/resolveTimeoutMs.ts
5666
6293
  function resolveTimeoutMs(timeout, fallbackMs) {
@@ -5875,12 +6502,12 @@ function canonicalizeBitcoinAddress(address) {
5875
6502
  }
5876
6503
  }
5877
6504
  function normalizePsbtToBase64(signedPsbt) {
5878
- const isHex2 = /^[0-9a-fA-F]+$/.test(signedPsbt);
5879
- return isHex2 ? Buffer.from(signedPsbt, "hex").toString("base64") : signedPsbt;
6505
+ const isHex3 = /^[0-9a-fA-F]+$/.test(signedPsbt);
6506
+ return isHex3 ? Buffer.from(signedPsbt, "hex").toString("base64") : signedPsbt;
5880
6507
  }
5881
6508
  function normalizeSignatureToBase64(signature) {
5882
- const isHex2 = /^[0-9a-fA-F]+$/.test(signature);
5883
- return isHex2 ? Buffer.from(signature, "hex").toString("base64") : signature;
6509
+ const isHex3 = /^[0-9a-fA-F]+$/.test(signature);
6510
+ return isHex3 ? Buffer.from(signature, "hex").toString("base64") : signature;
5884
6511
  }
5885
6512
  function isNativeBitcoinTransfer(config, chainKey, token) {
5886
6513
  return isBitcoinChainKeyType(chainKey) && !!token && isNativeBitcoinToken(config.getChainConfig(chainKey), token.address);
@@ -15595,11 +16222,15 @@ var ConfigService = class {
15595
16222
  isMoneyMarketSupportedToken(chainId, token) {
15596
16223
  return this.sodax.moneyMarket.supportedTokens[chainId].some((t) => t.address.toLowerCase() === token.toLowerCase());
15597
16224
  }
16225
+ /**
16226
+ * Is `asset` one of the money-market reserve assets?
16227
+ *
16228
+ * The reserve set is built from `moneyMarketHubVaults`, so its members are hub **vault**
16229
+ * addresses. Query it with an `XToken.vault`; an `XToken.hubAsset` only matches for the Sonic
16230
+ * vault shares themselves, where `hubAsset === vault`.
16231
+ */
15598
16232
  isMoneyMarketReserveAsset(asset) {
15599
- return this.sodax.moneyMarket.supportedReserveAssets.map((a) => a.toLowerCase()).includes(asset.toLowerCase());
15600
- }
15601
- isMoneyMarketReserveHubAsset(hubAsset) {
15602
- return this.moneyMarketReserveAssetsSet.has(hubAsset.toLowerCase());
16233
+ return this.moneyMarketReserveAssetsSet.has(asset.toLowerCase());
15603
16234
  }
15604
16235
  loadSodaxConfigDataStructures(sodaxConfig2) {
15605
16236
  this.hubAssetToXTokenMap = new Map(
@@ -15692,10 +16323,12 @@ var ConfigService = class {
15692
16323
  get bridgeUseBackendSubmitTx() {
15693
16324
  return this.bridge.useBackendSubmitTx ?? this.sodax.bridgeOptions?.useBackendSubmitTx ?? true;
15694
16325
  }
15695
- // Opt-in (default OFF), unlike the swaps/bridge toggles above: the leverage-yield submit-tx
15696
- // backend path is newer, so an omitted flag keeps the proven client-side relay.
16326
+ // Same ON default as the two above, and for the same reason: any backend non-success falls back
16327
+ // to the client-side relay, so the default costs a rejected attempt at worst. No deprecated
16328
+ // second-precedence key here — leverage yield arrived after `swapsOptions` / `bridgeOptions` were
16329
+ // already deprecated, so it never had one.
15697
16330
  get leverageYieldUseBackendSubmitTx() {
15698
- return this.leverageYield.useBackendSubmitTx ?? false;
16331
+ return this.leverageYield.useBackendSubmitTx ?? true;
15699
16332
  }
15700
16333
  get dex() {
15701
16334
  return this.sodax.dex;
@@ -15748,7 +16381,7 @@ function mergeSodaxConfig(base2, override) {
15748
16381
  }
15749
16382
  function encodeContractCalls(calls) {
15750
16383
  return viem.encodeAbiParameters(viem.parseAbiParameters("(address,uint256,bytes)[]"), [
15751
- calls.map((v12) => [v12.address, v12.value, v12.data])
16384
+ calls.map((v10) => [v10.address, v10.value, v10.data])
15752
16385
  ]);
15753
16386
  }
15754
16387
  async function waitForTransactionReceipt(hash, provider) {
@@ -18011,7 +18644,7 @@ function hexToBytes2(hex) {
18011
18644
  const al = hl / 2;
18012
18645
  if (hl % 2)
18013
18646
  throw new Error("hex string expected, got unpadded hex of length " + hl);
18014
- const array4 = new Uint8Array(al);
18647
+ const array3 = new Uint8Array(al);
18015
18648
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
18016
18649
  const n1 = asciiToBase16(hex.charCodeAt(hi));
18017
18650
  const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
@@ -18019,9 +18652,9 @@ function hexToBytes2(hex) {
18019
18652
  const char = hex[hi] + hex[hi + 1];
18020
18653
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
18021
18654
  }
18022
- array4[ai] = n1 * 16 + n2;
18655
+ array3[ai] = n1 * 16 + n2;
18023
18656
  }
18024
- return array4;
18657
+ return array3;
18025
18658
  }
18026
18659
  function concatBytes(...arrays) {
18027
18660
  let sum = 0;
@@ -18651,22 +19284,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
18651
19284
  const byte0 = Uint8Array.of(0);
18652
19285
  const byte1 = Uint8Array.of(1);
18653
19286
  const _maxDrbgIters = 1e3;
18654
- let v12 = u8n(hashLen);
19287
+ let v10 = u8n(hashLen);
18655
19288
  let k = u8n(hashLen);
18656
19289
  let i = 0;
18657
19290
  const reset = () => {
18658
- v12.fill(1);
19291
+ v10.fill(1);
18659
19292
  k.fill(0);
18660
19293
  i = 0;
18661
19294
  };
18662
- const h = (...msgs) => hmacFn(k, concatBytes(v12, ...msgs));
19295
+ const h = (...msgs) => hmacFn(k, concatBytes(v10, ...msgs));
18663
19296
  const reseed = (seed = NULL) => {
18664
19297
  k = h(byte0, seed);
18665
- v12 = h();
19298
+ v10 = h();
18666
19299
  if (seed.length === 0)
18667
19300
  return;
18668
19301
  k = h(byte1, seed);
18669
- v12 = h();
19302
+ v10 = h();
18670
19303
  };
18671
19304
  const gen = () => {
18672
19305
  if (i++ >= _maxDrbgIters)
@@ -18674,10 +19307,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
18674
19307
  let len = 0;
18675
19308
  const out = [];
18676
19309
  while (len < qByteLen) {
18677
- v12 = h();
18678
- const sl = v12.slice();
19310
+ v10 = h();
19311
+ const sl = v10.slice();
18679
19312
  out.push(sl);
18680
- len += v12.length;
19313
+ len += v10.length;
18681
19314
  }
18682
19315
  return concatBytes(...out);
18683
19316
  };
@@ -18692,18 +19325,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
18692
19325
  };
18693
19326
  return genUntil;
18694
19327
  }
18695
- function validateObject(object6, fields = {}, optFields = {}) {
18696
- if (!object6 || typeof object6 !== "object")
19328
+ function validateObject(object4, fields = {}, optFields = {}) {
19329
+ if (!object4 || typeof object4 !== "object")
18697
19330
  throw new Error("expected valid options object");
18698
19331
  function checkField(fieldName, expectedType, isOpt) {
18699
- const val = object6[fieldName];
19332
+ const val = object4[fieldName];
18700
19333
  if (isOpt && val === void 0)
18701
19334
  return;
18702
19335
  const current = typeof val;
18703
19336
  if (current !== expectedType || val === null)
18704
19337
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
18705
19338
  }
18706
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v12]) => checkField(k, v12, isOpt));
19339
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v10]) => checkField(k, v10, isOpt));
18707
19340
  iter(fields, false);
18708
19341
  iter(optFields, true);
18709
19342
  }
@@ -18742,12 +19375,12 @@ function pow2(x, power, modulo) {
18742
19375
  }
18743
19376
  return res;
18744
19377
  }
18745
- function invert(number6, modulo) {
18746
- if (number6 === _0n2)
19378
+ function invert(number4, modulo) {
19379
+ if (number4 === _0n2)
18747
19380
  throw new Error("invert: expected non-zero number");
18748
19381
  if (modulo <= _0n2)
18749
19382
  throw new Error("invert: expected positive modulus, got " + modulo);
18750
- let a = mod(number6, modulo);
19383
+ let a = mod(number4, modulo);
18751
19384
  let b = modulo;
18752
19385
  let x = _0n2, u = _1n2;
18753
19386
  while (a !== _0n2) {
@@ -18774,9 +19407,9 @@ function sqrt3mod4(Fp, n) {
18774
19407
  function sqrt5mod8(Fp, n) {
18775
19408
  const p5div8 = (Fp.ORDER - _5n) / _8n;
18776
19409
  const n2 = Fp.mul(n, _2n);
18777
- const v12 = Fp.pow(n2, p5div8);
18778
- const nv = Fp.mul(n, v12);
18779
- const i = Fp.mul(Fp.mul(nv, _2n), v12);
19410
+ const v10 = Fp.pow(n2, p5div8);
19411
+ const nv = Fp.mul(n, v10);
19412
+ const i = Fp.mul(Fp.mul(nv, _2n), v10);
18780
19413
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
18781
19414
  assertIsSquare(Fp, root, n);
18782
19415
  return root;
@@ -19251,27 +19884,27 @@ var wNAF = class {
19251
19884
  assert0(n);
19252
19885
  return acc;
19253
19886
  }
19254
- getPrecomputes(W, point, transform2) {
19887
+ getPrecomputes(W, point, transform) {
19255
19888
  let comp = pointPrecomputes.get(point);
19256
19889
  if (!comp) {
19257
19890
  comp = this.precomputeWindow(point, W);
19258
19891
  if (W !== 1) {
19259
- if (typeof transform2 === "function")
19260
- comp = transform2(comp);
19892
+ if (typeof transform === "function")
19893
+ comp = transform(comp);
19261
19894
  pointPrecomputes.set(point, comp);
19262
19895
  }
19263
19896
  }
19264
19897
  return comp;
19265
19898
  }
19266
- cached(point, scalar, transform2) {
19899
+ cached(point, scalar, transform) {
19267
19900
  const W = getW(point);
19268
- return this.wNAF(W, this.getPrecomputes(W, point, transform2), scalar);
19901
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
19269
19902
  }
19270
- unsafe(point, scalar, transform2, prev) {
19903
+ unsafe(point, scalar, transform, prev) {
19271
19904
  const W = getW(point);
19272
19905
  if (W === 1)
19273
19906
  return this._unsafeLadder(point, scalar, prev);
19274
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform2), scalar, prev);
19907
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
19275
19908
  }
19276
19909
  // We calculate precomputes for elliptic curve point multiplication
19277
19910
  // using windowed method. This specifies window size and
@@ -19358,9 +19991,9 @@ function edwards(params, extraOpts = {}) {
19358
19991
  validateObject(extraOpts, {}, { uvRatio: "function" });
19359
19992
  const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
19360
19993
  const modP = (n) => Fp.create(n);
19361
- const uvRatio2 = extraOpts.uvRatio || ((u, v12) => {
19994
+ const uvRatio2 = extraOpts.uvRatio || ((u, v10) => {
19362
19995
  try {
19363
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v12)) };
19996
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v10)) };
19364
19997
  } catch (e) {
19365
19998
  return { isValid: false, value: _0n4 };
19366
19999
  }
@@ -19456,8 +20089,8 @@ function edwards(params, extraOpts = {}) {
19456
20089
  aInRange("point.y", y, _0n4, max);
19457
20090
  const y2 = modP(y * y);
19458
20091
  const u = modP(y2 - _1n4);
19459
- const v12 = modP(d * y2 - a);
19460
- let { isValid, value: x } = uvRatio2(u, v12);
20092
+ const v10 = modP(d * y2 - a);
20093
+ let { isValid, value: x } = uvRatio2(u, v10);
19461
20094
  if (!isValid)
19462
20095
  throw new Error("bad point: invalid y coordinate");
19463
20096
  const isXOdd = (x & _1n4) === _1n4;
@@ -19797,13 +20430,13 @@ function adjustScalarBytes(bytes) {
19797
20430
  return bytes;
19798
20431
  }
19799
20432
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
19800
- function uvRatio(u, v12) {
20433
+ function uvRatio(u, v10) {
19801
20434
  const P = ed25519_CURVE_p;
19802
- const v32 = mod(v12 * v12 * v12, P);
19803
- const v72 = mod(v32 * v32 * v12, P);
20435
+ const v32 = mod(v10 * v10 * v10, P);
20436
+ const v72 = mod(v32 * v32 * v10, P);
19804
20437
  const pow = ed25519_pow_2_252_3(u * v72).pow_p_5_8;
19805
20438
  let x = mod(u * v32 * pow, P);
19806
- const vx2 = mod(v12 * x * x, P);
20439
+ const vx2 = mod(v10 * x * x, P);
19807
20440
  const root1 = x;
19808
20441
  const root2 = mod(x * ED25519_SQRT_M1, P);
19809
20442
  const useRoot1 = vx2 === u;
@@ -20134,7 +20767,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
20134
20767
  return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
20135
20768
  }
20136
20769
  function findSeatPriceForProtocolBefore49(validators, numSeats) {
20137
- const stakes = validators.map((v12) => BigInt(v12.stake)).sort(sortBigIntAsc);
20770
+ const stakes = validators.map((v10) => BigInt(v10.stake)).sort(sortBigIntAsc);
20138
20771
  const num = BigInt(numSeats);
20139
20772
  const stakesSum = stakes.reduce((a, b) => a + b);
20140
20773
  if (stakesSum < num) {
@@ -20163,7 +20796,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
20163
20796
  if (minimumStakeRatio.length != 2) {
20164
20797
  throw Error("minimumStakeRatio should have 2 elements");
20165
20798
  }
20166
- const stakes = validators.map((v12) => BigInt(v12.stake)).sort(sortBigIntAsc);
20799
+ const stakes = validators.map((v10) => BigInt(v10.stake)).sort(sortBigIntAsc);
20167
20800
  const stakesSum = stakes.reduce((a, b) => a + b);
20168
20801
  if (validators.length < maxNumberOfSeats) {
20169
20802
  return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
@@ -20335,10 +20968,10 @@ var DER = {
20335
20968
  if (length < 128)
20336
20969
  throw new E("tlv.decode(long): not minimal encoding");
20337
20970
  }
20338
- const v12 = data.subarray(pos, pos + length);
20339
- if (v12.length !== length)
20971
+ const v10 = data.subarray(pos, pos + length);
20972
+ if (v10.length !== length)
20340
20973
  throw new E("tlv.decode: wrong value length");
20341
- return { v: v12, l: data.subarray(pos + length) };
20974
+ return { v: v10, l: data.subarray(pos + length) };
20342
20975
  }
20343
20976
  },
20344
20977
  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
@@ -20906,9 +21539,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
20906
21539
  extraEntropy: false
20907
21540
  };
20908
21541
  const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
20909
- function isBiggerThanHalfOrder(number6) {
21542
+ function isBiggerThanHalfOrder(number4) {
20910
21543
  const HALF = CURVE_ORDER >> _1n6;
20911
- return number6 > HALF;
21544
+ return number4 > HALF;
20912
21545
  }
20913
21546
  function validateRS(title, num) {
20914
21547
  if (!Fn.isValidNot0(num))
@@ -21091,8 +21724,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
21091
21724
  const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
21092
21725
  if (R.is0())
21093
21726
  return false;
21094
- const v12 = Fn.create(R.x);
21095
- return v12 === r;
21727
+ const v10 = Fn.create(R.x);
21728
+ return v10 === r;
21096
21729
  } catch (e) {
21097
21730
  return false;
21098
21731
  }
@@ -24984,6 +25617,7 @@ function isTimeoutError(error) {
24984
25617
  return error instanceof Error && /timed?\s?out|timeout/i.test(error.message);
24985
25618
  }
24986
25619
  var DEFAULT_GET_COINS_LIMIT = 10;
25620
+ var LATEST_PACKAGE_ID_TIMEOUT_MS = 1e4;
24987
25621
  function toSuiObjectOwner(owner) {
24988
25622
  switch (owner?.$kind) {
24989
25623
  case "AddressOwner":
@@ -25052,16 +25686,20 @@ var SuiGrpcTransport = class {
25052
25686
  return effects.gasUsed;
25053
25687
  }
25054
25688
  async fetchLatestPackageId(objectId) {
25055
- let object6;
25689
+ let object4;
25056
25690
  try {
25057
- ({ object: object6 } = await this.client.core.getObject({ objectId, include: { json: true } }));
25691
+ ({ object: object4 } = await this.client.core.getObject({
25692
+ objectId,
25693
+ include: { json: true },
25694
+ signal: AbortSignal.timeout(LATEST_PACKAGE_ID_TIMEOUT_MS)
25695
+ }));
25058
25696
  } catch (error) {
25059
25697
  throw new Error("Failed to fetch asset manager id", { cause: error });
25060
25698
  }
25061
- if (!object6) {
25699
+ if (!object4) {
25062
25700
  throw new Error("Asset manager id not found (no data)");
25063
25701
  }
25064
- const fields = object6.json;
25702
+ const fields = object4.json;
25065
25703
  if (!fields) {
25066
25704
  throw new Error("Asset manager id not found (not a move object)");
25067
25705
  }
@@ -25098,7 +25736,11 @@ var SuiSpokeService = class {
25098
25736
  transport;
25099
25737
  /** @deprecated Renamed to `transport`, and no longer a raw `@mysten/sui` client. */
25100
25738
  publicClient;
25101
- assetManagerAddress;
25739
+ /**
25740
+ * `latest_package_id` reads still in flight, keyed by chain. An entry is dropped as soon as its
25741
+ * read settles, so concurrent callers share one request while a later build always re-reads.
25742
+ */
25743
+ assetManagerLookups = /* @__PURE__ */ new Map();
25102
25744
  pollingIntervalMs;
25103
25745
  maxTimeoutMs;
25104
25746
  constructor(config) {
@@ -25160,10 +25802,19 @@ var SuiSpokeService = class {
25160
25802
  };
25161
25803
  }
25162
25804
  async getAssetManagerAddress(chainId) {
25163
- if (!this.assetManagerAddress) {
25164
- this.assetManagerAddress = await this.fetchAssetManagerAddress(chainId);
25165
- }
25166
- return this.assetManagerAddress.toString();
25805
+ const { packageId, moduleId, stateId } = await this.resolveAssetManager(chainId);
25806
+ return `${packageId}::${moduleId}::${stateId}`;
25807
+ }
25808
+ /**
25809
+ * An upgraded Sui package lives at a new address and the superseded one aborts on
25810
+ * `enforce_version`, so the id is read per call and never held between two builds.
25811
+ */
25812
+ async resolveAssetManager(chainId) {
25813
+ const inFlight = this.assetManagerLookups.get(chainId);
25814
+ if (inFlight) return inFlight;
25815
+ const lookup = this.fetchAssetManagerAddress(chainId).then((address) => this.splitAddress(address)).finally(() => this.assetManagerLookups.delete(chainId));
25816
+ this.assetManagerLookups.set(chainId, lookup);
25817
+ return lookup;
25167
25818
  }
25168
25819
  async viewContract(tx, packageId, module, functionName, args, typeArgs = [], sender) {
25169
25820
  tx.moveCall({
@@ -25180,12 +25831,27 @@ var SuiSpokeService = class {
25180
25831
  * @returns {Promise<TxReturnType<SuiChainKey, R>>} A promise that resolves to the transaction hash or raw transaction base64 string.
25181
25832
  */
25182
25833
  async deposit(params) {
25834
+ const { tx, assetManager } = await this.buildDepositTransaction(params);
25835
+ if (params.raw === true) {
25836
+ return {
25837
+ from: params.srcAddress,
25838
+ to: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
25839
+ value: params.amount,
25840
+ data: tx.serialize()
25841
+ };
25842
+ }
25843
+ return params.walletProvider.signAndExecuteTxn(tx);
25844
+ }
25845
+ /** Both deposit paths build here, so the asset manager is resolved the same way for each. */
25846
+ async buildDepositTransaction(params) {
25183
25847
  const { srcAddress: from, srcChainKey, token, to, amount, data = "0x" } = params;
25184
25848
  const isNative = isNativeToken(srcChainKey, token);
25185
25849
  const tx = new transactions.Transaction();
25186
- const coin = isNative ? await this.getNativeCoin(tx, amount) : await this.getCoin(tx, token, amount, from);
25187
25850
  const connection = this.splitAddress(this.config.getChainConfig(srcChainKey).addresses.connection);
25188
- const assetManager = this.splitAddress(await this.getAssetManagerAddress(srcChainKey));
25851
+ const [coin, assetManager] = await Promise.all([
25852
+ isNative ? this.getNativeCoin(tx, amount) : this.getCoin(tx, token, amount, from),
25853
+ this.resolveAssetManager(srcChainKey)
25854
+ ]);
25189
25855
  tx.moveCall({
25190
25856
  target: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
25191
25857
  typeArguments: [token],
@@ -25198,15 +25864,7 @@ var SuiSpokeService = class {
25198
25864
  tx.pure(bcs.bcs.vector(bcs.bcs.u8()).serialize(viem.fromHex(data, "bytes")))
25199
25865
  ]
25200
25866
  });
25201
- if (params.raw === true) {
25202
- return {
25203
- from,
25204
- to: `${assetManager.packageId}::${assetManager.moduleId}::transfer`,
25205
- value: amount,
25206
- data: tx.serialize()
25207
- };
25208
- }
25209
- return params.walletProvider.signAndExecuteTxn(tx);
25867
+ return { tx, assetManager };
25210
25868
  }
25211
25869
  async sendMessage(params) {
25212
25870
  const { srcAddress: from, srcChainKey, dstChainKey, dstAddress, payload } = params;
@@ -25246,7 +25904,7 @@ var SuiSpokeService = class {
25246
25904
  * @returns {Promise<bigint>} The balance of the token.
25247
25905
  */
25248
25906
  async getDeposit(params) {
25249
- const assetmanager = this.splitAddress(await this.getAssetManagerAddress(params.srcChainKey));
25907
+ const assetmanager = await this.resolveAssetManager(params.srcChainKey);
25250
25908
  const tx = new transactions.Transaction();
25251
25909
  const result = await this.viewContract(
25252
25910
  tx,
@@ -28977,6 +29635,39 @@ var EvmHubProvider = class {
28977
29635
  }
28978
29636
  };
28979
29637
 
29638
+ // src/backendApi/detailedStatusRouting.ts
29639
+ var DETAILED_STATUS_NOT_DELIVERED = "relay_not_delivered";
29640
+ function isBackendSubmitTxAbandoned(data) {
29641
+ return data.status === "failed" || Boolean(data.abandonedAt);
29642
+ }
29643
+ async function resolveDeliveredPacket(params) {
29644
+ const { srcChainKey, srcTxHash, relayerApiEndpoint, backendAnswered } = params;
29645
+ const relayChainId = getIntentRelayChainId(srcChainKey);
29646
+ const packets = await getTransactionPackets(
29647
+ { action: "get_transaction_packets", params: { chain_id: relayChainId.toString(), tx_hash: srcTxHash } },
29648
+ relayerApiEndpoint,
29649
+ RELAY_REQUEST_TIMEOUT_MS
29650
+ );
29651
+ if (!packets.ok) {
29652
+ const notIndexed = packets.error instanceof HttpRelayError && packets.error.status === 404;
29653
+ return { ok: false, cause: packets.error, budgetable: notIndexed && backendAnswered };
29654
+ }
29655
+ if (!packets.value?.success || !Array.isArray(packets.value.data)) {
29656
+ return { ok: false, cause: new Error("relay returned no usable transaction packets"), budgetable: false };
29657
+ }
29658
+ const delivered = packets.value.data.find(
29659
+ (packet) => typeof packet?.src_tx_hash === "string" && packet.src_tx_hash.toLowerCase() === srcTxHash.toLowerCase() && packet.src_chain_id === Number(relayChainId) && packet.status === "executed" && typeof packet.dst_tx_hash === "string" && packet.dst_tx_hash.length > 0
29660
+ );
29661
+ if (!delivered) {
29662
+ return {
29663
+ ok: false,
29664
+ cause: new Error("relay has not delivered a packet for this source tx yet"),
29665
+ budgetable: backendAnswered
29666
+ };
29667
+ }
29668
+ return { ok: true, packet: delivered };
29669
+ }
29670
+
28980
29671
  // src/backendApi/api-utils.ts
28981
29672
  var API_KEY_HEADER = "x-api-key";
28982
29673
  function apiKeyHeader(apiKey) {
@@ -29575,7 +30266,7 @@ function selectSolvedIntentPacket(packets, intentsContract) {
29575
30266
 
29576
30267
  // src/swap/speed-tier.ts
29577
30268
  var SPEED_TIER_SECONDS = {
29578
- /** Either token maps to a money-market-reserve (sodaAsset) hub asset. */
30269
+ /** Either token's vault is a money-market-reserve (sodaAsset). */
29579
30270
  sodaAsset: 15,
29580
30271
  /** Anything else / default. */
29581
30272
  default: 35,
@@ -29593,7 +30284,7 @@ var secondsToTier = (seconds) => {
29593
30284
  return "slow";
29594
30285
  };
29595
30286
  function estimateSwapSpeedTier({ srcToken, dstToken }, isSodaAssetRelated) {
29596
- const eitherSodaAsset = isSodaAssetRelated(srcToken.hubAsset) || isSodaAssetRelated(dstToken.hubAsset);
30287
+ const eitherSodaAsset = isSodaAssetRelated(srcToken.vault) || isSodaAssetRelated(dstToken.vault);
29597
30288
  let estimatedSeconds = eitherSodaAsset ? SPEED_TIER_SECONDS.sodaAsset : SPEED_TIER_SECONDS.default;
29598
30289
  if (isEthereumToken(srcToken) || isEthereumToken(dstToken)) {
29599
30290
  estimatedSeconds += SPEED_TIER_SECONDS.ethereumPenalty;
@@ -29601,12 +30292,6 @@ function estimateSwapSpeedTier({ srcToken, dstToken }, isSodaAssetRelated) {
29601
30292
  return { tier: secondsToTier(estimatedSeconds), estimatedSeconds };
29602
30293
  }
29603
30294
 
29604
- // src/swap/detailedStatus.ts
29605
- var DETAILED_STATUS_NOT_DELIVERED = "relay_not_delivered";
29606
- function isBackendSubmitTxAbandoned(data) {
29607
- return data.status === "failed" || Boolean(data.abandonedAt);
29608
- }
29609
-
29610
30295
  // src/swap/errors.ts
29611
30296
  var swapInvariant = createInvariant("swap");
29612
30297
  var POST_EXECUTION_ERROR_CODES = /* @__PURE__ */ new Set([
@@ -29803,14 +30488,22 @@ var SwapService = class {
29803
30488
  */
29804
30489
  async getDetailedStatus(params) {
29805
30490
  try {
29806
- const record3 = await this.backendApi.swaps.getSubmitTxStatus({
30491
+ const record = await this.backendApi.swaps.getSubmitTxStatus({
29807
30492
  txHash: params.srcTxHash,
29808
30493
  srcChainKey: params.srcChainKey
29809
30494
  });
29810
- if (record3.ok && record3.value.success && !isBackendSubmitTxAbandoned(record3.value.data)) {
29811
- return { ok: true, value: { source: "backend", data: record3.value.data } };
30495
+ if (record.ok && record.value.success && !isBackendSubmitTxAbandoned(record.value.data)) {
30496
+ return { ok: true, value: { source: "backend", data: record.value.data } };
29812
30497
  }
29813
- const backendAnswered = record3.ok || isSodaxError(record3.error) && record3.error.context?.status === 404;
30498
+ if (!record.ok && isSodaxError(record.error) && isAuthFailure(record.error)) {
30499
+ return {
30500
+ ok: false,
30501
+ error: this.detailedStatusLookupFailed(record.error, params.srcChainKey, {
30502
+ status: record.error.context?.status
30503
+ })
30504
+ };
30505
+ }
30506
+ const backendAnswered = record.ok || isSodaxError(record.error) && record.error.context?.status === 404;
29814
30507
  const dstTxHash = await this.resolveHubTxHash(params, backendAnswered);
29815
30508
  if (!dstTxHash.ok) return dstTxHash;
29816
30509
  const solver = await this.resolveSolverStatus(
@@ -29831,48 +30524,23 @@ var SwapService = class {
29831
30524
  * is simply "no hash yet".
29832
30525
  */
29833
30526
  async resolveHubTxHash(key, backendAnswered) {
29834
- const missReason = backendAnswered ? DETAILED_STATUS_NOT_DELIVERED : void 0;
29835
30527
  let hubTxHash = key.srcTxHash;
29836
30528
  if (!isHubChainKeyType(key.srcChainKey)) {
29837
- const relayChainId = getIntentRelayChainId(key.srcChainKey);
29838
- const packets = await getTransactionPackets(
29839
- {
29840
- action: "get_transaction_packets",
29841
- params: { chain_id: relayChainId.toString(), tx_hash: key.srcTxHash }
29842
- },
29843
- this.relayerApiEndpoint,
29844
- RELAY_REQUEST_TIMEOUT_MS
29845
- );
29846
- if (!packets.ok) {
29847
- const notIndexed = packets.error instanceof HttpRelayError && packets.error.status === 404;
29848
- return {
29849
- ok: false,
29850
- error: this.detailedStatusLookupFailed(packets.error, key.srcChainKey, notIndexed ? missReason : void 0)
29851
- };
29852
- }
29853
- if (!packets.value?.success || !Array.isArray(packets.value.data)) {
29854
- return {
29855
- ok: false,
29856
- error: this.detailedStatusLookupFailed(
29857
- new Error("relay returned no usable transaction packets"),
29858
- key.srcChainKey
29859
- )
29860
- };
29861
- }
29862
- const delivered = packets.value.data.find(
29863
- (packet) => typeof packet?.src_tx_hash === "string" && packet.src_tx_hash.toLowerCase() === key.srcTxHash.toLowerCase() && packet.src_chain_id === Number(relayChainId) && packet.status === "executed" && typeof packet.dst_tx_hash === "string" && packet.dst_tx_hash.length > 0
29864
- );
29865
- if (!delivered) {
30529
+ const delivered = await resolveDeliveredPacket({
30530
+ srcChainKey: key.srcChainKey,
30531
+ srcTxHash: key.srcTxHash,
30532
+ relayerApiEndpoint: this.relayerApiEndpoint,
30533
+ backendAnswered
30534
+ });
30535
+ if (!delivered.ok) {
29866
30536
  return {
29867
30537
  ok: false,
29868
- error: this.detailedStatusLookupFailed(
29869
- new Error("relay has not delivered the intent to the hub yet"),
29870
- key.srcChainKey,
29871
- missReason
29872
- )
30538
+ error: this.detailedStatusLookupFailed(delivered.cause, key.srcChainKey, {
30539
+ reason: delivered.budgetable ? DETAILED_STATUS_NOT_DELIVERED : void 0
30540
+ })
29873
30541
  };
29874
30542
  }
29875
- hubTxHash = delivered.dst_tx_hash;
30543
+ hubTxHash = delivered.packet.dst_tx_hash;
29876
30544
  }
29877
30545
  if (viem.isHex(hubTxHash)) return { ok: true, value: hubTxHash };
29878
30546
  return {
@@ -29886,10 +30554,12 @@ var SwapService = class {
29886
30554
  /**
29887
30555
  * `reason` is set only for {@link DETAILED_STATUS_NOT_DELIVERED} — the miss a caller can bound
29888
30556
  * with a retry budget. Leaving it off marks a dependency that is failing right now, which a
29889
- * caller should keep retrying rather than give up on.
30557
+ * caller should keep retrying rather than give up on. `status` is lifted for a rejected key so
30558
+ * `isAuthFailure` recognises the wrapped error; it reads `context.status` and does not walk the
30559
+ * cause chain.
29890
30560
  */
29891
- detailedStatusLookupFailed(cause, srcChainKey, reason) {
29892
- return lookupFailed("swap", "getDetailedStatus", cause, { srcChainKey, action: "swap", reason });
30561
+ detailedStatusLookupFailed(cause, srcChainKey, extra) {
30562
+ return lookupFailed("swap", "getDetailedStatus", cause, { srcChainKey, action: "swap", ...extra });
29893
30563
  }
29894
30564
  /**
29895
30565
  * Notifies the solver API that an intent has been registered on the hub chain, triggering
@@ -30952,7 +31622,7 @@ var SwapService = class {
30952
31622
  /**
30953
31623
  * Offline, rule-based estimate of how fast a `srcToken`→`dstToken` swap will settle.
30954
31624
  *
30955
- * Derived purely from SDK config (no network / on-chain / backend call): tokens tied to a
31625
+ * Derived purely from SDK config (no network / on-chain / backend call): tokens whose vault is a
30956
31626
  * money-market-reserve sodaAsset settle faster, and an Ethereum leg adds a fixed penalty. See
30957
31627
  * {@link estimateSwapSpeedTier} for the rules.
30958
31628
  *
@@ -30960,7 +31630,7 @@ var SwapService = class {
30960
31630
  * @returns the estimated `tier` bucket and `estimatedSeconds`
30961
31631
  */
30962
31632
  getSwapSpeedTier(params) {
30963
- return estimateSwapSpeedTier(params, (hubAsset) => this.config.isMoneyMarketReserveHubAsset(hubAsset));
31633
+ return estimateSwapSpeedTier(params, (vault) => this.config.isMoneyMarketReserveAsset(vault));
30964
31634
  }
30965
31635
  };
30966
31636
 
@@ -33460,173 +34130,6 @@ var SponsoringApiService = class {
33460
34130
  return this.config.baseURL;
33461
34131
  }
33462
34132
  };
33463
- var RelayExtraDataResponseSchema = v__namespace.object({
33464
- address: v__namespace.string(),
33465
- payload: v__namespace.string()
33466
- });
33467
- var BridgeTokenSchema = v__namespace.object({
33468
- symbol: v__namespace.string(),
33469
- name: v__namespace.string(),
33470
- decimals: v__namespace.number(),
33471
- address: v__namespace.string(),
33472
- chainKey: v__namespace.string(),
33473
- hubAsset: v__namespace.string(),
33474
- vault: v__namespace.string()
33475
- });
33476
- var BridgeTokensResponseSchema = v__namespace.record(v__namespace.string(), v__namespace.array(BridgeTokenSchema));
33477
- var BridgeTokensByChainResponseSchema = v__namespace.array(BridgeTokenSchema);
33478
- var BridgeAllowanceCheckResponseSchema = v__namespace.object({
33479
- valid: v__namespace.boolean()
33480
- });
33481
- var makeBridgeApproveResponseSchema = (txSchema) => v__namespace.object({ tx: txSchema, resetTx: v__namespace.optional(txSchema) });
33482
- var makeCreateBridgeIntentResponseSchema = (txSchema) => v__namespace.object({
33483
- tx: txSchema,
33484
- relayData: RelayExtraDataResponseSchema
33485
- });
33486
- var BridgeSubmitTxResponseSchema = v__namespace.object({
33487
- success: v__namespace.boolean(),
33488
- data: v__namespace.object({
33489
- status: v__namespace.picklist(["inserted", "duplicate"]),
33490
- message: v__namespace.string()
33491
- })
33492
- });
33493
- var BridgePacketDataSchema = v__namespace.object({
33494
- src_chain_id: v__namespace.number(),
33495
- src_tx_hash: v__namespace.string(),
33496
- src_address: v__namespace.string(),
33497
- status: v__namespace.picklist(["pending", "validating", "executing", "executed"]),
33498
- dst_chain_id: v__namespace.number(),
33499
- conn_sn: v__namespace.number(),
33500
- dst_address: v__namespace.string(),
33501
- dst_tx_hash: v__namespace.string(),
33502
- signatures: v__namespace.array(v__namespace.string()),
33503
- payload: v__namespace.string()
33504
- });
33505
- var BridgeSubmitTxStatusResultSchema = v__namespace.object({
33506
- dstIntentTxHash: v__namespace.string(),
33507
- packetData: v__namespace.optional(BridgePacketDataSchema)
33508
- });
33509
- var BridgeSubmitTxStatusDataSchema = v__namespace.object({
33510
- txHash: v__namespace.string(),
33511
- srcChainKey: v__namespace.string(),
33512
- status: v__namespace.string(),
33513
- failedAtStep: v__namespace.optional(v__namespace.string()),
33514
- failureReason: v__namespace.optional(v__namespace.string()),
33515
- processingAttempts: v__namespace.number(),
33516
- abandonedAt: v__namespace.optional(v__namespace.string()),
33517
- result: v__namespace.optional(BridgeSubmitTxStatusResultSchema),
33518
- userMessage: v__namespace.optional(v__namespace.string())
33519
- });
33520
- var BridgeSubmitTxStatusResponseSchema = v__namespace.object({
33521
- success: v__namespace.boolean(),
33522
- data: BridgeSubmitTxStatusDataSchema
33523
- });
33524
- var BridgeFeeResponseSchema = v__namespace.object({ fee: v__namespace.string() });
33525
- var BridgeLimitSchema = v__namespace.object({
33526
- amount: v__namespace.string(),
33527
- decimals: v__namespace.number(),
33528
- type: v__namespace.picklist(["DEPOSIT_LIMIT", "WITHDRAWAL_LIMIT"])
33529
- });
33530
- var BridgeableAmountResponseSchema = v__namespace.object({ limit: BridgeLimitSchema });
33531
- var BridgeableCheckResponseSchema = v__namespace.object({ bridgeable: v__namespace.boolean() });
33532
- var AddressSchema2 = v__namespace.custom((input) => typeof input === "string");
33533
- var HexSchema = v__namespace.custom((input) => typeof input === "string");
33534
- var BigintFromString = v__namespace.pipe(v__namespace.string(), v__namespace.toBigint());
33535
- var BytesFromIndexRecord = v__namespace.pipe(
33536
- v__namespace.record(v__namespace.string(), v__namespace.number()),
33537
- v__namespace.transform((indexed) => Uint8Array.from(Object.values(indexed)))
33538
- );
33539
- var EvmRawTxSchema = v__namespace.object({
33540
- from: AddressSchema2,
33541
- to: AddressSchema2,
33542
- value: BigintFromString,
33543
- data: HexSchema
33544
- });
33545
- var SolanaRawTxSchema = v__namespace.object({
33546
- from: v__namespace.string(),
33547
- to: v__namespace.string(),
33548
- value: BigintFromString,
33549
- data: v__namespace.string()
33550
- });
33551
- var SuiRawTxSchema = v__namespace.object({
33552
- from: HexSchema,
33553
- to: v__namespace.string(),
33554
- value: BigintFromString,
33555
- data: v__namespace.string()
33556
- });
33557
- var StellarRawTxSchema = v__namespace.object({
33558
- from: v__namespace.string(),
33559
- to: v__namespace.string(),
33560
- value: BigintFromString,
33561
- data: v__namespace.string()
33562
- });
33563
- var BitcoinRawTxSchema = v__namespace.object({
33564
- from: v__namespace.string(),
33565
- to: v__namespace.string(),
33566
- value: BigintFromString,
33567
- data: v__namespace.string()
33568
- });
33569
- var InjectiveRawTxSchema = v__namespace.object({
33570
- from: HexSchema,
33571
- to: HexSchema,
33572
- signedDoc: v__namespace.object({
33573
- bodyBytes: BytesFromIndexRecord,
33574
- authInfoBytes: BytesFromIndexRecord,
33575
- chainId: v__namespace.string(),
33576
- accountNumber: BigintFromString
33577
- })
33578
- });
33579
- var NearRawTxSchema = v__namespace.object({
33580
- signerId: v__namespace.string(),
33581
- params: v__namespace.object({
33582
- contractId: v__namespace.string(),
33583
- method: v__namespace.string(),
33584
- args: v__namespace.custom((input) => typeof input === "object" && input !== null),
33585
- gas: v__namespace.optional(BigintFromString),
33586
- deposit: v__namespace.optional(BigintFromString)
33587
- })
33588
- });
33589
- var IconRawTxSchema = v__namespace.record(
33590
- v__namespace.string(),
33591
- v__namespace.union([v__namespace.string(), v__namespace.custom((input) => typeof input === "object" && input !== null)])
33592
- );
33593
- var StacksRawTxSchema = v__namespace.object({
33594
- payload: v__namespace.string(),
33595
- estimatedLength: v__namespace.optional(v__namespace.number())
33596
- });
33597
- var AnyRawTxSchema = v__namespace.custom((input) => typeof input === "object" && input !== null);
33598
- function rawTxSchemaForChainKey(chainKey) {
33599
- let chainType;
33600
- try {
33601
- chainType = getChainType(chainKey);
33602
- } catch {
33603
- chainType = void 0;
33604
- }
33605
- switch (chainType) {
33606
- case "EVM":
33607
- return EvmRawTxSchema;
33608
- case "SOLANA":
33609
- return SolanaRawTxSchema;
33610
- case "SUI":
33611
- return SuiRawTxSchema;
33612
- case "STELLAR":
33613
- return StellarRawTxSchema;
33614
- case "INJECTIVE":
33615
- return InjectiveRawTxSchema;
33616
- case "ICON":
33617
- return IconRawTxSchema;
33618
- case "STACKS":
33619
- return StacksRawTxSchema;
33620
- case "NEAR":
33621
- return NearRawTxSchema;
33622
- case "BITCOIN":
33623
- return BitcoinRawTxSchema;
33624
- default:
33625
- return AnyRawTxSchema;
33626
- }
33627
- }
33628
-
33629
- // src/backendApi/BridgeApiService.ts
33630
34133
  function toCreateBridgeIntentParamsV2(params, extras) {
33631
34134
  return {
33632
34135
  srcChainKey: params.srcChainKey,
@@ -33651,41 +34154,63 @@ var BridgeApiService = class {
33651
34154
  trimsLegacyOverrides;
33652
34155
  constructor(config, logger = consoleLogger, options = {}) {
33653
34156
  this.config = config;
33654
- this.headers = { ...config.headers };
34157
+ this.headers = mergeHeaders(config.headers);
33655
34158
  this.logger = logger;
33656
34159
  this.trimsLegacyOverrides = options.trimLegacyOverrides ?? true;
33657
34160
  }
33658
34161
  /**
33659
- * Issues a single HTTP request, validates the JSON body against `schema`, and
33660
- * wraps the result in `Result<T>`. The service-level `baseURL`/`timeout`/
33661
- * `headers` are merged with the optional per-call `overrideConfig` (which takes
33662
- * precedence) inside {@link makeRequest}. Every public method delegates here.
34162
+ * Build a `@sodax/bridge-api` client for a single call. Maps the SDK's {@link BaseApiConfig}
34163
+ * (`baseURL`/`timeout`/`headers`) to the package's config (`baseUrl`/`timeout`/`headers`), layering
34164
+ * the optional per-call `RequestOverrideConfig` on top (override wins per field; headers merge).
34165
+ * `timeout` falls back to the backend-API default so a config that omits it still gets a ceiling
34166
+ * rather than an unbounded request. Constructed per call so `setHeaders` mutations and per-call
34167
+ * overrides both take effect without caching stale state.
33663
34168
  */
33664
- async request(endpoint, config, schema, overrideConfig) {
34169
+ buildClient(overrideConfig) {
34170
+ const override = overrideConfig?.baseURL;
34171
+ const baseUrl = override ? this.trimsLegacyOverrides ? stripLegacyBackendMount(override) : override : this.config.baseURL;
34172
+ const timeout = overrideConfig?.timeout ?? this.config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
34173
+ const headers = mergeHeaders(this.headers, apiKeyHeader(overrideConfig?.apiKey), overrideConfig?.headers);
34174
+ return new bridgeApi.BridgeApi({ baseUrl, headers, timeout });
34175
+ }
34176
+ /**
34177
+ * Run one delegated `BridgeApi` call and wrap it in `Result<T>`. A thrown `BridgeApiError`
34178
+ * (network/timeout/HTTP/parse/validation) becomes `{ ok: false }` with a canonical
34179
+ * `SodaxError<'EXTERNAL_API_ERROR'>`; the original error is kept as `cause`, and its
34180
+ * `code`/`status`/`issues` are projected into `context` so consumers can discriminate failure
34181
+ * kinds without unwrapping `cause`. Only a RESPONSE-shape validation failure is tagged
34182
+ * `reason: 'invalid_response_shape'` — a request-side validation error is a caller bug, not a
34183
+ * backend fault.
34184
+ */
34185
+ async toResult(endpoint, call, overrideConfig) {
33665
34186
  try {
33666
- const raw = await makeRequest({
33667
- endpoint,
33668
- config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
33669
- // Normalized like a configured base URL: the override is the gateway root, so a legacy
33670
- // `/be`-suffixed value must not nest `/bridge/*` under the data API's mount — unless the config
33671
- // opted out of the legacy trim, in which case the per-call value is left exactly as given.
33672
- overrideConfig: this.trimsLegacyOverrides ? normalizeOverrideBaseURL(overrideConfig) : overrideConfig,
33673
- logger: this.logger,
33674
- serviceLabel: "BridgeApiService"
33675
- });
33676
- const parsed = v__namespace.safeParse(schema, raw);
33677
- if (!parsed.success) {
33678
- return {
33679
- ok: false,
33680
- error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from bridge API for ${endpoint}`, {
33681
- feature: "backend",
33682
- context: { api: "bridge", endpoint, reason: "invalid_response_shape", issues: v__namespace.flatten(parsed.issues) }
33683
- })
33684
- };
33685
- }
33686
- return { ok: true, value: parsed.output };
34187
+ const value = await call(this.buildClient(overrideConfig));
34188
+ return { ok: true, value };
33687
34189
  } catch (error) {
33688
- return { ok: false, error: toExternalApiError({ api: "bridge", feature: "backend", endpoint, error }) };
34190
+ const context = { api: "bridge", endpoint };
34191
+ if (error instanceof bridgeApi.BridgeApiError) {
34192
+ context.code = error.code;
34193
+ if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
34194
+ context.reason = "invalid_response_shape";
34195
+ const issues = error.context.issues;
34196
+ context.issues = issues instanceof v__namespace.ValiError ? v__namespace.flatten(issues.issues) : issues;
34197
+ }
34198
+ if (error.context.status !== void 0) context.status = error.context.status;
34199
+ if (isAuthStatus(error.context.status)) {
34200
+ this.logger.warn(
34201
+ `[BridgeApiService] ${endpoint} was rejected by the bridge API key guard (${error.context.status}). Configure a valid partner API key \u2014 new Sodax({ apiKey }) \u2014 see docs/CONFIGURE_SDK.md.`
34202
+ );
34203
+ }
34204
+ }
34205
+ this.logger.error(`[BridgeApiService] Request to ${endpoint} failed`, error);
34206
+ return {
34207
+ ok: false,
34208
+ error: new SodaxError(
34209
+ "EXTERNAL_API_ERROR",
34210
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
34211
+ { feature: "backend", cause: error, context }
34212
+ )
34213
+ };
33689
34214
  }
33690
34215
  }
33691
34216
  // ──────────────────────────────────────────────────────────────────────
@@ -33697,7 +34222,7 @@ var BridgeApiService = class {
33697
34222
  * @returns `Result<GetBridgeTokensResponseV2>` — map of chain key → token list.
33698
34223
  */
33699
34224
  async getTokens(config) {
33700
- return this.request("/bridge/tokens", { method: "GET" }, BridgeTokensResponseSchema, config);
34225
+ return this.toResult("/bridge/tokens", (c) => c.getTokens(), config);
33701
34226
  }
33702
34227
  /**
33703
34228
  * Fetch supported bridge tokens for a single SpokeChainKey.
@@ -33706,12 +34231,7 @@ var BridgeApiService = class {
33706
34231
  * @returns `Result<GetBridgeTokensByChainResponseV2>` — token list for the chain.
33707
34232
  */
33708
34233
  async getTokensByChain(chainKey, config) {
33709
- return this.request(
33710
- `/bridge/tokens/${chainKey}`,
33711
- { method: "GET" },
33712
- BridgeTokensByChainResponseSchema,
33713
- config
33714
- );
34234
+ return this.toResult(`/bridge/tokens/${chainKey}`, (c) => c.getTokensByChain(chainKey), config);
33715
34235
  }
33716
34236
  // ──────────────────────────────────────────────────────────────────────
33717
34237
  // Allowance · approve · create intent
@@ -33722,12 +34242,7 @@ var BridgeApiService = class {
33722
34242
  * @returns `Result<BridgeAllowanceCheckResponseV2>` — `{ valid }`.
33723
34243
  */
33724
34244
  async checkAllowance(body, config) {
33725
- return this.request(
33726
- "/bridge/allowance/check",
33727
- { method: "POST", body: toJsonBody(body) },
33728
- BridgeAllowanceCheckResponseSchema,
33729
- config
33730
- );
34245
+ return this.toResult("/bridge/allowance/check", (c) => c.checkAllowance(body), config);
33731
34246
  }
33732
34247
  /**
33733
34248
  * Build an unsigned token-approval transaction for the source token.
@@ -33736,13 +34251,7 @@ var BridgeApiService = class {
33736
34251
  * broadcast and mine `resetTx` first when it is present.
33737
34252
  */
33738
34253
  async approve(body, config) {
33739
- const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
33740
- return this.request(
33741
- "/bridge/approve",
33742
- { method: "POST", body: toJsonBody(body) },
33743
- makeBridgeApproveResponseSchema(txSchema),
33744
- config
33745
- );
34254
+ return this.toResult("/bridge/approve", (c) => c.approve(body), config);
33746
34255
  }
33747
34256
  /**
33748
34257
  * Build an unsigned spoke-deposit (create-bridge-intent) transaction.
@@ -33750,13 +34259,7 @@ var BridgeApiService = class {
33750
34259
  * @returns `Result<CreateBridgeIntentResponseV2>` — `{ tx, relayData }` (no intent struct).
33751
34260
  */
33752
34261
  async createBridgeIntent(body, config) {
33753
- const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
33754
- return this.request(
33755
- "/bridge/intents",
33756
- { method: "POST", body: toJsonBody(body) },
33757
- makeCreateBridgeIntentResponseSchema(txSchema),
33758
- config
33759
- );
34262
+ return this.toResult("/bridge/intents", (c) => c.createBridgeIntent(body), config);
33760
34263
  }
33761
34264
  // ──────────────────────────────────────────────────────────────────────
33762
34265
  // Submit-tx state machine
@@ -33768,12 +34271,7 @@ var BridgeApiService = class {
33768
34271
  * @returns `Result<BridgeSubmitTxResponseV2>` — `{ success, data: { status, message } }`.
33769
34272
  */
33770
34273
  async submitTx(body, config) {
33771
- return this.request(
33772
- "/bridge/submit-tx",
33773
- { method: "POST", body: toJsonBody(body) },
33774
- BridgeSubmitTxResponseSchema,
33775
- config
33776
- );
34274
+ return this.toResult("/bridge/submit-tx", (c) => c.submitTx(body), config);
33777
34275
  }
33778
34276
  /**
33779
34277
  * Get the processing status of a submitted bridge transaction by `(txHash, srcChainKey)`.
@@ -33781,13 +34279,7 @@ var BridgeApiService = class {
33781
34279
  * @returns `Result<BridgeSubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
33782
34280
  */
33783
34281
  async getSubmitTxStatus(query, config) {
33784
- const queryParams = new URLSearchParams({ txHash: query.txHash, srcChainKey: query.srcChainKey });
33785
- return this.request(
33786
- `/bridge/submit-tx/status?${queryParams.toString()}`,
33787
- { method: "GET" },
33788
- BridgeSubmitTxStatusResponseSchema,
33789
- config
33790
- );
34282
+ return this.toResult("/bridge/submit-tx/status", (c) => c.getSubmitTxStatus(query), config);
33791
34283
  }
33792
34284
  // ──────────────────────────────────────────────────────────────────────
33793
34285
  // Fee · bridgeable quote (read-only; mirror the SDK-core client-side methods)
@@ -33801,12 +34293,7 @@ var BridgeApiService = class {
33801
34293
  * @returns `Result<BridgeFeeResponseV2>` — `{ fee }` (decimal string).
33802
34294
  */
33803
34295
  async getFee(body, config) {
33804
- return this.request(
33805
- "/bridge/fee",
33806
- { method: "POST", body: toJsonBody(body) },
33807
- BridgeFeeResponseSchema,
33808
- config
33809
- );
34296
+ return this.toResult("/bridge/fee", (c) => c.getFee(body), config);
33810
34297
  }
33811
34298
  /**
33812
34299
  * Deposit capacity / withdrawal liquidity for a (from, to) token pair. Computable client-side in the
@@ -33815,12 +34302,7 @@ var BridgeApiService = class {
33815
34302
  * @returns `Result<BridgeableAmountResponseV2>` — `{ limit }`.
33816
34303
  */
33817
34304
  async getBridgeableAmount(body, config) {
33818
- return this.request(
33819
- "/bridge/bridgeable-amount",
33820
- { method: "POST", body: toJsonBody(body) },
33821
- BridgeableAmountResponseSchema,
33822
- config
33823
- );
34305
+ return this.toResult("/bridge/bridgeable-amount", (c) => c.getBridgeableAmount(body), config);
33824
34306
  }
33825
34307
  /**
33826
34308
  * Whether a (from, to) token pair is bridgeable. Computable client-side in the SDK core
@@ -33829,19 +34311,15 @@ var BridgeApiService = class {
33829
34311
  * @returns `Result<BridgeableCheckResponseV2>` — `{ bridgeable }`.
33830
34312
  */
33831
34313
  async isBridgeable(body, config) {
33832
- return this.request(
33833
- "/bridge/bridgeable/check",
33834
- { method: "POST", body: toJsonBody(body) },
33835
- BridgeableCheckResponseSchema,
33836
- config
33837
- );
34314
+ return this.toResult("/bridge/bridgeable/check", (c) => c.isBridgeable(body), config);
33838
34315
  }
33839
34316
  // ──────────────────────────────────────────────────────────────────────
33840
34317
  // Utilities (parity with SwapsApiService)
33841
34318
  // ──────────────────────────────────────────────────────────────────────
33842
34319
  /**
33843
34320
  * Merge additional headers into the service's default header set. Existing
33844
- * keys are overwritten; keys absent from `headers` are preserved.
34321
+ * keys are overwritten; keys absent from `headers` are preserved. Applied to
34322
+ * every subsequent call (the delegated client is rebuilt per call).
33845
34323
  */
33846
34324
  setHeaders(headers) {
33847
34325
  assignHeaders(this.headers, headers);
@@ -35692,6 +36170,80 @@ var BridgeService = class {
35692
36170
  }
35693
36171
  return encodeContractCalls(calls);
35694
36172
  }
36173
+ /**
36174
+ * Answers "what is the status of this bridge?" from the **source-chain** tx — the one identifier a
36175
+ * caller always holds. It does not define a new status: it routes to whichever of the two existing
36176
+ * sources can answer, and returns that source's payload unmodified.
36177
+ *
36178
+ * `sodax.api.bridge.getSubmitTxStatus` cannot answer for every bridge. Sometimes there is no
36179
+ * record — `useBackendSubmitTx: false`, or the submit itself never landed. More often the record
36180
+ * exists but is stale: the backend path POSTs the tx first and only falls back to the client-side
36181
+ * relay once that stalls, so a fallback-completed bridge leaves behind whatever state the backend
36182
+ * last reached, including a record it abandoned outright. Neither shape reflects what happened.
36183
+ *
36184
+ * 1. Read the backend record; return it while it is still in play.
36185
+ * 2. Otherwise return the delivered relay packet, which is terminal by construction.
36186
+ *
36187
+ * A rejected API key is the one failure that does **not** fall through to step 2: the status route
36188
+ * is key-guarded, so degrading would bury a 401/403 behind a relay error and leave a poller
36189
+ * retrying a request only a corrected key can satisfy. It surfaces with `context.status` instead,
36190
+ * which is what `isAuthFailure` reads.
36191
+ *
36192
+ * A point-in-time read; poll it yourself, or use dapp-kit's `useBridgeDetailedStatus`.
36193
+ *
36194
+ * @param params - `srcChainKey` and `srcTxHash` of the source-chain bridge transaction.
36195
+ * @param config - Optional per-request override for the backend read (e.g. a per-action API key).
36196
+ * The relay leg is unauthenticated and takes none.
36197
+ * @returns A `Result` containing a {@link DetailedBridgeStatus}. Fails with `LOOKUP_FAILED` when no
36198
+ * source can answer yet — usually the relay has not delivered the packet. Branch on
36199
+ * `error.context.reason`: `DETAILED_STATUS_NOT_DELIVERED` is the ambiguous miss a caller should
36200
+ * bound with a retry budget; anything else is a dependency failing right now, so keep retrying.
36201
+ */
36202
+ async getDetailedStatus(params, config) {
36203
+ try {
36204
+ const record = await this.backendApi.bridge.getSubmitTxStatus(
36205
+ { txHash: params.srcTxHash, srcChainKey: params.srcChainKey },
36206
+ config
36207
+ );
36208
+ if (record.ok && record.value.success && !isBackendSubmitTxAbandoned(record.value.data)) {
36209
+ return { ok: true, value: { source: "backend", data: record.value.data } };
36210
+ }
36211
+ if (!record.ok && isSodaxError(record.error) && isAuthFailure(record.error)) {
36212
+ return {
36213
+ ok: false,
36214
+ error: this.detailedStatusLookupFailed(record.error, params.srcChainKey, {
36215
+ status: record.error.context?.status
36216
+ })
36217
+ };
36218
+ }
36219
+ const backendAnswered = record.ok || isSodaxError(record.error) && record.error.context?.status === 404;
36220
+ const delivered = await resolveDeliveredPacket({
36221
+ srcChainKey: params.srcChainKey,
36222
+ srcTxHash: params.srcTxHash,
36223
+ relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
36224
+ backendAnswered
36225
+ });
36226
+ if (!delivered.ok) {
36227
+ return {
36228
+ ok: false,
36229
+ error: this.detailedStatusLookupFailed(delivered.cause, params.srcChainKey, {
36230
+ reason: delivered.budgetable ? DETAILED_STATUS_NOT_DELIVERED : void 0
36231
+ })
36232
+ };
36233
+ }
36234
+ return { ok: true, value: { source: "relay", data: delivered.packet } };
36235
+ } catch (error) {
36236
+ return { ok: false, error: this.detailedStatusLookupFailed(error, params.srcChainKey) };
36237
+ }
36238
+ }
36239
+ /**
36240
+ * `reason` is set only for {@link DETAILED_STATUS_NOT_DELIVERED} — the miss a caller can bound with
36241
+ * a retry budget. `status` is lifted for a rejected key so `isAuthFailure` recognises the wrapped
36242
+ * error; it reads `context.status` and does not walk the cause chain.
36243
+ */
36244
+ detailedStatusLookupFailed(cause, srcChainKey, extra) {
36245
+ return lookupFailed("bridge", "getDetailedStatus", cause, { srcChainKey, action: "bridge", ...extra });
36246
+ }
35695
36247
  /**
35696
36248
  * Returns the maximum amount that can currently be bridged between two tokens,
35697
36249
  * taking into account both deposit capacity on the source side and withdrawal liquidity
@@ -43865,6 +44417,24 @@ var isLeverageYieldPostExecutionError = isCodeMember(
43865
44417
  var isLeverageYieldSwapError = isCodeMember(LEVERAGE_YIELD_SWAP_CODES);
43866
44418
  var isLeverageYieldError = isCodeMember(LEVERAGE_YIELD_CODES);
43867
44419
 
44420
+ // src/leverageYield/positionFunding.ts
44421
+ function resolvePositionFundingAddress(chainKey, hubChainKey, token) {
44422
+ if (chainKey !== hubChainKey) return token?.address ?? "";
44423
+ if (token && isNativeToken(chainKey, token)) return token.address;
44424
+ return token?.hubAsset ?? token?.address ?? "";
44425
+ }
44426
+
44427
+ // src/leverageYield/positionIntent.ts
44428
+ async function reportPositionIntent(notifySolver, txHashes) {
44429
+ const result = await notifySolver({ intent_tx_hash: txHashes.dstChainTxHash }).catch((error2) => ({
44430
+ ok: false,
44431
+ error: error2
44432
+ }));
44433
+ if (result.ok) return { txHashes, notified: true };
44434
+ const { error } = result;
44435
+ return { txHashes, notified: false, notifyError: error instanceof Error ? error.message : String(error) };
44436
+ }
44437
+
43868
44438
  // src/leverageYield/LeverageYieldService.ts
43869
44439
  var leverageYieldVaultAbi = viem.parseAbi([
43870
44440
  "function asset() view returns (address)",
@@ -43874,7 +44444,33 @@ var leverageYieldVaultAbi = viem.parseAbi([
43874
44444
  "function borrowToken() view returns (address)",
43875
44445
  "function targetLTV() view returns (uint256)"
43876
44446
  ]);
44447
+ var MAX_POSITION_FEE_BPS = 100;
44448
+ var leveragePositionFactoryAbi = viem.parseAbi([
44449
+ "function positionsOf(address owner) view returns (address[])",
44450
+ "function nextPositionIdFor(address owner) view returns (uint256)",
44451
+ "function predictPosition(address creator, address owner, uint256 positionId) view returns (address)",
44452
+ "function createPositionAndLeverage((address owner, address collateral, address borrowToken, uint8 eModeCategory, uint256 originChainId, bytes originAddress, address originAsset, address feeReceiver, uint16 feeBps) cfg, uint256 initialAssets, uint256 borrowAmount, uint256 minCollateralOut) returns (address)",
44453
+ "function createPositionFromDebtToken((address owner, address collateral, address borrowToken, uint8 eModeCategory, uint256 originChainId, bytes originAddress, address originAsset, address feeReceiver, uint16 feeBps) cfg, uint256 contribution, uint256 totalInput, uint256 minCollateralOut) returns (address)"
44454
+ ]);
44455
+ var leveragePositionAbi = viem.parseAbi([
44456
+ "function owner() view returns (address)",
44457
+ "function collateral() view returns (address)",
44458
+ "function borrowToken() view returns (address)",
44459
+ "function eModeCategory() view returns (uint8)",
44460
+ "function feeBps() view returns (uint16)",
44461
+ "function feeReceiver() view returns (address)",
44462
+ "function hasPendingOperation() view returns (bool)",
44463
+ "function pendingKind() view returns (uint8)",
44464
+ "function addLeverage(uint256 borrowAmount, uint256 minCollateralOut)",
44465
+ "function decreaseLeverage(uint256 collateralIn, uint256 minDebtOut, address exitAsset)",
44466
+ "function withdraw(uint256 amount, address to)",
44467
+ "function cancel()",
44468
+ "function settle()"
44469
+ ]);
43877
44470
  var INTENT_DEADLINE_BUFFER_SECONDS = 5 * 60;
44471
+ var RECONCILE_TIMEOUT_MS2 = 5e3;
44472
+ var DETAILED_STATUS_SOLVER_TIMEOUT_MS2 = 5e3;
44473
+ var BITCOIN_UNSUPPORTED_MESSAGE = "Bitcoin is not a supported source chain for leverage positions; use a supported spoke or the hub";
43878
44474
  var ANY_SOLVER_ADDRESS = "0x0000000000000000000000000000000000000000";
43879
44475
  var MAX_WITHDRAW_DUST_BUFFER = 1000n;
43880
44476
  function pctToRay(aprPct) {
@@ -43911,9 +44507,9 @@ var LeverageYieldService = class {
43911
44507
  spoke;
43912
44508
  backendApi;
43913
44509
  /**
43914
- * Effective backend submit-tx flow (`leverageYield.useBackendSubmitTx`, default off). Read live off
43915
- * `ConfigService`, like `config.leverageYieldPartnerFee`, so the config object and the behavior can
43916
- * never disagree.
44510
+ * Effective backend submit-tx flow (`leverageYield.useBackendSubmitTx`, default ON; opt out with
44511
+ * `false`). Read live off `ConfigService`, like `config.leverageYieldPartnerFee`, so the config
44512
+ * object and the behavior can never disagree.
43917
44513
  */
43918
44514
  get useBackendSubmitTx() {
43919
44515
  return this.config.leverageYieldUseBackendSubmitTx;
@@ -43931,7 +44527,7 @@ var LeverageYieldService = class {
43931
44527
  }
43932
44528
  /** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
43933
44529
  getVault(name) {
43934
- return this.listVaults().find((v12) => v12.name === name);
44530
+ return this.listVaults().find((v10) => v10.name === name);
43935
44531
  }
43936
44532
  /**
43937
44533
  * Looks up a registered vault by its on-chain proxy address (case-insensitive).
@@ -43939,7 +44535,7 @@ var LeverageYieldService = class {
43939
44535
  */
43940
44536
  getVaultByAddress(address) {
43941
44537
  const normalized = address.toLowerCase();
43942
- return this.listVaults().find((v12) => v12.vault.toLowerCase() === normalized);
44538
+ return this.listVaults().find((v10) => v10.vault.toLowerCase() === normalized);
43943
44539
  }
43944
44540
  /**
43945
44541
  * Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
@@ -44405,10 +45001,11 @@ var LeverageYieldService = class {
44405
45001
  );
44406
45002
  }
44407
45003
  /**
44408
- * Client-side vault-swap completion (the default path): verify the broadcast intent tx landed,
45004
+ * Client-side vault-swap completion (the opt-out path, and the fallback): verify the broadcast
45005
+ * intent tx landed,
44409
45006
  * relay it to the hub (Sonic) — or use it directly when the source IS the hub — then notify the
44410
45007
  * solver via {@link LeverageYieldService.notifySolver} and build the {@link VaultSwapResponse}.
44411
- * Extracted from `vaultSwap()` so the opt-in backend 2-step path ({@link LeverageYieldService.submitTx})
45008
+ * Extracted from `vaultSwap()` so the default backend 2-step path ({@link LeverageYieldService.submitTx})
44412
45009
  * can fall back to it on any non-success. Leverage-yield copy of `SwapService.fallbackSwapSteps`.
44413
45010
  */
44414
45011
  async fallbackVaultSwapSteps(_params, created, timeoutMs) {
@@ -44466,7 +45063,8 @@ var LeverageYieldService = class {
44466
45063
  };
44467
45064
  }
44468
45065
  /**
44469
- * Backend 2-step vault-swap path (opt-in via `leverageYield.useBackendSubmitTx`): hand the
45066
+ * Backend 2-step vault-swap path (the default; opt out with `leverageYield.useBackendSubmitTx:
45067
+ * false`): hand the
44470
45068
  * broadcast intent tx to the leverage-yield API (`POST /leverage-yield/submit-tx`); the backend
44471
45069
  * relays + post-executes server-side. Polls `getSubmitTxStatus` until `solved`, then reconstructs
44472
45070
  * the same {@link VaultSwapResponse} the client-side path returns.
@@ -44505,6 +45103,10 @@ var LeverageYieldService = class {
44505
45103
  operation: _params.hubWalletSwap ? "withdraw" : "deposit"
44506
45104
  },
44507
45105
  statusQuery: { txHash: spokeTxHash, srcChainKey },
45106
+ // Per-action key wins over the instance one for both legs of the attempt — the submit POST
45107
+ // and its status polls. Undefined leaves the configured key in place; the same per-action
45108
+ // override `extras.partnerFee` already has, travelling per call.
45109
+ overrideConfig: { apiKey: _params.extras?.apiKey },
44508
45110
  // A vault deposit/withdraw IS a solver swap, so terminal success is `solved` — not bridge's
44509
45111
  // `executed`.
44510
45112
  terminalStatus: "solved",
@@ -44528,7 +45130,12 @@ var LeverageYieldService = class {
44528
45130
  }
44529
45131
  }
44530
45132
  /**
44531
- * Notifies the solver that the vault intent landed on the hub, triggering it to fill.
45133
+ * Notifies the solver that an intent landed on the hub, triggering it to fill.
45134
+ *
45135
+ * REQUIRED for anything that creates an intent, not an optimisation. An intent created on the hub
45136
+ * is invisible to the solver until this call puts it in the task pool, so an unnotified intent
45137
+ * simply expires. Leverage positions post their intents on-chain from the position contract, so
45138
+ * the caller that sent the transaction is the only one who can report the hash.
44532
45139
  * Leverage-yield copy of the swap domain's `postExecution` — emits only
44533
45140
  * `EXECUTION_FAILED` / `EXTERNAL_API_ERROR` / `UNKNOWN` (relay/verify codes appear only
44534
45141
  * on {@link LeverageYieldService.vaultSwap}, which owns the verify + relay steps).
@@ -44573,6 +45180,209 @@ var LeverageYieldService = class {
44573
45180
  return { ok: false, error: executionFailed("leverageYield", error, { phase: "postExecution" }) };
44574
45181
  }
44575
45182
  }
45183
+ /**
45184
+ * Polls the solver for the execution status of an intent this service created.
45185
+ *
45186
+ * Pair with {@link LeverageYieldService.notifySolver}: `notifySolver` puts the intent in the
45187
+ * solver's task pool, this reports what became of it. `fill_tx_hash` is set only once
45188
+ * `status === SolverIntentStatusCode.SOLVED`.
45189
+ *
45190
+ * A `NOT_FOUND` status usually means the notification never landed rather than that the intent
45191
+ * does not exist — an intent created on the hub is invisible to the solver until it is told.
45192
+ *
45193
+ * Reports the solver verbatim. It does NOT reconcile a `NOT_FOUND` against the backend's durable
45194
+ * record the way {@link LeverageYieldService.getDetailedStatus} does — a restarted solver answers
45195
+ * `NOT_FOUND` for intents it already filled, and that read resolves it. Keeping this one
45196
+ * unreconciled is deliberate: it has shipped with this contract, and folding the reconcile in
45197
+ * would turn a `NOT_FOUND` behind an unreadable backend into an error for every existing caller.
45198
+ * Prefer `getDetailedStatus` when you hold the source tx hash.
45199
+ *
45200
+ * @param request - `{ intent_tx_hash }` — the hub-chain (Sonic) tx hash the intent was
45201
+ * registered in. For a position that is the tx that called the factory or the position.
45202
+ */
45203
+ async getIntentStatus(request) {
45204
+ try {
45205
+ const result = await this.solverStatus(request);
45206
+ if (result.ok) return result;
45207
+ const detail = result.error?.detail ?? {
45208
+ code: exports.SolverIntentErrorCode.UNKNOWN,
45209
+ message: "Solver returned malformed error response"
45210
+ };
45211
+ return {
45212
+ ok: false,
45213
+ error: new SodaxError("EXTERNAL_API_ERROR", detail.message, {
45214
+ feature: "leverageYield",
45215
+ context: {
45216
+ phase: "lookup",
45217
+ api: "solver",
45218
+ solverCode: detail.code,
45219
+ solverDetail: detail
45220
+ }
45221
+ })
45222
+ };
45223
+ } catch (error) {
45224
+ if (isLeverageYieldPostExecutionError(error)) return { ok: false, error };
45225
+ return { ok: false, error: executionFailed("leverageYield", error, { phase: "lookup" }) };
45226
+ }
45227
+ }
45228
+ /**
45229
+ * The raw solver read, in the solver's own vocabulary. Both public status surfaces start here; the
45230
+ * api key is the 5th argument, and leaving it out let a keyed partner notify and then fail to poll.
45231
+ */
45232
+ async solverStatus(request, timeoutMs, apiKey) {
45233
+ return SolverApiService.getStatus(
45234
+ request,
45235
+ this.config.solver,
45236
+ this.config.logger,
45237
+ timeoutMs,
45238
+ apiKey || this.config.apiKey
45239
+ );
45240
+ }
45241
+ /**
45242
+ * {@link LeverageYieldService.solverStatus} plus the durable-record reconcile, for
45243
+ * {@link LeverageYieldService.getDetailedStatus}. Deliberately not shared with
45244
+ * {@link LeverageYieldService.getIntentStatus}: the reconcile turns a `NOT_FOUND` behind an
45245
+ * unreadable backend into an error, which is right for a polled read that would otherwise spend a
45246
+ * budget on an unverified miss, and wrong to impose on a surface that already ships without it.
45247
+ *
45248
+ * `timeoutMs` bounds the solver request alone. The reconcile carries its own
45249
+ * {@link RECONCILE_TIMEOUT_MS}, so a bounded call can cost both.
45250
+ */
45251
+ async resolveSolverStatus(request, timeoutMs, apiKey) {
45252
+ const solverResult = await this.solverStatus(request, timeoutMs, apiKey);
45253
+ const forgotten = !solverResult.ok || solverResult.value.status === exports.SolverIntentStatusCode.NOT_FOUND;
45254
+ if (!forgotten) return solverResult;
45255
+ const timeout = Math.min(RECONCILE_TIMEOUT_MS2, this.backendApi.requestTimeoutMs);
45256
+ const intent = await this.backendApi.getIntentByTxHash(request.intent_tx_hash, { timeout, apiKey });
45257
+ const settled = intent.ok ? intent.value.events.filter(isFillEvent).find((fill) => fill.intentState.remainingInput === "0") : void 0;
45258
+ if (settled) return { ok: true, value: { status: exports.SolverIntentStatusCode.SOLVED, fill_tx_hash: settled.txHash } };
45259
+ const backendAnswered = intent.ok || isSodaxError(intent.error) && intent.error.context?.status === 404;
45260
+ if (solverResult.ok && !backendAnswered) {
45261
+ return {
45262
+ ok: false,
45263
+ error: {
45264
+ detail: {
45265
+ code: exports.SolverIntentErrorCode.UNKNOWN,
45266
+ message: "solver reported NOT_FOUND and the durable intent record could not be read to verify it"
45267
+ }
45268
+ }
45269
+ };
45270
+ }
45271
+ return solverResult;
45272
+ }
45273
+ /**
45274
+ * Reads a vault swap's status from its source-chain transaction — the identifier a caller always
45275
+ * holds after `vaultSwap()`.
45276
+ *
45277
+ * **Routes; does not translate.** Returns the backend submit-tx record while it is in play,
45278
+ * otherwise the solver's answer via the hub tx hash resolved from the relay packet. The result is
45279
+ * tagged with `source` (discriminate on it) and carries that source's payload unmodified.
45280
+ *
45281
+ * `sodax.api.leverageYield.getSubmitTxStatus` cannot answer for every vault swap. Sometimes there
45282
+ * is no record — `useBackendSubmitTx: false`, or the submit was rejected. More often the record
45283
+ * exists but is stale: the backend path POSTs first and falls back to the client-side relay once
45284
+ * that stalls, so a fallback-completed vault swap leaves behind whatever state the backend last
45285
+ * reached, including a record it abandoned outright.
45286
+ *
45287
+ * **Any** unusable backend response routes to the solver — a 404, a transport or server error, or
45288
+ * a record the backend gave up on. A rejected API key is the exception: it is not a source with
45289
+ * nothing to say, it is a configuration problem only a corrected key resolves, so routing it on
45290
+ * would bury it behind a relay or solver error and leave a poller retrying a request that cannot
45291
+ * succeed. The same rule the swap and bridge siblings apply. It holds here even though
45292
+ * `GET /leverage-yield/submit-tx/status` declares no scope of its own: whether a key is checked
45293
+ * is a per-deployment setting, so this must not assume the read is unauthenticated.
45294
+ *
45295
+ * A point-in-time read; poll it yourself, or use dapp-kit's `useLeverageYieldDetailedStatus`.
45296
+ *
45297
+ * @param params - `srcChainKey` and `srcTxHash` of the source-chain vault-swap transaction.
45298
+ * @param config - Optional per-request override. Its `apiKey` reaches every keyed leg — the
45299
+ * submit-tx record read, the solver read, and the durable-intent read a solver `NOT_FOUND` falls
45300
+ * back to — so one override keys the whole call. The relay leg is unauthenticated and takes none.
45301
+ * @returns A `Result` containing a {@link DetailedLeverageYieldStatus}. Fails with `LOOKUP_FAILED`
45302
+ * when no source can answer yet. Branch on `error.context.reason`:
45303
+ * `DETAILED_STATUS_NOT_DELIVERED` is the ambiguous miss a caller should bound with a retry
45304
+ * budget; anything else is a dependency failing right now, so keep retrying.
45305
+ */
45306
+ async getDetailedStatus(params, config) {
45307
+ try {
45308
+ const record = await this.backendApi.leverageYield.getSubmitTxStatus(
45309
+ { txHash: params.srcTxHash, srcChainKey: params.srcChainKey },
45310
+ config
45311
+ );
45312
+ if (record.ok && record.value.success && !isBackendSubmitTxAbandoned(record.value.data)) {
45313
+ return { ok: true, value: { source: "backend", data: record.value.data } };
45314
+ }
45315
+ if (!record.ok && isSodaxError(record.error) && isAuthFailure(record.error)) {
45316
+ return {
45317
+ ok: false,
45318
+ error: this.detailedStatusLookupFailed(record.error, params.srcChainKey, {
45319
+ status: record.error.context?.status
45320
+ })
45321
+ };
45322
+ }
45323
+ const backendAnswered = record.ok || isSodaxError(record.error) && record.error.context?.status === 404;
45324
+ const dstTxHash = await this.resolveHubTxHash(params, backendAnswered);
45325
+ if (!dstTxHash.ok) return dstTxHash;
45326
+ const solver = await this.resolveSolverStatus(
45327
+ { intent_tx_hash: dstTxHash.value },
45328
+ DETAILED_STATUS_SOLVER_TIMEOUT_MS2,
45329
+ config?.apiKey
45330
+ );
45331
+ if (!solver.ok) {
45332
+ return { ok: false, error: this.detailedStatusLookupFailed(solver.error, params.srcChainKey) };
45333
+ }
45334
+ return { ok: true, value: { source: "solver", dstTxHash: dstTxHash.value, data: solver.value } };
45335
+ } catch (error) {
45336
+ return { ok: false, error: this.detailedStatusLookupFailed(error, params.srcChainKey) };
45337
+ }
45338
+ }
45339
+ /**
45340
+ * The hub-chain tx hash the solver is keyed on. A hub-source vault swap has no relay leg — the
45341
+ * source tx *is* the hub tx. Otherwise the delivered relay packet carries it, so an undelivered
45342
+ * packet is simply "no hash yet".
45343
+ */
45344
+ async resolveHubTxHash(key, backendAnswered) {
45345
+ let hubTxHash = key.srcTxHash;
45346
+ if (!isHubChainKeyType(key.srcChainKey)) {
45347
+ const delivered = await resolveDeliveredPacket({
45348
+ srcChainKey: key.srcChainKey,
45349
+ srcTxHash: key.srcTxHash,
45350
+ relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
45351
+ backendAnswered
45352
+ });
45353
+ if (!delivered.ok) {
45354
+ return {
45355
+ ok: false,
45356
+ error: this.detailedStatusLookupFailed(delivered.cause, key.srcChainKey, {
45357
+ reason: delivered.budgetable ? DETAILED_STATUS_NOT_DELIVERED : void 0
45358
+ })
45359
+ };
45360
+ }
45361
+ hubTxHash = delivered.packet.dst_tx_hash;
45362
+ }
45363
+ if (viem.isHex(hubTxHash)) return { ok: true, value: hubTxHash };
45364
+ return {
45365
+ ok: false,
45366
+ error: this.detailedStatusLookupFailed(
45367
+ new Error(`hub tx hash is not a hex string: ${hubTxHash}`),
45368
+ key.srcChainKey
45369
+ )
45370
+ };
45371
+ }
45372
+ /**
45373
+ * `reason` is set only for {@link DETAILED_STATUS_NOT_DELIVERED} — the miss a caller can bound
45374
+ * with a retry budget. Leaving it off marks a dependency that is failing right now, which a
45375
+ * caller should keep retrying rather than give up on. `status` is lifted for a rejected key so
45376
+ * `isAuthFailure` recognises the wrapped error; it reads `context.status` and does not walk the
45377
+ * cause chain.
45378
+ */
45379
+ detailedStatusLookupFailed(cause, srcChainKey, extra) {
45380
+ return lookupFailed("leverageYield", "getDetailedStatus", cause, {
45381
+ srcChainKey,
45382
+ action: "vaultSwap",
45383
+ ...extra
45384
+ });
45385
+ }
44576
45386
  /**
44577
45387
  * Approves the vault's underlying asset to the leverage vault on Sonic. For callers
44578
45388
  * interacting with the vault directly on the hub — the swap-style {@link
@@ -44881,6 +45691,1252 @@ var LeverageYieldService = class {
44881
45691
  return { ok: false, error: lookupFailed("leverageYield", "getShareBalanceForUser", error, { srcChainKey }) };
44882
45692
  }
44883
45693
  }
45694
+ // ─── Leverage positions ────────────────────────────────────────────────
45695
+ /**
45696
+ * Resolves the `LeveragePositionFactory` address, or a validation error when it is missing.
45697
+ *
45698
+ * The deployed factory ships in `leverageYieldConfig`, so this only fails when an integrator
45699
+ * overrides it with an empty value — which is what a bad env var produces. Failing closed there is
45700
+ * deliberate: a placeholder address would post real intents at nothing.
45701
+ */
45702
+ requireFactory(action) {
45703
+ const factory = this.config.sodaxConfig.leverageYield.positionFactory;
45704
+ if (!factory) {
45705
+ return {
45706
+ ok: false,
45707
+ error: lookupFailed(
45708
+ "leverageYield",
45709
+ action,
45710
+ new Error("leverageYield.positionFactory is not configured; supply the deployed factory address")
45711
+ )
45712
+ };
45713
+ }
45714
+ return { ok: true, value: factory };
45715
+ }
45716
+ /** Position clones owned by `owner`, in creation order. Empty when the owner has none. */
45717
+ async listPositions(owner) {
45718
+ const factory = this.requireFactory("listPositions");
45719
+ if (!factory.ok) return factory;
45720
+ try {
45721
+ const value = await this.hubProvider.publicClient.readContract({
45722
+ address: factory.value,
45723
+ abi: leveragePositionFactoryAbi,
45724
+ functionName: "positionsOf",
45725
+ args: [owner]
45726
+ });
45727
+ return { ok: true, value };
45728
+ } catch (error) {
45729
+ if (isLeverageYieldLookupError(error)) return { ok: false, error };
45730
+ return { ok: false, error: lookupFailed("leverageYield", "listPositions", error) };
45731
+ }
45732
+ }
45733
+ /**
45734
+ * Positions belonging to a user, resolved by their spoke-side address rather than a hub address.
45735
+ *
45736
+ * Positions are owned by the user's hub wallet, so discovery goes through
45737
+ * `getUserHubWalletAddress` — which returns the wallet router for a Sonic user and the
45738
+ * cross-chain wallet for a spoke user, so the same call works on every chain. Prefer this over
45739
+ * `listPositions` in user-facing code; passing a raw EOA finds nothing.
45740
+ */
45741
+ async listPositionsForUser(srcChainKey, srcAddress) {
45742
+ try {
45743
+ const hubWallet = await this.hubProvider.getUserHubWalletAddress(srcAddress, srcChainKey);
45744
+ return await this.listPositions(hubWallet);
45745
+ } catch (error) {
45746
+ if (isLeverageYieldLookupError(error)) return { ok: false, error };
45747
+ return { ok: false, error: lookupFailed("leverageYield", "listPositionsForUser", error, { srcChainKey }) };
45748
+ }
45749
+ }
45750
+ /** Static descriptor of a position — owner, both legs, and the fixed eMode category. */
45751
+ async getPositionInfo(position) {
45752
+ try {
45753
+ const [owner, collateral, borrowToken, eModeCategory, feeBps, feeReceiver] = await Promise.all([
45754
+ this.hubProvider.publicClient.readContract({
45755
+ address: position,
45756
+ abi: leveragePositionAbi,
45757
+ functionName: "owner"
45758
+ }),
45759
+ this.hubProvider.publicClient.readContract({
45760
+ address: position,
45761
+ abi: leveragePositionAbi,
45762
+ functionName: "collateral"
45763
+ }),
45764
+ this.hubProvider.publicClient.readContract({
45765
+ address: position,
45766
+ abi: leveragePositionAbi,
45767
+ functionName: "borrowToken"
45768
+ }),
45769
+ this.hubProvider.publicClient.readContract({
45770
+ address: position,
45771
+ abi: leveragePositionAbi,
45772
+ functionName: "eModeCategory"
45773
+ }),
45774
+ this.hubProvider.publicClient.readContract({
45775
+ address: position,
45776
+ abi: leveragePositionAbi,
45777
+ functionName: "feeBps"
45778
+ }),
45779
+ this.hubProvider.publicClient.readContract({
45780
+ address: position,
45781
+ abi: leveragePositionAbi,
45782
+ functionName: "feeReceiver"
45783
+ })
45784
+ ]);
45785
+ return {
45786
+ ok: true,
45787
+ value: {
45788
+ address: position,
45789
+ owner,
45790
+ collateral,
45791
+ borrowToken,
45792
+ eModeCategory,
45793
+ // From the position, not from config: config can change and an open can override it, so
45794
+ // what a NEW position would carry is not what THIS one does.
45795
+ feeBps: Number(feeBps),
45796
+ feeReceiver
45797
+ }
45798
+ };
45799
+ } catch (error) {
45800
+ if (isLeverageYieldLookupError(error)) return { ok: false, error };
45801
+ return { ok: false, error: lookupFailed("leverageYield", "getPositionInfo", error) };
45802
+ }
45803
+ }
45804
+ /**
45805
+ * Live AAVE account snapshot for a position. Read from the pool, not the position: the
45806
+ * position contract keeps no accounting of its own, so collateral, debt and health factor
45807
+ * all come from `getUserAccountData`.
45808
+ *
45809
+ * The pool comes from `moneyMarket.lendingPool` config rather than the position's own
45810
+ * `pool()` getter — same address, one fewer round trip, and it keeps the deployment address
45811
+ * sourced from config like the rest of the SDK.
45812
+ */
45813
+ async getPositionAccount(position) {
45814
+ try {
45815
+ const [totalCollateralBase, totalDebtBase, availableBorrowsBase, currentLiquidationThreshold, ltv, healthFactor] = await this.hubProvider.publicClient.readContract({
45816
+ address: this.config.sodaxConfig.moneyMarket.lendingPool,
45817
+ abi: poolAbi,
45818
+ functionName: "getUserAccountData",
45819
+ args: [position]
45820
+ });
45821
+ return {
45822
+ ok: true,
45823
+ value: {
45824
+ totalCollateralBase,
45825
+ totalDebtBase,
45826
+ availableBorrowsBase,
45827
+ currentLiquidationThreshold,
45828
+ ltv,
45829
+ healthFactor
45830
+ }
45831
+ };
45832
+ } catch (error) {
45833
+ if (isLeverageYieldLookupError(error)) return { ok: false, error };
45834
+ return { ok: false, error: lookupFailed("leverageYield", "getPositionAccount", error) };
45835
+ }
45836
+ }
45837
+ /**
45838
+ * The position's collateral holding, as an exact aToken balance.
45839
+ *
45840
+ * Needed to size a full exit. {@link LeverageYieldService.getPositionAccount} reports collateral
45841
+ * in the oracle's base currency at 8 decimals, which is fine to display but cannot name an amount:
45842
+ * dividing it back out by a price lands near the balance, and a `decreaseLeverage` asking for more
45843
+ * collateral than the position holds does not fail on submission — the hook's `transferFrom`
45844
+ * reverts at fill time, so the intent silently expires instead.
45845
+ *
45846
+ * Safe to act on a slightly stale read: aToken balances only grow, since interest accrues into
45847
+ * them, so a value from a few blocks ago is always still spendable. Selling it leaves interest
45848
+ * dust behind rather than coming up short.
45849
+ *
45850
+ * @param collateral The position's collateral reserve. Read from the position when omitted; pass
45851
+ * it if you already hold a {@link LeveragePosition} to save the round trip.
45852
+ */
45853
+ async getPositionCollateralBalance(position, collateral) {
45854
+ try {
45855
+ const asset = collateral ?? await this.hubProvider.publicClient.readContract({
45856
+ address: position,
45857
+ abi: leveragePositionAbi,
45858
+ functionName: "collateral"
45859
+ });
45860
+ const reserve = await this.hubProvider.publicClient.readContract({
45861
+ address: this.config.sodaxConfig.moneyMarket.lendingPool,
45862
+ abi: poolAbi,
45863
+ functionName: "getReserveData",
45864
+ args: [asset]
45865
+ });
45866
+ const aToken = reserve.aTokenAddress;
45867
+ const balance = await this.hubProvider.publicClient.readContract({
45868
+ address: aToken,
45869
+ abi: viem.erc20Abi,
45870
+ functionName: "balanceOf",
45871
+ args: [position]
45872
+ });
45873
+ return { ok: true, value: { aToken, balance } };
45874
+ } catch (error) {
45875
+ if (isLeverageYieldLookupError(error)) return { ok: false, error };
45876
+ return { ok: false, error: lookupFailed("leverageYield", "getPositionCollateralBalance", error) };
45877
+ }
45878
+ }
45879
+ /**
45880
+ * The position's operation slot: which operation it recorded, and whether that intent is still
45881
+ * live on `Intents`.
45882
+ *
45883
+ * Both are needed, because the interesting state is when they disagree. `isLive` false with a
45884
+ * non-zero `kind` means the intent resolved — filled, expired, or cancelled by someone else — but
45885
+ * the position has not been told, so its grant is still open and any debt-side contribution is
45886
+ * still sitting there. That is what `needsSettle` flags, and `buildSettlePosition` clears. A live
45887
+ * intent instead blocks any second operation until it resolves.
45888
+ */
45889
+ async getPositionPendingState(position) {
45890
+ try {
45891
+ const [isLive, kind] = await Promise.all([
45892
+ this.hubProvider.publicClient.readContract({
45893
+ address: position,
45894
+ abi: leveragePositionAbi,
45895
+ functionName: "hasPendingOperation"
45896
+ }),
45897
+ this.hubProvider.publicClient.readContract({
45898
+ address: position,
45899
+ abi: leveragePositionAbi,
45900
+ functionName: "pendingKind"
45901
+ })
45902
+ ]);
45903
+ return { ok: true, value: { kind, isLive, needsSettle: kind !== 0 && !isLive } };
45904
+ } catch (error) {
45905
+ if (isLeverageYieldLookupError(error)) return { ok: false, error };
45906
+ return { ok: false, error: lookupFailed("leverageYield", "getPositionPendingState", error) };
45907
+ }
45908
+ }
45909
+ /** Deterministic clone address for the next position a given creator opens for `owner`. */
45910
+ async predictPosition(creator, owner, positionId) {
45911
+ const factory = this.requireFactory("predictPosition");
45912
+ if (!factory.ok) return factory;
45913
+ try {
45914
+ const id = positionId ?? await this.hubProvider.publicClient.readContract({
45915
+ address: factory.value,
45916
+ abi: leveragePositionFactoryAbi,
45917
+ functionName: "nextPositionIdFor",
45918
+ args: [owner]
45919
+ });
45920
+ const value = await this.hubProvider.publicClient.readContract({
45921
+ address: factory.value,
45922
+ abi: leveragePositionFactoryAbi,
45923
+ functionName: "predictPosition",
45924
+ args: [creator, owner, id]
45925
+ });
45926
+ return { ok: true, value };
45927
+ } catch (error) {
45928
+ if (isLeverageYieldLookupError(error)) return { ok: false, error };
45929
+ return { ok: false, error: lookupFailed("leverageYield", "predictPosition", error) };
45930
+ }
45931
+ }
45932
+ // ─── Position transaction builders ─────────────────────────────────────
45933
+ //
45934
+ // Positions are driven by direct Sonic calls, not intents, so these return raw transactions
45935
+ // for the caller to sign with a hub wallet provider. The leverage and deleverage calls only
45936
+ // *post* an intent — a solver fills it afterwards, so poll `getPositionPendingState`
45937
+ // rather than treating the receipt as completion.
45938
+ /**
45939
+ * Opens a new position and requests leverage on it in the same transaction — the standard way
45940
+ * to open a leveraged position: one approve, then this.
45941
+ *
45942
+ * `initialAssets` of `collateral` is pulled from the signer, so the factory needs an allowance
45943
+ * first. Control is assigned to `owner`, which may differ from the signer — pass a user's hub
45944
+ * wallet address to have the existing cross-chain path drive the position.
45945
+ *
45946
+ * The leverage is still asynchronous: this posts the intent and a solver fills it afterwards,
45947
+ * so on confirmation the position is funded with the request outstanding, not yet levered. If
45948
+ * no solver fills it, `buildCancelPositionOperation` returns the deposit to the owner.
45949
+ */
45950
+ /**
45951
+ * Turns a {@link PositionOrigin} into the tuple the factory takes, and refuses the combinations the
45952
+ * contract would refuse anyway — better a rejected build than a transaction that reverts.
45953
+ */
45954
+ resolveOrigin(origin, method) {
45955
+ const chainId = getIntentRelayChainId(origin.chainKey);
45956
+ if (chainId === void 0) {
45957
+ return {
45958
+ ok: false,
45959
+ error: lookupFailed(
45960
+ "leverageYield",
45961
+ method,
45962
+ new Error(`no relay chain id for origin chain ${origin.chainKey}`)
45963
+ )
45964
+ };
45965
+ }
45966
+ const isHub = origin.chainKey === this.hubProvider.chainConfig.chain.key;
45967
+ if (!isHub && !origin.asset) {
45968
+ return {
45969
+ ok: false,
45970
+ error: lookupFailed(
45971
+ "leverageYield",
45972
+ method,
45973
+ new Error(`origin.asset is required for a refund to ${origin.chainKey}`)
45974
+ )
45975
+ };
45976
+ }
45977
+ return {
45978
+ ok: true,
45979
+ value: {
45980
+ chainId,
45981
+ // The chain's own encoding, not a 0x-prefixed string. `originAddress` is `bytes` on-chain and
45982
+ // is handed to the AssetManager as the refund destination, so a Solana or Stellar address has
45983
+ // to arrive in the form that chain's spoke expects — prefixing `0x` would produce a refund
45984
+ // address that is merely well-formed hex. EVM addresses pass through unchanged.
45985
+ address: encodeAddress(origin.chainKey, origin.address),
45986
+ // Named on the hub as well, not just off it. The asset decides what a cancellation pays back,
45987
+ // and zeroing it here is why someone who funded with USSD was refunded `sodaUSSD`. Callers pass
45988
+ // the asset only when a wrap actually happened — when the reserve IS what was deposited there is
45989
+ // nothing to unwrap and `address(0)` is the correct answer.
45990
+ asset: origin.asset ?? viem.zeroAddress
45991
+ }
45992
+ };
45993
+ }
45994
+ /**
45995
+ * Partner fee for a position, in the shape `PositionConfig` takes.
45996
+ *
45997
+ * Only the PERCENTAGE variant of `PartnerFee` maps: the contract stores basis points and derives
45998
+ * the amount per operation (`_feeFor`), so a fixed-amount fee has nowhere to go and is rejected
45999
+ * rather than silently dropped. Same precedence as the vault flows — per-call, then
46000
+ * `leverageYield.partnerFee`, then none.
46001
+ *
46002
+ * The fee is FIXED AT CREATION on-chain, so this is read when a position is created and never
46003
+ * again; changing the config later does not re-price positions already open.
46004
+ */
46005
+ /**
46006
+ * The fee a position created NOW would carry, in basis points, plus who receives it.
46007
+ *
46008
+ * Public because a caller cannot project a position correctly without it and cannot derive it:
46009
+ * the fee resolves from `leverageYield.partnerFee`, then the global fee, then none, and it is
46010
+ * FIXED AT CREATION on-chain. Feed `feeBps` to {@link projectLeverageLeg} — the hooks require
46011
+ * `inputAmount + fee`, so a leverage-up borrows the fee ON TOP of what the solver is paid. Leaving
46012
+ * it out understates LTV and overstates the ceiling, which is the Aave `'36'` failure at fill time
46013
+ * this module exists to prevent: 50 bp takes a debt-side ceiling from 9.88x to about 9.44x.
46014
+ *
46015
+ * Pass the same `override` here as to the open call, or omit it on both.
46016
+ */
46017
+ getEffectivePositionFee(override) {
46018
+ return this.resolvePositionFee(override, "getEffectivePositionFee");
46019
+ }
46020
+ resolvePositionFee(override, method) {
46021
+ const fee = override ?? this.config.leverageYieldPartnerFee;
46022
+ if (!fee) return { ok: true, value: { feeReceiver: viem.zeroAddress, feeBps: 0 } };
46023
+ if (!isPartnerFeePercentage(fee)) {
46024
+ return {
46025
+ ok: false,
46026
+ error: lookupFailed(
46027
+ "leverageYield",
46028
+ method,
46029
+ new Error("a position partner fee must be the percentage variant; PositionConfig stores basis points")
46030
+ )
46031
+ };
46032
+ }
46033
+ if (!Number.isInteger(fee.percentage) || fee.percentage < 0 || fee.percentage > MAX_POSITION_FEE_BPS) {
46034
+ return {
46035
+ ok: false,
46036
+ error: lookupFailed(
46037
+ "leverageYield",
46038
+ method,
46039
+ new Error(
46040
+ `a position partner fee must be a whole number of basis points between 0 and MAX_POSITION_FEE_BPS (${MAX_POSITION_FEE_BPS}) (got ${fee.percentage})`
46041
+ )
46042
+ )
46043
+ };
46044
+ }
46045
+ if (fee.percentage === 0 !== viem.isAddressEqual(fee.address, viem.zeroAddress)) {
46046
+ return {
46047
+ ok: false,
46048
+ error: lookupFailed(
46049
+ "leverageYield",
46050
+ method,
46051
+ new Error(
46052
+ `a position partner fee needs a rate and a receiver together, or neither (got ${fee.percentage} bps for ${fee.address})`
46053
+ )
46054
+ )
46055
+ };
46056
+ }
46057
+ return { ok: true, value: { feeReceiver: fee.address, feeBps: fee.percentage } };
46058
+ }
46059
+ /** A hub transaction. Every builder below produces this shape and none of them sends value. */
46060
+ // Generic so a builder's declared return type applies its own brand. The cast is the single one
46061
+ // the pattern needs — a brand is type-only and erased at runtime — and keeping it here means no
46062
+ // builder carries one of its own.
46063
+ hubTx(from, to, data) {
46064
+ return { from, to, value: 0n, data };
46065
+ }
46066
+ /**
46067
+ * The `PositionConfig` struct both factory entry points take, assembled from a resolved origin.
46068
+ *
46069
+ * Shared so the two create paths cannot drift: which side the funded reserve goes on is their only
46070
+ * real difference, and a field silently spelled differently in one of them would be a
46071
+ * mis-recorded refund destination rather than a compile error.
46072
+ */
46073
+ positionConfig(args) {
46074
+ return {
46075
+ owner: args.owner,
46076
+ collateral: args.collateral,
46077
+ borrowToken: args.borrowToken,
46078
+ eModeCategory: args.eModeCategory,
46079
+ originChainId: args.origin.chainId,
46080
+ originAddress: args.origin.address,
46081
+ originAsset: args.origin.asset,
46082
+ feeReceiver: args.fee?.feeReceiver ?? viem.zeroAddress,
46083
+ feeBps: args.fee?.feeBps ?? 0
46084
+ };
46085
+ }
46086
+ buildCreatePositionAndLeverage(params) {
46087
+ const method = "buildCreatePositionAndLeverage";
46088
+ const factory = this.requireFactory(method);
46089
+ if (!factory.ok) return factory;
46090
+ const fee = this.resolvePositionFee(params.partnerFee, method);
46091
+ if (!fee.ok) return fee;
46092
+ const origin = this.resolveOrigin(params.origin, method);
46093
+ if (!origin.ok) return origin;
46094
+ return {
46095
+ ok: true,
46096
+ value: this.hubTx(
46097
+ params.from,
46098
+ factory.value,
46099
+ viem.encodeFunctionData({
46100
+ abi: leveragePositionFactoryAbi,
46101
+ functionName: "createPositionAndLeverage",
46102
+ args: [
46103
+ this.positionConfig({ ...params, origin: origin.value, fee: fee.value }),
46104
+ params.initialAssets,
46105
+ params.borrowAmount,
46106
+ params.minCollateralOut
46107
+ ]
46108
+ })
46109
+ )
46110
+ };
46111
+ }
46112
+ /**
46113
+ * Opens a levered position starting from the **debt** token, with no collateral of your own.
46114
+ *
46115
+ * Pulls `contribution` of `borrowToken` from the signer — not the collateral. On fill the hook
46116
+ * supplies the solver's collateral, adds the contribution, borrows `totalInput - contribution`,
46117
+ * and pays the solver the total, so a holder of the debt asset lands in a levered collateral
46118
+ * position having never owned collateral. Requires the deployment's implementation to have a
46119
+ * debt-side hook configured; otherwise the position reverts with `DebtSideHookUnavailable`.
46120
+ */
46121
+ buildCreatePositionFromDebtToken(params) {
46122
+ const method = "buildCreatePositionFromDebtToken";
46123
+ const factory = this.requireFactory(method);
46124
+ if (!factory.ok) return factory;
46125
+ const fee = this.resolvePositionFee(params.partnerFee, method);
46126
+ if (!fee.ok) return fee;
46127
+ const origin = this.resolveOrigin(params.origin, method);
46128
+ if (!origin.ok) return origin;
46129
+ return {
46130
+ ok: true,
46131
+ value: this.hubTx(
46132
+ params.from,
46133
+ factory.value,
46134
+ viem.encodeFunctionData({
46135
+ abi: leveragePositionFactoryAbi,
46136
+ functionName: "createPositionFromDebtToken",
46137
+ args: [
46138
+ this.positionConfig({ ...params, origin: origin.value, fee: fee.value }),
46139
+ params.contribution,
46140
+ params.totalInput,
46141
+ params.minCollateralOut
46142
+ ]
46143
+ })
46144
+ )
46145
+ };
46146
+ }
46147
+ /** Borrows `borrowAmount` and swaps it into more collateral. `minCollateralOut` is the slippage floor. */
46148
+ buildAddLeverage(params) {
46149
+ return this.hubTx(
46150
+ params.from,
46151
+ params.position,
46152
+ viem.encodeFunctionData({
46153
+ abi: leveragePositionAbi,
46154
+ functionName: "addLeverage",
46155
+ args: [params.borrowAmount, params.minCollateralOut]
46156
+ })
46157
+ );
46158
+ }
46159
+ /**
46160
+ * Gives up `collateralIn` of collateral to repay debt. `minDebtOut` is the slippage floor.
46161
+ *
46162
+ * CLOSING INTO THE DEBT TOKEN is this call with the position's collateral balance, less the fee a
46163
+ * non-zero `feeBps` gives up on top of the input (`balance x 10_000 / (10_000 + feeBps)`) — there is
46164
+ * no separate close entry point, because selling everything is the same operation as selling part.
46165
+ * Size it with {@link LeverageYieldService.getPositionCollateralBalance}, never off
46166
+ * `totalCollateralBase`, and quote the full amount so `minDebtOut` reflects what the solver will
46167
+ * actually pay for all of it.
46168
+ *
46169
+ * What that leaves behind is worth knowing. The solver delivers more debt token than is owed, so
46170
+ * the hook repays the debt and hands the surplus to the position, which is the owner's equity now
46171
+ * denominated in the debt asset. It sits in the position until someone calls
46172
+ * {@link LeverageYieldService.buildSettlePosition} — that sweep is what actually delivers it, and
46173
+ * it goes to the position's `owner` (the hub wallet), not to whoever signed. Exiting into the
46174
+ * *collateral* instead means repaying only the debt and then calling
46175
+ * {@link LeverageYieldService.buildPositionWithdraw}, which can pay out to any address.
46176
+ */
46177
+ buildDecreaseLeverage(params) {
46178
+ return this.hubTx(
46179
+ params.from,
46180
+ params.position,
46181
+ viem.encodeFunctionData({
46182
+ abi: leveragePositionAbi,
46183
+ functionName: "decreaseLeverage",
46184
+ args: [params.collateralIn, params.minDebtOut, params.exitAsset ?? viem.zeroAddress]
46185
+ })
46186
+ );
46187
+ }
46188
+ /**
46189
+ * Withdraws collateral out of the position. The pool rejects a withdrawal that would drop
46190
+ * the position below its liquidation threshold, so no client-side health check is applied
46191
+ * here — but note that bound is health factor 1, not a safety buffer above it.
46192
+ */
46193
+ buildPositionWithdraw(params) {
46194
+ return this.hubTx(
46195
+ params.from,
46196
+ params.position,
46197
+ viem.encodeFunctionData({
46198
+ abi: leveragePositionAbi,
46199
+ functionName: "withdraw",
46200
+ args: [params.amount, params.to]
46201
+ })
46202
+ );
46203
+ }
46204
+ /**
46205
+ * Clears an operation that has already resolved and returns anything the position is holding
46206
+ * loose to its owner.
46207
+ *
46208
+ * PERMISSIONLESS, and deliberately so: it only ever tightens state, so a stranded balance can be
46209
+ * pushed back by anyone rather than waiting on the owner to notice. That matters because an intent
46210
+ * can be cancelled by a third party once past its deadline, which leaves the position resolved but
46211
+ * un-swept if the hook's notification did not land.
46212
+ *
46213
+ * Reverts while the intent is still live — use {@link LeverageYieldService.buildCancelPositionOperation}
46214
+ * to end one that has not resolved yet.
46215
+ */
46216
+ buildSettlePosition(params) {
46217
+ return this.hubTx(
46218
+ params.from,
46219
+ params.position,
46220
+ viem.encodeFunctionData({ abi: leveragePositionAbi, functionName: "settle" })
46221
+ );
46222
+ }
46223
+ /**
46224
+ * Cancels the in-flight operation and returns the deposit.
46225
+ *
46226
+ * Nothing is escrowed when an intent is posted, so cancelling recovers nothing by itself — but
46227
+ * a position carrying no debt withdraws its whole collateral balance back to the owner, which
46228
+ * is what a leveraged open whose intent never filled needs. With debt outstanding the
46229
+ * collateral stays put: the pool would reject the withdrawal on its health-factor check.
46230
+ */
46231
+ buildCancelPositionOperation(params) {
46232
+ return this.hubTx(
46233
+ params.from,
46234
+ params.position,
46235
+ viem.encodeFunctionData({ abi: leveragePositionAbi, functionName: "cancel" })
46236
+ );
46237
+ }
46238
+ // ─── Positions from any chain ──────────────────────────────────────────
46239
+ //
46240
+ // The builders above produce a transaction sent straight to the hub. That only works for a user
46241
+ // signing on the hub, and even there it has to be routed so `msg.sender` is their hub wallet —
46242
+ // a position's `onlyOwner` is that wallet, and an EOA cannot send as another address.
46243
+ //
46244
+ // These take over from there: the calls are encoded as a hub-wallet payload and carried by the
46245
+ // spoke transport, which routes them locally on the hub and relays them from anywhere else. So one
46246
+ // code path covers every chain, and the hub is not a special case.
46247
+ /**
46248
+ * Encodes position calls as a hub-wallet payload.
46249
+ *
46250
+ * Takes the raw transactions from the builders above and produces the `(address,uint256,bytes)[]`
46251
+ * payload the hub wallet executes. Public because that payload is the unit the transport takes:
46252
+ * pass it to `spoke.deposit` / `spoke.sendMessage` yourself when you want manual relay control,
46253
+ * or use {@link LeverageYieldService.openPosition} / {@link LeverageYieldService.operatePosition},
46254
+ * which do it for you.
46255
+ */
46256
+ encodePositionCalls(txs) {
46257
+ return encodeContractCalls(
46258
+ txs.map((tx) => ({ address: tx.to, value: tx.value ?? 0n, data: tx.data }))
46259
+ );
46260
+ }
46261
+ /**
46262
+ * Resolves the hub reserve a spoke token funds, and the hub asset it arrives as.
46263
+ *
46264
+ * Three addresses per token and they are not interchangeable: `hubAsset` is what lands in the hub
46265
+ * wallet, `vault` is the 18-decimal money-market reserve a position actually uses, and the spoke
46266
+ * `address` is neither. Getting this wrong is silent — the wrong one is still a valid ERC-20.
46267
+ */
46268
+ resolveFunding(srcChainKey, token, method) {
46269
+ const spokeToken = this.config.getSpokeTokenFromOriginalAssetAddress(srcChainKey, token) ?? this.config.getXTokenFromHubAsset(token);
46270
+ if (!spokeToken) {
46271
+ return {
46272
+ ok: false,
46273
+ error: lookupFailed(
46274
+ "leverageYield",
46275
+ method,
46276
+ new Error(`no hub asset registered for ${token} on ${srcChainKey}`),
46277
+ { srcChainKey }
46278
+ )
46279
+ };
46280
+ }
46281
+ return {
46282
+ ok: true,
46283
+ value: {
46284
+ hubAsset: spokeToken.hubAsset,
46285
+ vault: spokeToken.vault,
46286
+ decimals: spokeToken.decimals
46287
+ }
46288
+ };
46289
+ }
46290
+ /**
46291
+ * What a refund should pay back: the asset the user actually funded with, or `undefined` when that IS
46292
+ * the reserve and there is nothing to unwrap.
46293
+ *
46294
+ * A named asset makes `IntentRefund` unwrap before paying, on the hub as well as off it — so someone
46295
+ * who deposited USSD is refunded USSD rather than `sodaUSSD`.
46296
+ */
46297
+ refundAsset(funding) {
46298
+ return funding.hubAsset.toLowerCase() === funding.vault.toLowerCase() ? void 0 : funding.hubAsset;
46299
+ }
46300
+ /**
46301
+ * Encodes the wrap of an arriving deposit into its money-market reserve, and returns the reserve
46302
+ * amount that produces.
46303
+ *
46304
+ * A hub asset that is already a soda vault token IS the reserve, so nothing is wrapped. Otherwise
46305
+ * the vault mints 18-decimal shares one-for-one with the asset, which is what
46306
+ * `translateIncomingDecimals` computes — the same conversion the asset manager applies to a spoke
46307
+ * deposit, rather than a second implementation of it. A reserve carrying a non-zero deposit fee
46308
+ * would mint fewer shares than this predicts and the factory's pull would revert; both reserves in
46309
+ * use today are fee-free.
46310
+ */
46311
+ encodeWrapIntoReserve(funding, amount) {
46312
+ if (this.config.isSodaVaultHubAsset(funding.hubAsset)) {
46313
+ return { calls: [], reserveAmount: amount };
46314
+ }
46315
+ return {
46316
+ calls: [
46317
+ Erc20Service.encodeApprove(funding.hubAsset, funding.vault, amount),
46318
+ EvmVaultTokenService.encodeDeposit(funding.vault, funding.hubAsset, amount)
46319
+ ],
46320
+ reserveAmount: EvmVaultTokenService.translateIncomingDecimals(funding.decimals, amount)
46321
+ };
46322
+ }
46323
+ /**
46324
+ * Everything both opens do before they diverge: resolve the factory, the funding token's hub asset
46325
+ * and reserve, and the origin to refund to; predict the address the position will be created at;
46326
+ * and encode the wrap plus the transfer that funds it.
46327
+ *
46328
+ * Only the factory call itself differs between the collateral side and the debt side — which side
46329
+ * the funded reserve lands on, and the two amounts — so everything up to that point lives here
46330
+ * once. `calls` is returned ready to be appended to.
46331
+ */
46332
+ async prepareOpen(params, method) {
46333
+ const factory = this.requireFactory(method);
46334
+ if (!factory.ok) return factory;
46335
+ const fee = this.resolvePositionFee(params.partnerFee, method);
46336
+ if (!fee.ok) return fee;
46337
+ const funding = this.resolveFunding(params.srcChainKey, params.token, method);
46338
+ if (!funding.ok) return funding;
46339
+ const origin = this.resolveOrigin(
46340
+ { chainKey: params.srcChainKey, address: params.srcAddress, asset: this.refundAsset(funding.value) },
46341
+ method
46342
+ );
46343
+ if (!origin.ok) return origin;
46344
+ const predicted = await this.predictPosition(params.owner, params.owner);
46345
+ if (!predicted.ok) return predicted;
46346
+ const { calls, reserveAmount } = this.encodeWrapIntoReserve(funding.value, params.amount);
46347
+ calls.push(Erc20Service.encodeTransfer(funding.value.vault, predicted.value, reserveAmount));
46348
+ return {
46349
+ ok: true,
46350
+ value: {
46351
+ factory: factory.value,
46352
+ funding: funding.value,
46353
+ calls,
46354
+ reserveAmount,
46355
+ origin: origin.value,
46356
+ fee: fee.value
46357
+ }
46358
+ };
46359
+ }
46360
+ /**
46361
+ * Hub-side payload for opening a position from the collateral side.
46362
+ *
46363
+ * Wrap the arriving deposit into its reserve, TRANSFER it to the address the position will be
46364
+ * created at, create the position and post its leverage intent — one batch, executed by the user's
46365
+ * hub wallet. The position's collateral is the reserve behind `params.token`; `borrowToken` is
46366
+ * borrowed against it.
46367
+ *
46368
+ * Nothing is ever approved to the factory: it holds no allowance and pulls from nobody, so funding
46369
+ * is a transfer to `predictPosition(creator, owner, nextPositionIdFor(owner))` and the clone supplies
46370
+ * whatever it finds. The id is per-owner, so an unrelated user creating a position cannot move the
46371
+ * address out from under this batch — and because the transfer and the create are in the same batch,
46372
+ * a stale prediction reverts both rather than stranding the tokens.
46373
+ *
46374
+ * The owner's OWN concurrent opens are the one thing that can still advance the id between building
46375
+ * this payload and executing it. On the hub that reverts atomically and nothing is lost; funded from
46376
+ * a spoke the deposit has already landed in the user's hub wallet when the batch reverts, and is
46377
+ * recovered with `sodax.recovery` (see RECOVERY.md). Do not open two positions for one owner at once.
46378
+ *
46379
+ * The origin recorded on the position is `srcChainKey` / `srcAddress` / the deposited hub asset,
46380
+ * so a leverage intent that never fills refunds to the user on the chain they funded from — not to
46381
+ * the position, and not to the hub wallet.
46382
+ */
46383
+ async buildOpenPositionData(params) {
46384
+ const prep = await this.prepareOpen(params, "buildOpenPositionData");
46385
+ if (!prep.ok) return prep;
46386
+ const { factory, funding, calls, reserveAmount, origin, fee } = prep.value;
46387
+ calls.push({
46388
+ address: factory,
46389
+ value: 0n,
46390
+ data: viem.encodeFunctionData({
46391
+ abi: leveragePositionFactoryAbi,
46392
+ functionName: "createPositionAndLeverage",
46393
+ args: [
46394
+ this.positionConfig({
46395
+ owner: params.owner,
46396
+ collateral: funding.vault,
46397
+ borrowToken: params.borrowToken,
46398
+ eModeCategory: params.eModeCategory ?? 0,
46399
+ origin,
46400
+ fee
46401
+ }),
46402
+ reserveAmount,
46403
+ params.borrowAmount,
46404
+ params.minCollateralOut
46405
+ ]
46406
+ })
46407
+ });
46408
+ return { ok: true, value: encodeContractCalls(calls) };
46409
+ }
46410
+ /**
46411
+ * Hub-side payload for opening a position from the debt side.
46412
+ *
46413
+ * The mirror of {@link LeverageYieldService.buildOpenPositionData}: here the deposit is the
46414
+ * position's *debt* token, contributed rather than supplied, and `collateral` is the reserve the
46415
+ * position ends up long. The hook supplies the solver's collateral on fill and borrows only the
46416
+ * shortfall, so the position legitimately starts with no collateral of its own.
46417
+ */
46418
+ async buildOpenPositionFromDebtTokenData(params) {
46419
+ const prep = await this.prepareOpen(params, "buildOpenPositionFromDebtTokenData");
46420
+ if (!prep.ok) return prep;
46421
+ const { factory, funding, calls, reserveAmount, origin, fee } = prep.value;
46422
+ calls.push({
46423
+ address: factory,
46424
+ value: 0n,
46425
+ data: viem.encodeFunctionData({
46426
+ abi: leveragePositionFactoryAbi,
46427
+ functionName: "createPositionFromDebtToken",
46428
+ args: [
46429
+ this.positionConfig({
46430
+ owner: params.owner,
46431
+ collateral: params.collateral,
46432
+ // The deposited token IS the debt side, so its reserve is the borrow token.
46433
+ borrowToken: funding.vault,
46434
+ eModeCategory: params.eModeCategory ?? 0,
46435
+ origin,
46436
+ fee
46437
+ }),
46438
+ reserveAmount,
46439
+ params.totalInput,
46440
+ params.minCollateralOut
46441
+ ]
46442
+ })
46443
+ });
46444
+ return { ok: true, value: encodeContractCalls(calls) };
46445
+ }
46446
+ /**
46447
+ * Whether the funding token is already approved for an open from `srcChainKey`.
46448
+ *
46449
+ * The spender differs by chain and neither choice is guessable: on the hub the deposit is pulled
46450
+ * by the user's own hub wallet, executing inside the routed batch; on an EVM spoke it is pulled by
46451
+ * that spoke's asset manager. Chains with no allowance concept report `true`, and Stellar reports
46452
+ * whether the trustline covers the amount.
46453
+ */
46454
+ async isPositionFundingAllowanceValid(params) {
46455
+ const baseCtx = { srcChainKey: params.srcChainKey, action: "allowanceCheck" };
46456
+ try {
46457
+ leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
46458
+ const srcChainKey = params.srcChainKey;
46459
+ const inner = isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey) ? await this.spoke.isAllowanceValid({
46460
+ srcChainKey,
46461
+ token: params.token,
46462
+ amount: params.amount,
46463
+ owner: params.srcAddress,
46464
+ spender: await this.resolveFundingSpender(srcChainKey, params.srcAddress)
46465
+ }) : await this.spoke.isAllowanceValid({
46466
+ srcChainKey,
46467
+ token: params.token,
46468
+ amount: params.amount,
46469
+ owner: params.srcAddress
46470
+ });
46471
+ if (inner.ok) return inner;
46472
+ return { ok: false, error: allowanceCheckFailed("leverageYield", inner.error, baseCtx) };
46473
+ } catch (error) {
46474
+ if (isLeverageYieldAllowanceCheckError(error)) return { ok: false, error };
46475
+ return { ok: false, error: allowanceCheckFailed("leverageYield", error, baseCtx) };
46476
+ }
46477
+ }
46478
+ /**
46479
+ * Approves the funding token for an open, against the spender that chain's deposit actually uses —
46480
+ * see {@link LeverageYieldService.isPositionFundingAllowanceValid} for which that is.
46481
+ *
46482
+ * WAITS FOR THE APPROVAL TO LAND before returning. `Erc20Service.approve` resolves with the hash the
46483
+ * moment it is broadcast, so a caller that immediately re-reads the allowance sees the value from
46484
+ * BEFORE the approval — a UI then keeps showing "approve" and the user signs a second, pointless
46485
+ * approval. Returning early from a helper whose whole purpose is "the allowance is now sufficient" is
46486
+ * a footgun, so the wait lives here rather than in each caller.
46487
+ */
46488
+ async approvePositionFunding(params) {
46489
+ const baseCtx = { srcChainKey: params.srcChainKey, action: "approve" };
46490
+ try {
46491
+ leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
46492
+ const srcChainKey = params.srcChainKey;
46493
+ let inner = {
46494
+ ok: false,
46495
+ error: new Error(`[LeverageYieldService.approvePositionFunding] approve is unsupported on ${srcChainKey}`)
46496
+ };
46497
+ if (isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey)) {
46498
+ leverageYieldInvariant(viem.isAddress(params.token), "Invalid token address", { ...baseCtx, field: "token" });
46499
+ inner = await this.spoke.approve({
46500
+ srcChainKey,
46501
+ token: params.token,
46502
+ amount: params.amount,
46503
+ owner: params.srcAddress,
46504
+ spender: await this.resolveFundingSpender(srcChainKey, params.srcAddress),
46505
+ raw: false,
46506
+ // `K` stays open here, so the provider is only checkable against the chain key inside `spoke.approve`.
46507
+ walletProvider: params.walletProvider
46508
+ });
46509
+ } else if (isStellarChainKeyType(srcChainKey)) {
46510
+ inner = await this.spoke.approve({
46511
+ srcChainKey,
46512
+ token: params.token,
46513
+ amount: params.amount,
46514
+ owner: params.srcAddress,
46515
+ raw: false,
46516
+ walletProvider: params.walletProvider
46517
+ });
46518
+ }
46519
+ if (!inner.ok) return { ok: false, error: approveFailed("leverageYield", inner.error, baseCtx) };
46520
+ if (params.walletProvider && isEvmWalletProviderType(params.walletProvider)) {
46521
+ const receipt = await params.walletProvider.waitForTransactionReceipt(
46522
+ inner.value
46523
+ );
46524
+ if (receipt.status !== "success") {
46525
+ return { ok: false, error: approveFailed("leverageYield", "transaction reverted", baseCtx) };
46526
+ }
46527
+ } else {
46528
+ const landed = await this.spoke.verifyTxHash({ txHash: inner.value, chainKey: params.srcChainKey });
46529
+ if (!landed.ok) return { ok: false, error: approveFailed("leverageYield", landed.error, baseCtx) };
46530
+ }
46531
+ return inner;
46532
+ } catch (error) {
46533
+ if (isLeverageYieldApproveError(error)) return { ok: false, error };
46534
+ return { ok: false, error: approveFailed("leverageYield", error, baseCtx) };
46535
+ }
46536
+ }
46537
+ /**
46538
+ * Who pulls the deposit on an EVM source chain.
46539
+ *
46540
+ * On the hub the pull happens inside the routed batch, so the spender is the user's own hub wallet
46541
+ * rather than any protocol contract; on an EVM spoke it is that spoke's asset manager. Chains with
46542
+ * no ERC-20 allowance never reach here.
46543
+ */
46544
+ async resolveFundingSpender(srcChainKey, srcAddress) {
46545
+ if (isHubChainKeyType(srcChainKey)) return await this.hubProvider.getUserHubWalletAddress(srcAddress, srcChainKey);
46546
+ return this.config.getChainConfig(srcChainKey).addresses.assetManager;
46547
+ }
46548
+ /**
46549
+ * Opens a leveraged position, funded from any chain, in one signature.
46550
+ *
46551
+ * The deposit is carried to the user's hub wallet and the position is created from inside that
46552
+ * same batch, so there is no window in which the funds sit on the hub unattached to a position.
46553
+ * On the hub this routes locally; from a spoke it relays and this waits for the hub side to land.
46554
+ *
46555
+ * WHAT IS AND IS NOT DONE WHEN THIS RESOLVES: the position exists and its leverage intent is
46556
+ * posted. The leverage itself is not applied — a solver fills that intent afterwards. And an
46557
+ * intent is invisible to the solver until its hub transaction hash is reported, so pass the
46558
+ * returned `dstChainTxHash` to {@link LeverageYieldService.notifySolver}; an unreported intent
46559
+ * simply expires and the deposit comes back.
46560
+ *
46561
+ * Spoke tokens need the spoke asset manager approved first, the same as any other deposit.
46562
+ *
46563
+ * @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
46564
+ * end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
46565
+ * replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
46566
+ * delivering the underlying back to the spoke it came from — has never run on mainnet.
46567
+ * Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
46568
+ * outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
46569
+ */
46570
+ async openPosition(_params) {
46571
+ return this.runPositionOpen(
46572
+ _params,
46573
+ "openPosition",
46574
+ (owner, params) => this.buildOpenPositionData({ ...params, owner })
46575
+ );
46576
+ }
46577
+ /**
46578
+ * Opens a leveraged position from the **debt** token, funded from any chain.
46579
+ *
46580
+ * Same transport and the same asynchronous settlement as
46581
+ * {@link LeverageYieldService.openPosition} — see there for what is and is not done when this
46582
+ * resolves. The difference is only which side the user funds: here they hand over debt token and
46583
+ * end up long collateral they never held.
46584
+ *
46585
+ * Requires the deployed implementation to have a debt-side hook configured; without one the
46586
+ * position reverts `DebtSideHookUnavailable`.
46587
+ *
46588
+ * @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
46589
+ * end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
46590
+ * replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
46591
+ * delivering the underlying back to the spoke it came from — has never run on mainnet.
46592
+ * Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
46593
+ * outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
46594
+ */
46595
+ async openPositionFromDebtToken(_params) {
46596
+ return this.runPositionOpen(
46597
+ _params,
46598
+ "openPositionFromDebtToken",
46599
+ (owner, params) => this.buildOpenPositionFromDebtTokenData({ ...params, owner })
46600
+ );
46601
+ }
46602
+ /**
46603
+ * Shared body of the two open paths. They differ only in which factory call the payload ends with,
46604
+ * so everything around it — owner resolution, deposit, verify, relay — lives here rather than
46605
+ * being written twice and drifting.
46606
+ */
46607
+ /**
46608
+ * Instrumentation for both opens. Wrapping the shared runner rather than each entry point keeps
46609
+ * `openPosition` and `openPositionFromDebtToken` from drifting, and `action` is already threaded
46610
+ * through for the error context, so it doubles as the analytics action.
46611
+ *
46612
+ * `start` carries only the fields common to both param shapes — the funding side's token and
46613
+ * amount. The side-specific ones (`borrowToken`/`borrowAmount` vs `collateral`/`totalInput`) are
46614
+ * not on `PositionFundingParams`, and inventing a cast to reach them would be worse than omitting
46615
+ * them.
46616
+ */
46617
+ async runPositionOpen(_params, action, build) {
46618
+ return this.config.analytics.trackResult(
46619
+ "leverageYield",
46620
+ action,
46621
+ () => this.executePositionOpen(_params, action, build),
46622
+ {
46623
+ start: () => ({
46624
+ srcChainKey: _params.params.srcChainKey,
46625
+ srcAddress: _params.params.srcAddress,
46626
+ inputToken: _params.params.token,
46627
+ inputAmount: _params.params.amount,
46628
+ eModeCategory: _params.params.eModeCategory
46629
+ }),
46630
+ success: (value) => ({ srcTxHash: value.srcChainTxHash, dstTxHash: value.dstChainTxHash }),
46631
+ failure: (error) => ({ code: error.code })
46632
+ }
46633
+ );
46634
+ }
46635
+ async executePositionOpen(_params, action, buildData) {
46636
+ const { params, timeout = DEFAULT_RELAY_TX_TIMEOUT } = _params;
46637
+ const baseCtx = {
46638
+ srcChainKey: params.srcChainKey,
46639
+ action
46640
+ };
46641
+ try {
46642
+ leverageYieldInvariant(!isBitcoinChainKeyType(params.srcChainKey), BITCOIN_UNSUPPORTED_MESSAGE, {
46643
+ ...baseCtx,
46644
+ field: "srcChainKey"
46645
+ });
46646
+ leverageYieldInvariant(params.amount > 0n, "amount must be greater than 0", { ...baseCtx, field: "amount" });
46647
+ leverageYieldInvariant(params.minCollateralOut > 0n, "minCollateralOut must be greater than 0", {
46648
+ ...baseCtx,
46649
+ field: "minCollateralOut"
46650
+ });
46651
+ leverageYieldInvariant(
46652
+ isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
46653
+ `Invalid wallet provider for chain key: ${params.srcChainKey}`,
46654
+ { ...baseCtx, field: "walletProvider" }
46655
+ );
46656
+ const hubWallet = await this.hubProvider.getUserHubWalletAddress(params.srcAddress, params.srcChainKey);
46657
+ const data = await buildData(hubWallet, params);
46658
+ if (!data.ok) return data;
46659
+ const txResult = await this.spoke.deposit({
46660
+ srcChainKey: params.srcChainKey,
46661
+ srcAddress: params.srcAddress,
46662
+ to: hubWallet,
46663
+ token: params.token,
46664
+ amount: params.amount,
46665
+ data: data.value,
46666
+ skipSimulation: _params.skipSimulation ?? false,
46667
+ raw: false,
46668
+ walletProvider: _params.walletProvider
46669
+ });
46670
+ if (!txResult.ok) {
46671
+ if (isLeverageYieldCreateIntentError(txResult.error)) return { ok: false, error: txResult.error };
46672
+ return { ok: false, error: intentCreationFailed("leverageYield", txResult.error, baseCtx) };
46673
+ }
46674
+ return await this.settleHubWalletMessage(txResult.value, { address: hubWallet, payload: data.value }, baseCtx, {
46675
+ timeout
46676
+ });
46677
+ } catch (error) {
46678
+ if (isLeverageYieldSwapError(error)) return { ok: false, error };
46679
+ return { ok: false, error: executionFailed("leverageYield", error, { ...baseCtx, phase: "intentCreation" }) };
46680
+ }
46681
+ }
46682
+ /**
46683
+ * Which address actually funds a position from `chainKey` — what a balance must be read against,
46684
+ * and what the deposit is built from.
46685
+ *
46686
+ * ONE ANSWER FOR BOTH, because two answers cost an open on mainnet: the balance was read from the
46687
+ * registry `address` while the deposit rewrote it to `hubAsset`, so for Sonic's native S the form
46688
+ * showed 42 S and the batch then called `wS.transferFrom(user, hubWallet, 5e18)` against a wS
46689
+ * balance of zero. The approval was correct; the revert surfaced as nothing but "External call
46690
+ * failed". Any integrator reading a balance for a position deposit needs this same answer.
46691
+ *
46692
+ * Three addresses hang off a registry entry and they are not interchangeable:
46693
+ *
46694
+ * `address` the spoke-side original; for a bridged entry it can name another chain entirely
46695
+ * `hubAsset` what the user holds ON THE HUB, and the vault's deposit input
46696
+ * `vault` the hub money-market reserve the position ends up in
46697
+ *
46698
+ * Off the hub the answer is always `address` — that is the chain the user is on. On the hub it is
46699
+ * `hubAsset`, EXCEPT for a native entry: `EvmSpokeService.deposit` keys on the chain's own
46700
+ * `nativeToken` to send `msg.value` rather than an ERC-20 `transferFrom`, and the native entry
46701
+ * carries exactly that sentinel as its `address`. Rewriting that to the wrapper asks for a token
46702
+ * the wallet does not hold.
46703
+ *
46704
+ * @returns The funding address, or `undefined` when the token is not supported on `chainKey`.
46705
+ */
46706
+ resolvePositionFunding(chainKey, token) {
46707
+ const address = resolvePositionFundingAddress(chainKey, this.hubProvider.chainConfig.chain.key, token);
46708
+ return address === "" ? void 0 : address;
46709
+ }
46710
+ /**
46711
+ * Quotes one leg of a position operation: the borrowed side when levering up, the collateral when
46712
+ * levering down or exiting.
46713
+ *
46714
+ * Use this rather than {@link LeverageYieldService.getQuote} for a position. Both hit the same
46715
+ * endpoint, but this one names the hub reserves as the pair the intent actually swaps and quotes
46716
+ * GROSS — see `positionLegQuote.ts` for why either alone gets the floor wrong. Feed `quotedAmount`
46717
+ * to {@link projectLeverageLeg}.
46718
+ *
46719
+ * A refusal is not always a dead pair: {@link isNoRouteRefusal} is also what the solver answers
46720
+ * for a leg that is only too small, and telling the two apart means quoting again at a healthy
46721
+ * notional. That size is priced, so it is the caller's to choose.
46722
+ */
46723
+ async getPositionLegQuote(params) {
46724
+ const hubChainKey = this.hubProvider.chainConfig.chain.key;
46725
+ const quote = await this.getQuote({
46726
+ token_src: params.inputHubToken,
46727
+ token_src_blockchain_id: hubChainKey,
46728
+ token_dst: params.outputHubToken,
46729
+ token_dst_blockchain_id: hubChainKey,
46730
+ amount: params.amount,
46731
+ quote_type: "exact_input",
46732
+ // Explicit, not omitted: omitting it applies the configured leverage-yield fee.
46733
+ partnerFee: { address: viem.zeroAddress, percentage: 0 }
46734
+ });
46735
+ if (!quote.ok) return quote;
46736
+ return { ok: true, value: { quotedAmount: quote.value.quoted_amount } };
46737
+ }
46738
+ /**
46739
+ * Opens a leveraged position AND reports the intent it posts. Prefer this to
46740
+ * {@link LeverageYieldService.openPosition} / {@link LeverageYieldService.openPositionFromDebtToken}.
46741
+ *
46742
+ * Those two only post the intent. Reporting it is a separate call that must not be skipped — an
46743
+ * unreported intent expires unfilled, so the owner is left funded with leverage that never arrives
46744
+ * and nothing said so. Pairing them here is the difference between an API that works and one that
46745
+ * works only if you read the docs.
46746
+ *
46747
+ * `side` picks which asset funds the open: `'collateral'` supplies the deposit and borrows against
46748
+ * it, `'debt'` hands the deposit to the solver and ends up long collateral never held.
46749
+ *
46750
+ * RESOLVING MEANS THE INTENT IS LIVE, not that the position is open, and a failed notification is
46751
+ * still `ok: true` — see {@link LeveragePositionIntentResult}.
46752
+ *
46753
+ * @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN — see `operatePosition`.
46754
+ */
46755
+ async openLeveragePosition(_params) {
46756
+ return this.config.analytics.trackResult(
46757
+ "leverageYield",
46758
+ "openLeveragePosition",
46759
+ async () => {
46760
+ const { side, ...rest } = _params;
46761
+ const opened = side === "debt" ? await this.openPositionFromDebtToken(
46762
+ rest
46763
+ ) : await this.openPosition(rest);
46764
+ if (!opened.ok) return opened;
46765
+ return { ok: true, value: await reportPositionIntent(this.notifyIntent, opened.value) };
46766
+ },
46767
+ {
46768
+ start: () => ({ srcChainKey: _params.params.srcChainKey, side: _params.side ?? "collateral" }),
46769
+ success: (result) => ({ ...result.txHashes, notified: result.notified }),
46770
+ failure: (error) => ({ code: error.code })
46771
+ }
46772
+ );
46773
+ }
46774
+ /**
46775
+ * Runs position calls that POST A SOLVER INTENT — `addLeverage` and `decreaseLeverage` — and
46776
+ * reports it. Prefer this to {@link LeverageYieldService.operatePosition} for those two.
46777
+ *
46778
+ * USE {@link LeverageYieldService.runLeveragePositionOperation} FOR `withdraw`, `settle` AND
46779
+ * `cancel`. Those are synchronous on the hub and need no notification, and the split is not
46780
+ * cosmetic: sending a leverage change through the route-only path leaves an intent nothing will
46781
+ * fill, and it expires without a word. The other direction is merely noisy.
46782
+ *
46783
+ * @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN — see `operatePosition`.
46784
+ */
46785
+ async submitLeveragePositionIntent(_params) {
46786
+ return this.config.analytics.trackResult(
46787
+ "leverageYield",
46788
+ "submitLeveragePositionIntent",
46789
+ async () => {
46790
+ const routed = await this.operatePosition(_params);
46791
+ if (!routed.ok) return routed;
46792
+ return { ok: true, value: await reportPositionIntent(this.notifyIntent, routed.value) };
46793
+ },
46794
+ {
46795
+ start: () => ({ srcChainKey: _params.params.srcChainKey, calls: _params.params.calls.length }),
46796
+ success: (result) => ({ ...result.txHashes, notified: result.notified }),
46797
+ failure: (error) => ({ code: error.code })
46798
+ }
46799
+ );
46800
+ }
46801
+ /**
46802
+ * Runs position calls that do NOT post an intent — `withdraw`, `settle` and `cancel` — as the
46803
+ * owning hub wallet. They are synchronous on the hub, so resolving means the work is done.
46804
+ *
46805
+ * Still routed, never sent directly: the position's `onlyOwner` is the hub wallet, so a builder's
46806
+ * transaction sent from the signer reverts `NotOwner`. Use
46807
+ * {@link LeverageYieldService.submitLeveragePositionIntent} for `addLeverage` and
46808
+ * `decreaseLeverage`, which this deliberately does not report.
46809
+ *
46810
+ * @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN, and this path carries the worst of
46811
+ * it: an exit or cancellation delivering the underlying back to the spoke it came from
46812
+ * has never run on mainnet.
46813
+ */
46814
+ async runLeveragePositionOperation(_params) {
46815
+ return this.operatePosition(_params);
46816
+ }
46817
+ /** Bound once so the notify half can be handed around without losing `this`. */
46818
+ notifyIntent = (request) => this.notifySolver(request);
46819
+ /**
46820
+ * Runs position calls as the user's hub wallet, from any chain.
46821
+ *
46822
+ * The write counterpart to the read hooks: add or decrease leverage, withdraw, settle, cancel. No
46823
+ * funds move, so this is a bare message rather than a deposit — on the hub it routes locally, from
46824
+ * a spoke it relays and this waits for the hub side to land.
46825
+ *
46826
+ * The leverage calls only *post* an intent, so a resolved promise means the intent is live, not
46827
+ * that leverage moved. Report the returned `dstChainTxHash` to
46828
+ * {@link LeverageYieldService.notifySolver} for those two; `withdraw`, `settle` and `cancel` are
46829
+ * synchronous on the hub and need no notification.
46830
+ *
46831
+ * @experimental OFF-HUB (SPOKE) ORIGINS ARE UNVERIFIED ON-CHAIN. Every path here has been exercised
46832
+ * end to end on Sonic, the hub. From a spoke the inbound half is proven only by a fork
46833
+ * replay of a real relayed message, and the OUTBOUND half — an exit or a cancellation
46834
+ * delivering the underlying back to the spoke it came from — has never run on mainnet.
46835
+ * Treat a non-hub `srcChainKey` as experimental until it has. Bitcoin is refused
46836
+ * outright — see {@link BITCOIN_UNSUPPORTED_MESSAGE}.
46837
+ */
46838
+ async operatePosition(_params) {
46839
+ return this.config.analytics.trackResult(
46840
+ "leverageYield",
46841
+ "operatePosition",
46842
+ () => this.executePositionOperation(_params),
46843
+ {
46844
+ // The calls themselves are not emitted — they are arbitrary hub calldata. The count is
46845
+ // enough to tell a batched adjust from a single write.
46846
+ start: () => ({
46847
+ srcChainKey: _params.params.srcChainKey,
46848
+ srcAddress: _params.params.srcAddress,
46849
+ callCount: _params.params.calls.length
46850
+ }),
46851
+ success: (value) => ({ srcTxHash: value.srcChainTxHash, dstTxHash: value.dstChainTxHash }),
46852
+ failure: (error) => ({ code: error.code })
46853
+ }
46854
+ );
46855
+ }
46856
+ async executePositionOperation(_params) {
46857
+ const { params, timeout = DEFAULT_RELAY_TX_TIMEOUT } = _params;
46858
+ const baseCtx = {
46859
+ srcChainKey: params.srcChainKey,
46860
+ action: "operatePosition"
46861
+ };
46862
+ try {
46863
+ leverageYieldInvariant(!isBitcoinChainKeyType(params.srcChainKey), BITCOIN_UNSUPPORTED_MESSAGE, {
46864
+ ...baseCtx,
46865
+ field: "srcChainKey"
46866
+ });
46867
+ leverageYieldInvariant(params.calls.length > 0, "at least one call is required", {
46868
+ ...baseCtx,
46869
+ field: "calls"
46870
+ });
46871
+ leverageYieldInvariant(
46872
+ isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
46873
+ `Invalid wallet provider for chain key: ${params.srcChainKey}`,
46874
+ { ...baseCtx, field: "walletProvider" }
46875
+ );
46876
+ const hubWallet = await this.hubProvider.getUserHubWalletAddress(params.srcAddress, params.srcChainKey);
46877
+ const payload = this.encodePositionCalls(params.calls);
46878
+ const txResult = await this.spoke.sendMessage({
46879
+ srcChainKey: params.srcChainKey,
46880
+ srcAddress: params.srcAddress,
46881
+ dstChainKey: HUB_CHAIN_KEY,
46882
+ dstAddress: hubWallet,
46883
+ payload,
46884
+ skipSimulation: _params.skipSimulation ?? false,
46885
+ raw: false,
46886
+ walletProvider: _params.walletProvider
46887
+ });
46888
+ if (!txResult.ok) {
46889
+ if (isLeverageYieldCreateIntentError(txResult.error)) return { ok: false, error: txResult.error };
46890
+ return { ok: false, error: intentCreationFailed("leverageYield", txResult.error, baseCtx) };
46891
+ }
46892
+ return await this.settleHubWalletMessage(txResult.value, { address: hubWallet, payload }, baseCtx, { timeout });
46893
+ } catch (error) {
46894
+ if (isLeverageYieldSwapError(error)) return { ok: false, error };
46895
+ return { ok: false, error: executionFailed("leverageYield", error, { ...baseCtx, phase: "intentCreation" }) };
46896
+ }
46897
+ }
46898
+ /**
46899
+ * Verifies a submitted source transaction and, off the hub, relays it and waits for the hub side.
46900
+ *
46901
+ * Shared by both write paths because the tail is identical whether funds moved or not. The hub
46902
+ * short-circuit is not an optimisation: a hub transaction has already executed the calls, so there
46903
+ * is nothing to relay, and both hashes are the same transaction.
46904
+ */
46905
+ async settleHubWalletMessage(srcTxHash, relayData, baseCtx, opts) {
46906
+ const verify = await this.spoke.verifyTxHash({ txHash: srcTxHash, chainKey: baseCtx.srcChainKey });
46907
+ if (!verify.ok) return { ok: false, error: verifyFailed("leverageYield", verify.error, baseCtx) };
46908
+ if (isHubChainKeyType(baseCtx.srcChainKey)) {
46909
+ const receipt = await this.hubProvider.publicClient.waitForTransactionReceipt({
46910
+ hash: srcTxHash,
46911
+ timeout: opts.timeout
46912
+ });
46913
+ if (receipt.status !== "success") {
46914
+ return {
46915
+ ok: false,
46916
+ error: verifyFailed("leverageYield", new Error(`hub transaction ${srcTxHash} reverted`), baseCtx)
46917
+ };
46918
+ }
46919
+ return { ok: true, value: { srcChainTxHash: srcTxHash, dstChainTxHash: srcTxHash } };
46920
+ }
46921
+ const packet = await relayTxAndWaitPacket({
46922
+ srcTxHash,
46923
+ data: relayData,
46924
+ chainKey: baseCtx.srcChainKey,
46925
+ relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
46926
+ timeout: opts.timeout
46927
+ });
46928
+ if (!packet.ok) {
46929
+ return {
46930
+ ok: false,
46931
+ error: mapRelayFailure(packet.error, {
46932
+ feature: "leverageYield",
46933
+ action: baseCtx.action,
46934
+ srcChainKey: baseCtx.srcChainKey
46935
+ })
46936
+ };
46937
+ }
46938
+ return { ok: true, value: { srcChainTxHash: srcTxHash, dstChainTxHash: packet.value.dst_tx_hash } };
46939
+ }
44884
46940
  };
44885
46941
 
44886
46942
  // src/sponsoring/errors.ts
@@ -44908,12 +46964,12 @@ function toDomainCode(value) {
44908
46964
  }
44909
46965
  function readErrorBody(body) {
44910
46966
  if (typeof body !== "object" || body === null) return {};
44911
- const record3 = body;
44912
- const retryAfterSeconds = typeof record3.retryAfterSeconds === "number" && Number.isFinite(record3.retryAfterSeconds) && record3.retryAfterSeconds > 0 ? record3.retryAfterSeconds : void 0;
44913
- const sponsorSequence = typeof record3.sponsorSequence === "string" && /^\d+$/.test(record3.sponsorSequence) ? record3.sponsorSequence : void 0;
46967
+ const record = body;
46968
+ const retryAfterSeconds = typeof record.retryAfterSeconds === "number" && Number.isFinite(record.retryAfterSeconds) && record.retryAfterSeconds > 0 ? record.retryAfterSeconds : void 0;
46969
+ const sponsorSequence = typeof record.sponsorSequence === "string" && /^\d+$/.test(record.sponsorSequence) ? record.sponsorSequence : void 0;
44914
46970
  return {
44915
- message: typeof record3.message === "string" ? record3.message : void 0,
44916
- code: toDomainCode(record3.error),
46971
+ message: typeof record.message === "string" ? record.message : void 0,
46972
+ code: toDomainCode(record.error),
44917
46973
  retryAfterSeconds,
44918
46974
  sponsorSequence
44919
46975
  };
@@ -45569,6 +47625,81 @@ var PARTNER_CODES = /* @__PURE__ */ new Set([
45569
47625
  "UNKNOWN"
45570
47626
  ]);
45571
47627
  var isPartnerError = isCodeMember(PARTNER_CODES);
47628
+ function sizeLeverageBorrow(request) {
47629
+ const { side, deposit, depositDecimals, collateralPriceUsd, borrowPriceUsd, borrowDecimals, leverage } = request;
47630
+ const depositTokens = Number(viem.formatUnits(deposit, depositDecimals));
47631
+ const depositUsd = depositTokens * (side === "debt" ? borrowPriceUsd : collateralPriceUsd);
47632
+ const RATIO_SCALE = 1000000000n;
47633
+ const ratio = borrowPriceUsd > 0 && depositTokens > 0 ? depositUsd * Math.max(leverage - 1, 0) / borrowPriceUsd / depositTokens : 0;
47634
+ const borrowAmount = deposit * BigInt(Math.floor(ratio * Number(RATIO_SCALE))) * 10n ** BigInt(borrowDecimals) / (RATIO_SCALE * 10n ** BigInt(depositDecimals));
47635
+ const depositInBorrowUnits = deposit * 10n ** BigInt(borrowDecimals) / 10n ** BigInt(depositDecimals);
47636
+ const intentInput = side === "debt" ? borrowAmount + depositInBorrowUnits : borrowAmount;
47637
+ const feeAmount = request.feeBps ? intentInput * BigInt(Math.round(request.feeBps)) / 10000n : 0n;
47638
+ const borrowUsd = Number(viem.formatUnits(borrowAmount, borrowDecimals)) * borrowPriceUsd;
47639
+ const feeUsd = Number(viem.formatUnits(feeAmount, borrowDecimals)) * borrowPriceUsd;
47640
+ return {
47641
+ borrowAmount,
47642
+ intentInput,
47643
+ depositUsd,
47644
+ // Taken from the amount actually being borrowed, so the projection cannot disagree with the
47645
+ // transaction by the rounding above.
47646
+ borrowUsd,
47647
+ feeAmount,
47648
+ // The fee is borrowed on top on a leverage-up, so it is debt even though the solver never sees it.
47649
+ debtUsd: borrowUsd + feeUsd
47650
+ };
47651
+ }
47652
+ function projectLeverageLeg(request, quote, risk, slippagePct) {
47653
+ const { side, collateralPriceUsd, leverage } = request;
47654
+ const sized = sizeLeverageBorrow(request);
47655
+ const { depositUsd, borrowUsd } = sized;
47656
+ const floor = quote.quotedCollateral * BigInt(Math.round((100 - slippagePct) * 100)) / 10000n;
47657
+ const minCollateralOut = floor > 0n ? floor : 1n;
47658
+ const floorUsd = Number(viem.formatUnits(minCollateralOut, quote.collateralDecimals)) * collateralPriceUsd;
47659
+ const quotedUsd = Number(viem.formatUnits(quote.quotedCollateral, quote.collateralDecimals)) * collateralPriceUsd;
47660
+ const inputUsd = side === "debt" ? depositUsd * leverage : borrowUsd;
47661
+ const f = inputUsd > 0 ? floorUsd / inputUsd : 0;
47662
+ const haircut = inputUsd > 0 ? 1 - quotedUsd / inputUsd : 0;
47663
+ const collateralUsd = (side === "debt" ? 0 : depositUsd) + floorUsd;
47664
+ const debtUsd = sized.debtUsd;
47665
+ const ltv = collateralUsd > 0 ? debtUsd / collateralUsd : 0;
47666
+ const ltvF = risk.ltv * f;
47667
+ const phi = (request.feeBps ?? 0) / 1e4;
47668
+ const denominator = 1 + phi - ltvF;
47669
+ const usableMaxLeverage = risk.ltv <= 0 ? 1 : denominator <= 0 ? Number.POSITIVE_INFINITY : side === "debt" ? 1 / denominator : 1 + risk.ltv / denominator;
47670
+ const equityUsd = collateralUsd - debtUsd;
47671
+ return {
47672
+ minCollateralOut,
47673
+ collateralUsd,
47674
+ debtUsd,
47675
+ exposureLeverage: equityUsd > 0 ? collateralUsd / equityUsd : Number.POSITIVE_INFINITY,
47676
+ ltv,
47677
+ healthFactor: debtUsd > 0 ? collateralUsd * risk.liquidationThreshold / debtUsd : Number.POSITIVE_INFINITY,
47678
+ exceedsMaxLtv: ltv > risk.ltv,
47679
+ haircut,
47680
+ inputUsd,
47681
+ costUsd: inputUsd * haircut + sized.debtUsd - borrowUsd,
47682
+ usableMaxLeverage
47683
+ };
47684
+ }
47685
+
47686
+ // src/leverageYield/positionApyMath.ts
47687
+ function leveragedNetApyPct(supplyApyPct, borrowApyPct, leverage) {
47688
+ return supplyApyPct * leverage - borrowApyPct * (leverage - 1);
47689
+ }
47690
+ function timeToBreakevenYears(supplyApyPct, borrowApyPct, toLeverage, { costUsd, equityUsd, fromLeverage }) {
47691
+ if (!(equityUsd > 0) || !Number.isFinite(costUsd)) return void 0;
47692
+ if (costUsd <= 0) return "immediate";
47693
+ const incrementalPct = leveragedNetApyPct(supplyApyPct, borrowApyPct, toLeverage) - leveragedNetApyPct(supplyApyPct, borrowApyPct, fromLeverage);
47694
+ if (!(incrementalPct > 0)) return "never";
47695
+ return costUsd / (equityUsd * (incrementalPct / 100));
47696
+ }
47697
+
47698
+ // src/leverageYield/positionLegQuote.ts
47699
+ function isNoRouteRefusal(error) {
47700
+ const message = typeof error === "object" && error !== null && "detail" in error ? error.detail?.message : error instanceof Error ? error.message : void 0;
47701
+ return /no path was found/i.test(message ?? "");
47702
+ }
45572
47703
  /*! Bundled license information:
45573
47704
 
45574
47705
  @noble/hashes/utils.js:
@@ -45591,6 +47722,10 @@ Object.defineProperty(exports, "SwapsApiError", {
45591
47722
  enumerable: true,
45592
47723
  get: function () { return swapsApi.SwapsApiError; }
45593
47724
  });
47725
+ Object.defineProperty(exports, "BridgeApiError", {
47726
+ enumerable: true,
47727
+ get: function () { return bridgeApi.BridgeApiError; }
47728
+ });
45594
47729
  exports.ALLOWANCE_CHECK_CODES = ALLOWANCE_CHECK_CODES;
45595
47730
  exports.APPROVE_CODES = APPROVE_CODES;
45596
47731
  exports.AssetService = AssetService;
@@ -45679,6 +47814,7 @@ exports.LockupMultiplier = LockupMultiplier;
45679
47814
  exports.LockupPeriod = LockupPeriod;
45680
47815
  exports.LsodaSymbols = LsodaSymbols;
45681
47816
  exports.LsodaTokens = LsodaTokens;
47817
+ exports.MAX_POSITION_FEE_BPS = MAX_POSITION_FEE_BPS;
45682
47818
  exports.MAX_UINT256 = MAX_UINT256;
45683
47819
  exports.MigrationService = MigrationService;
45684
47820
  exports.MintPositionEventAbi = MintPositionEventAbi;
@@ -45703,6 +47839,7 @@ exports.RadfiApiError = RadfiApiError;
45703
47839
  exports.RadfiProvider = RadfiProvider;
45704
47840
  exports.RecoveryService = RecoveryService;
45705
47841
  exports.RelayChainIdMap = RelayChainIdMap;
47842
+ exports.SDK_VERSION = SDK_VERSION;
45706
47843
  exports.SECONDS_PER_YEAR = SECONDS_PER_YEAR;
45707
47844
  exports.SODAX_ERROR_CODES = SODAX_ERROR_CODES;
45708
47845
  exports.SODAX_FEATURES = SODAX_FEATURES;
@@ -45786,6 +47923,7 @@ exports.clRouterAbi = clRouterAbi;
45786
47923
  exports.clTickLensAbi = clTickLensAbi;
45787
47924
  exports.classifySponsorError = classifySponsorError;
45788
47925
  exports.concentratedLiquidityConfig = concentratedLiquidityConfig;
47926
+ exports.configVersionFor = configVersionFor;
45789
47927
  exports.connectionAbi = connectionAbi;
45790
47928
  exports.consoleLogger = consoleLogger;
45791
47929
  exports.convertTransactionInstructionToRaw = convertTransactionInstructionToRaw;
@@ -45808,6 +47946,7 @@ exports.estimateSwapSpeedTier = estimateSwapSpeedTier;
45808
47946
  exports.ethereumSupportedTokens = ethereumSupportedTokens;
45809
47947
  exports.executionFailed = executionFailed;
45810
47948
  exports.formatBasisPoints = formatBasisPoints;
47949
+ exports.formatConfigVersion = formatConfigVersion;
45811
47950
  exports.formatEModeCategory = formatEModeCategory;
45812
47951
  exports.formatEModes = formatEModes;
45813
47952
  exports.formatPercentage = formatPercentage;
@@ -45921,6 +48060,7 @@ exports.isNearChainKey = isNearChainKey;
45921
48060
  exports.isNearChainKeyType = isNearChainKeyType;
45922
48061
  exports.isNewbnUSDChainId = isNewbnUSDChainId;
45923
48062
  exports.isNewbnUSDToken = isNewbnUSDToken;
48063
+ exports.isNoRouteRefusal = isNoRouteRefusal;
45924
48064
  exports.isOptionalBitcoinWalletProviderType = isOptionalBitcoinWalletProviderType;
45925
48065
  exports.isOptionalEvmWalletProviderType = isOptionalEvmWalletProviderType;
45926
48066
  exports.isOptionalStellarWalletProviderType = isOptionalStellarWalletProviderType;
@@ -45979,6 +48119,7 @@ exports.kaiaSupportedTokens = kaiaSupportedTokens;
45979
48119
  exports.leverageYieldConfig = leverageYieldConfig;
45980
48120
  exports.leverageYieldInvariant = leverageYieldInvariant;
45981
48121
  exports.leverageYieldVaults = leverageYieldVaults;
48122
+ exports.leveragedNetApyPct = leveragedNetApyPct;
45982
48123
  exports.lightlinkSupportedTokens = lightlinkSupportedTokens;
45983
48124
  exports.lookupFailed = lookupFailed;
45984
48125
  exports.mapRelayFailure = mapRelayFailure;
@@ -46004,6 +48145,7 @@ exports.optimismSupportedTokens = optimismSupportedTokens;
46004
48145
  exports.pancakeSwapInfinityDefaultHookAbi = pancakeSwapInfinityDefaultHookAbi;
46005
48146
  exports.pancakeSwapInfinityPoolManagerAbi = pancakeSwapInfinityPoolManagerAbi;
46006
48147
  exports.pancakeSwapInfinityPositionManagerAbi = pancakeSwapInfinityPositionManagerAbi;
48148
+ exports.parseConfigVersion = parseConfigVersion;
46007
48149
  exports.parseToStroops = parseToStroops;
46008
48150
  exports.parseTokenArrayFromJson = parseTokenArrayFromJson;
46009
48151
  exports.partnerInvariant = partnerInvariant;
@@ -46011,6 +48153,7 @@ exports.permit2Abi = permit2Abi;
46011
48153
  exports.polygonSupportedTokens = polygonSupportedTokens;
46012
48154
  exports.poolAbi = poolAbi;
46013
48155
  exports.poolKeyAbi = poolKeyAbi;
48156
+ exports.projectLeverageLeg = projectLeverageLeg;
46014
48157
  exports.randomUint256 = randomUint256;
46015
48158
  exports.rayDiv = rayDiv;
46016
48159
  exports.rayMul = rayMul;
@@ -46020,11 +48163,13 @@ exports.recoveryInvariant = recoveryInvariant;
46020
48163
  exports.redbellySupportedTokens = redbellySupportedTokens;
46021
48164
  exports.relayConfig = relayConfig;
46022
48165
  exports.relayTxAndWaitPacket = relayTxAndWaitPacket;
48166
+ exports.reportPositionIntent = reportPositionIntent;
46023
48167
  exports.requestAddress = requestAddress;
46024
48168
  exports.requestJsonRpc = requestJsonRpc;
46025
48169
  exports.requestSigning = requestSigning;
46026
48170
  exports.resolveAnalytics = resolveAnalytics;
46027
48171
  exports.resolveLogger = resolveLogger;
48172
+ exports.resolvePositionFundingAddress = resolvePositionFundingAddress;
46028
48173
  exports.retry = retry;
46029
48174
  exports.reverseEncodeAddress = reverseEncodeAddress;
46030
48175
  exports.robinhoodChain = robinhoodChain;
@@ -46032,6 +48177,7 @@ exports.robinhoodSupportedTokens = robinhoodSupportedTokens;
46032
48177
  exports.serializeAddressData = serializeAddressData;
46033
48178
  exports.settleWalletBalances = settleWalletBalances;
46034
48179
  exports.silentLogger = silentLogger;
48180
+ exports.sizeLeverageBorrow = sizeLeverageBorrow;
46035
48181
  exports.sleep = sleep;
46036
48182
  exports.sodaxConfig = sodaxConfig;
46037
48183
  exports.sodaxInvariant = sodaxInvariant;
@@ -46059,6 +48205,7 @@ exports.swapExactInSingleParamsAbi = swapExactInSingleParamsAbi;
46059
48205
  exports.swapInvariant = swapInvariant;
46060
48206
  exports.swapSupportedTokens = swapSupportedTokens;
46061
48207
  exports.swapsConfig = swapsConfig;
48208
+ exports.timeToBreakevenYears = timeToBreakevenYears;
46062
48209
  exports.toCreateBridgeIntentParamsV2 = toCreateBridgeIntentParamsV2;
46063
48210
  exports.toSuiExecutionResult = toSuiExecutionResult;
46064
48211
  exports.toSuiExecutionStatus = toSuiExecutionStatus;