@sodax/sdk 2.0.0-rc.19 → 2.0.0-rc.20

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
@@ -19,7 +19,8 @@ var IconSdkRaw = require('icon-sdk-js');
19
19
  var sdkTs = require('@injectivelabs/sdk-ts');
20
20
  var tx_js = require('cosmjs-types/cosmos/tx/v1beta1/tx.js');
21
21
  var networks = require('@injectivelabs/networks');
22
- var v4 = require('valibot');
22
+ var v2 = require('valibot');
23
+ var swapsApi = require('@sodax/swaps-api');
23
24
  var BigNumber5 = require('bignumber.js');
24
25
  var swapSdkCore = require('@pancakeswap/swap-sdk-core');
25
26
  var v3Sdk = require('@pancakeswap/v3-sdk');
@@ -48,7 +49,7 @@ var rlp__namespace = /*#__PURE__*/_interopNamespace(rlp);
48
49
  var ecc__namespace = /*#__PURE__*/_interopNamespace(ecc);
49
50
  var BN__default = /*#__PURE__*/_interopDefault(BN);
50
51
  var IconSdkRaw__namespace = /*#__PURE__*/_interopNamespace(IconSdkRaw);
51
- var v4__namespace = /*#__PURE__*/_interopNamespace(v4);
52
+ var v2__namespace = /*#__PURE__*/_interopNamespace(v2);
52
53
  var BigNumber5__default = /*#__PURE__*/_interopDefault(BigNumber5);
53
54
 
54
55
  // src/errors/SodaxError.ts
@@ -121,8 +122,8 @@ function serializeCause(cause, depth) {
121
122
  }
122
123
  function sanitizeContext(value, depth) {
123
124
  const out = {};
124
- for (const [key, v6] of Object.entries(value)) {
125
- out[key] = sanitizeValue(v6, depth + 1);
125
+ for (const [key, v4] of Object.entries(value)) {
126
+ out[key] = sanitizeValue(v4, depth + 1);
126
127
  }
127
128
  return out;
128
129
  }
@@ -133,13 +134,13 @@ function sanitizeValue(value, depth) {
133
134
  if (t === "bigint") return value.toString();
134
135
  if (t === "string" || t === "number" || t === "boolean") return value;
135
136
  if (t === "function" || t === "symbol") return safeString(value);
136
- if (Array.isArray(value)) return value.map((v6) => sanitizeValue(v6, depth + 1));
137
+ if (Array.isArray(value)) return value.map((v4) => sanitizeValue(v4, depth + 1));
137
138
  if (value instanceof Date) return value.toISOString();
138
139
  if (value instanceof Map) {
139
- return Array.from(value.entries()).map(([k, v6]) => [sanitizeValue(k, depth + 1), sanitizeValue(v6, depth + 1)]);
140
+ return Array.from(value.entries()).map(([k, v4]) => [sanitizeValue(k, depth + 1), sanitizeValue(v4, depth + 1)]);
140
141
  }
141
142
  if (value instanceof Set) {
142
- return Array.from(value.values()).map((v6) => sanitizeValue(v6, depth + 1));
143
+ return Array.from(value.values()).map((v4) => sanitizeValue(v4, depth + 1));
143
144
  }
144
145
  if (value instanceof Error) return { name: value.name, message: value.message };
145
146
  if (t === "object") {
@@ -151,9 +152,9 @@ function sanitizeValue(value, depth) {
151
152
  }
152
153
  return safeString(value);
153
154
  }
154
- function safeString(v6) {
155
+ function safeString(v4) {
155
156
  try {
156
- return String(v6);
157
+ return String(v4);
157
158
  } catch {
158
159
  return "[unserializable]";
159
160
  }
@@ -161,11 +162,17 @@ function safeString(v6) {
161
162
 
162
163
  // src/errors/codes.ts
163
164
  var CREATE_INTENT_CODES = /* @__PURE__ */ new Set([
165
+ "USER_REJECTED",
164
166
  "VALIDATION_FAILED",
165
167
  "INTENT_CREATION_FAILED",
166
168
  "UNKNOWN"
167
169
  ]);
168
- var APPROVE_CODES = /* @__PURE__ */ new Set(["VALIDATION_FAILED", "APPROVE_FAILED", "UNKNOWN"]);
170
+ var APPROVE_CODES = /* @__PURE__ */ new Set([
171
+ "USER_REJECTED",
172
+ "VALIDATION_FAILED",
173
+ "APPROVE_FAILED",
174
+ "UNKNOWN"
175
+ ]);
169
176
  var ALLOWANCE_CHECK_CODES = /* @__PURE__ */ new Set([
170
177
  "VALIDATION_FAILED",
171
178
  "ALLOWANCE_CHECK_FAILED",
@@ -178,6 +185,7 @@ var GAS_ESTIMATION_CODES = /* @__PURE__ */ new Set([
178
185
  ]);
179
186
  var LOOKUP_CODES = /* @__PURE__ */ new Set(["VALIDATION_FAILED", "LOOKUP_FAILED", "UNKNOWN"]);
180
187
  var SODAX_ERROR_CODES = [
188
+ "USER_REJECTED",
181
189
  "VALIDATION_FAILED",
182
190
  "INTENT_CREATION_FAILED",
183
191
  "EXECUTION_FAILED",
@@ -299,7 +307,8 @@ var ChainKeys = {
299
307
  BITCOIN_MAINNET: "bitcoin",
300
308
  REDBELLY_MAINNET: "redbelly",
301
309
  KAIA_MAINNET: "0x2019.kaia",
302
- STACKS_MAINNET: "stacks"
310
+ STACKS_MAINNET: "stacks",
311
+ HEDERA_MAINNET: "hedera"
303
312
  };
304
313
  var CHAIN_KEYS = Object.values(ChainKeys);
305
314
  var spokeChainKeysSet = new Set(CHAIN_KEYS);
@@ -336,6 +345,7 @@ var HubVaultSymbols = [
336
345
  "sodaKAIA",
337
346
  "sodaSTX",
338
347
  "sodaUSDS",
348
+ "sodaHBAR",
339
349
  "sodaJITOSOL"
340
350
  ];
341
351
  var SodaTokens = {
@@ -564,6 +574,15 @@ var SodaTokens = {
564
574
  hubAsset: "0x243b0c26c8b38793908d7C64e8510f21B19B4613",
565
575
  vault: "0x243b0c26c8b38793908d7C64e8510f21B19B4613"
566
576
  },
577
+ sodaHBAR: {
578
+ symbol: "sodaHBAR",
579
+ name: "Soda HBAR",
580
+ decimals: 18,
581
+ address: "0x3BB956cc8922E1Ba4148dc10eD1b4Fa19aa599c4",
582
+ chainKey: ChainKeys.SONIC_MAINNET,
583
+ hubAsset: "0x3BB956cc8922E1Ba4148dc10eD1b4Fa19aa599c4",
584
+ vault: "0x3BB956cc8922E1Ba4148dc10eD1b4Fa19aa599c4"
585
+ },
567
586
  sodaJITOSOL: {
568
587
  symbol: "sodaJITOSOL",
569
588
  name: "Soda JITOSOL",
@@ -2549,6 +2568,44 @@ var kaiaSupportedTokens = {
2549
2568
  vault: SodaTokens.sodaSODA.address
2550
2569
  }
2551
2570
  };
2571
+ var hederaSupportedTokens = {
2572
+ HBAR: {
2573
+ symbol: "HBAR",
2574
+ name: "HBAR",
2575
+ decimals: 8,
2576
+ address: "0x0000000000000000000000000000000000000000",
2577
+ chainKey: ChainKeys.HEDERA_MAINNET,
2578
+ hubAsset: "0x5c18c543b6B6EA97dE739F48C49CfC291B3AD465",
2579
+ vault: SodaTokens.sodaHBAR.address
2580
+ },
2581
+ bnUSD: {
2582
+ symbol: "bnUSD",
2583
+ name: "bnUSD",
2584
+ decimals: 8,
2585
+ address: "0x0000000000000000000000000000000000a0286a",
2586
+ chainKey: ChainKeys.HEDERA_MAINNET,
2587
+ hubAsset: "0x44be1984cd279334a630469fa357305c7dba2837",
2588
+ vault: SodaTokens.bnUSD.address
2589
+ },
2590
+ SODA: {
2591
+ symbol: "SODA",
2592
+ name: "SODAX",
2593
+ decimals: 8,
2594
+ address: "0x0000000000000000000000000000000000a02869",
2595
+ chainKey: ChainKeys.HEDERA_MAINNET,
2596
+ hubAsset: "0x1217721376839dbffe78093ddd5d8e50d0239b3f",
2597
+ vault: SodaTokens.sodaSODA.address
2598
+ },
2599
+ USDC: {
2600
+ symbol: "USDC",
2601
+ name: "USD Coin",
2602
+ decimals: 6,
2603
+ address: "0x000000000000000000000000000000000006f89a",
2604
+ chainKey: ChainKeys.HEDERA_MAINNET,
2605
+ hubAsset: "0xafafae0c1476424c4b81f09095bd7dcb858047c8",
2606
+ vault: SodaTokens.sodaUSDC.address
2607
+ }
2608
+ };
2552
2609
  var stacksSupportedTokens = {
2553
2610
  STX: {
2554
2611
  symbol: "STX",
@@ -2616,7 +2673,8 @@ var supportedTokensByChain = {
2616
2673
  [ChainKeys.NEAR_MAINNET]: nearSupportedTokens,
2617
2674
  [ChainKeys.ETHEREUM_MAINNET]: ethereumSupportedTokens,
2618
2675
  [ChainKeys.KAIA_MAINNET]: kaiaSupportedTokens,
2619
- [ChainKeys.STACKS_MAINNET]: stacksSupportedTokens
2676
+ [ChainKeys.STACKS_MAINNET]: stacksSupportedTokens,
2677
+ [ChainKeys.HEDERA_MAINNET]: hederaSupportedTokens
2620
2678
  };
2621
2679
 
2622
2680
  // ../types/dist/chains/chains.js
@@ -2640,7 +2698,8 @@ var RelayChainIdMap = {
2640
2698
  [ChainKeys.BITCOIN_MAINNET]: 627463n,
2641
2699
  [ChainKeys.REDBELLY_MAINNET]: 726564n,
2642
2700
  [ChainKeys.KAIA_MAINNET]: 27489n,
2643
- [ChainKeys.STACKS_MAINNET]: 60n
2701
+ [ChainKeys.STACKS_MAINNET]: 60n,
2702
+ [ChainKeys.HEDERA_MAINNET]: 18501n
2644
2703
  };
2645
2704
  var INTENT_CHAIN_IDS = Object.values(RelayChainIdMap);
2646
2705
  var IntentRelayChainIdToChainKey = new Map(Object.entries(RelayChainIdMap).map(([chainKey, chainId]) => [chainId, chainKey]));
@@ -2926,6 +2985,20 @@ var baseChainInfo = {
2926
2985
  addressUrl: "https://explorer.hiro.so/address/",
2927
2986
  contractUrl: "https://explorer.hiro.so/txid/"
2928
2987
  }
2988
+ },
2989
+ [ChainKeys.HEDERA_MAINNET]: {
2990
+ name: "Hedera",
2991
+ key: ChainKeys.HEDERA_MAINNET,
2992
+ type: "EVM",
2993
+ chainId: 295,
2994
+ mainnet: true,
2995
+ logo: chainLogo(ChainKeys.HEDERA_MAINNET),
2996
+ explorer: {
2997
+ baseUrl: "https://hashscan.io/mainnet/",
2998
+ txUrl: "https://hashscan.io/mainnet/transaction/",
2999
+ addressUrl: "https://hashscan.io/mainnet/account/",
3000
+ contractUrl: "https://hashscan.io/mainnet/contract/"
3001
+ }
2929
3002
  }
2930
3003
  };
2931
3004
  var filterChainKeysByType = (type) => CHAIN_KEYS.filter((key) => baseChainInfo[key].type === type);
@@ -3321,6 +3394,21 @@ var spokeChainConfig = {
3321
3394
  pollingIntervalMs: 1e4,
3322
3395
  maxTimeoutMs: 12e4
3323
3396
  }
3397
+ },
3398
+ [ChainKeys.HEDERA_MAINNET]: {
3399
+ chain: baseChainInfo[ChainKeys.HEDERA_MAINNET],
3400
+ rpcUrl: "https://mainnet.hashio.io/api",
3401
+ addresses: {
3402
+ assetManager: "0x0df73542cC68bDC01b361d231c60F726B0e0bC05",
3403
+ connection: "0x4555aC13D7338D9E671584C1D118c06B2a3C88eD"
3404
+ },
3405
+ nativeToken: "0x0000000000000000000000000000000000000000",
3406
+ bnUSD: "0x0000000000000000000000000000000000a0286a",
3407
+ supportedTokens: hederaSupportedTokens,
3408
+ pollingConfig: {
3409
+ pollingIntervalMs: 2e3,
3410
+ maxTimeoutMs: 6e4
3411
+ }
3324
3412
  }
3325
3413
  };
3326
3414
  var supportedSpokeChains = Object.keys(spokeChainConfig);
@@ -3571,6 +3659,11 @@ var moneyMarketSupportedTokens = {
3571
3659
  ],
3572
3660
  [ChainKeys.BITCOIN_MAINNET]: [
3573
3661
  spokeChainConfig[ChainKeys.BITCOIN_MAINNET].supportedTokens.BTC
3662
+ ],
3663
+ [ChainKeys.HEDERA_MAINNET]: [
3664
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.bnUSD,
3665
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.SODA,
3666
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.USDC
3574
3667
  ]
3575
3668
  };
3576
3669
  var moneyMarketReserveAssets = [
@@ -3980,7 +4073,9 @@ var swapSupportedTokens = {
3980
4073
  spokeChainConfig[ChainKeys.STACKS_MAINNET].supportedTokens.SODA,
3981
4074
  spokeChainConfig[ChainKeys.STACKS_MAINNET].supportedTokens.sBTC,
3982
4075
  spokeChainConfig[ChainKeys.STACKS_MAINNET].supportedTokens.USDC
3983
- ]
4076
+ ],
4077
+ // Hedera is currently staging-only — see stagingSwapSupportedTokens
4078
+ [ChainKeys.HEDERA_MAINNET]: []
3984
4079
  };
3985
4080
  var stagingSwapSupportedTokens = {
3986
4081
  [ChainKeys.SONIC_MAINNET]: [SodaTokens.sodaUSDS],
@@ -4013,7 +4108,13 @@ var stagingSwapSupportedTokens = {
4013
4108
  ],
4014
4109
  [ChainKeys.REDBELLY_MAINNET]: [],
4015
4110
  [ChainKeys.KAIA_MAINNET]: [],
4016
- [ChainKeys.STACKS_MAINNET]: []
4111
+ [ChainKeys.STACKS_MAINNET]: [],
4112
+ [ChainKeys.HEDERA_MAINNET]: [
4113
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.HBAR,
4114
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.bnUSD,
4115
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.USDC,
4116
+ spokeChainConfig[ChainKeys.HEDERA_MAINNET].supportedTokens.SODA
4117
+ ]
4017
4118
  };
4018
4119
  var swapsConfig = {
4019
4120
  supportedTokens: swapSupportedTokens
@@ -4249,7 +4350,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
4249
4350
  }
4250
4351
 
4251
4352
  // ../types/dist/index.js
4252
- var CONFIG_VERSION = 217;
4353
+ var CONFIG_VERSION = 218;
4253
4354
  function isEvmSpokeChainConfig(value) {
4254
4355
  return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
4255
4356
  }
@@ -4376,11 +4477,11 @@ async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_R
4376
4477
  throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
4377
4478
  }
4378
4479
  function getRandomBytes(length) {
4379
- const array3 = new Uint8Array(length);
4480
+ const array2 = new Uint8Array(length);
4380
4481
  for (let i = 0; i < length; i++) {
4381
- array3[i] = Math.floor(Math.random() * 256);
4482
+ array2[i] = Math.floor(Math.random() * 256);
4382
4483
  }
4383
- return array3;
4484
+ return array2;
4384
4485
  }
4385
4486
  function randomUint256() {
4386
4487
  const bytes = getRandomBytes(32);
@@ -4739,8 +4840,61 @@ function isCodeMember(codes) {
4739
4840
  }
4740
4841
 
4741
4842
  // src/errors/wrappers.ts
4742
- function messageOf(error, fallback) {
4743
- return error instanceof Error ? error.message : fallback;
4843
+ function messageOf(error, fallback2) {
4844
+ return error instanceof Error ? error.message : fallback2;
4845
+ }
4846
+ var REJECTION_TEXT_PATTERNS = [
4847
+ /user rejected/i,
4848
+ /user denied/i,
4849
+ /user declined/i,
4850
+ /user cancel(?:l)?ed/i,
4851
+ /user abort(?:ed)?/i,
4852
+ /user closed/i,
4853
+ /rejected by user/i,
4854
+ /cancelled by user/i,
4855
+ /canceled by user/i,
4856
+ // `was` is mandatory: matches Phantom / Brave's "Transaction was rejected" (user cancellation)
4857
+ // but NOT bare "Transaction rejected by node / by validator" (network or chain-level reject).
4858
+ /transaction was rejected/i,
4859
+ /signature rejected/i,
4860
+ /request rejected/i,
4861
+ /cancel_signing/i,
4862
+ /cancel_json-rpc/i,
4863
+ /popup ?closed/i
4864
+ ];
4865
+ function matchRejectionText(text) {
4866
+ if (typeof text !== "string" || text.length === 0) return false;
4867
+ for (const pattern of REJECTION_TEXT_PATTERNS) {
4868
+ if (pattern.test(text)) return true;
4869
+ }
4870
+ return false;
4871
+ }
4872
+ function isWalletRejection(error) {
4873
+ if (error == null) return false;
4874
+ if (isSodaxError(error)) return error.code === "USER_REJECTED";
4875
+ if (typeof error === "string") return matchRejectionText(error);
4876
+ if (typeof error !== "object") return false;
4877
+ const o = error;
4878
+ if (o.name === "UserRejectedRequestError") return true;
4879
+ if (o.name === "WalletSignTransactionError" && matchRejectionText(o.message)) return true;
4880
+ if (o.name === "WalletConnectionError" && matchRejectionText(o.message)) return true;
4881
+ if (o.code === 4001) return true;
4882
+ if (o.code === "ACTION_REJECTED") return true;
4883
+ if (o.code === "CANCEL_SIGNING") return true;
4884
+ if (o.code === "CANCEL_JSON-RPC") return true;
4885
+ if (o.code === -31002) return true;
4886
+ if (matchRejectionText(o.shortMessage)) return true;
4887
+ if (matchRejectionText(o.details)) return true;
4888
+ if (matchRejectionText(o.message)) return true;
4889
+ if (matchRejectionText(o.reason)) return true;
4890
+ return false;
4891
+ }
4892
+ function userRejected(feature, cause, context) {
4893
+ return new SodaxError("USER_REJECTED", "User rejected the request", {
4894
+ feature,
4895
+ cause,
4896
+ context
4897
+ });
4744
4898
  }
4745
4899
  function lookupFailed(feature, method, cause, context) {
4746
4900
  return new SodaxError("LOOKUP_FAILED", messageOf(cause, `${method} failed`), {
@@ -4757,6 +4911,7 @@ function verifyFailed(feature, cause, context) {
4757
4911
  });
4758
4912
  }
4759
4913
  function intentCreationFailed(feature, cause, context) {
4914
+ if (isWalletRejection(cause)) return userRejected(feature, cause, { phase: "intentCreation", ...context });
4760
4915
  return new SodaxError("INTENT_CREATION_FAILED", messageOf(cause, "Intent creation failed"), {
4761
4916
  feature,
4762
4917
  cause,
@@ -4771,6 +4926,7 @@ function executionFailed(feature, cause, context) {
4771
4926
  });
4772
4927
  }
4773
4928
  function approveFailed(feature, cause, context) {
4929
+ if (isWalletRejection(cause)) return userRejected(feature, cause, { phase: "approve", ...context });
4774
4930
  return new SodaxError("APPROVE_FAILED", messageOf(cause, "Approve failed"), {
4775
4931
  feature,
4776
4932
  cause,
@@ -14055,7 +14211,7 @@ function mergeSodaxConfig(base2, override) {
14055
14211
  }
14056
14212
  function encodeContractCalls(calls) {
14057
14213
  return viem.encodeAbiParameters(viem.parseAbiParameters("(address,uint256,bytes)[]"), [
14058
- calls.map((v6) => [v6.address, v6.value, v6.data])
14214
+ calls.map((v4) => [v4.address, v4.value, v4.data])
14059
14215
  ]);
14060
14216
  }
14061
14217
  async function waitForTransactionReceipt(hash, provider) {
@@ -14139,6 +14295,8 @@ function getEvmViemChain(key) {
14139
14295
  return chains.redbellyMainnet;
14140
14296
  case ChainKeys.KAIA_MAINNET:
14141
14297
  return chains.kaia;
14298
+ case ChainKeys.HEDERA_MAINNET:
14299
+ return chains.hedera;
14142
14300
  default: {
14143
14301
  const exhaustiveCheck = key;
14144
14302
  console.log(exhaustiveCheck);
@@ -14153,7 +14311,7 @@ var EvmVaultTokenService = class {
14153
14311
  * Fetches token information for a specific token in the vault.
14154
14312
  * @param vault - The address of the vault.
14155
14313
  * @param token - The address of the token.
14156
- * @param publicClient - PublicClient<HttpTransport>
14314
+ * @param publicClient - PublicClient
14157
14315
  * @returns Token information as a TokenInfo object.
14158
14316
  */
14159
14317
  static async getTokenInfo(vault, token, publicClient) {
@@ -14192,7 +14350,7 @@ var EvmVaultTokenService = class {
14192
14350
  /**
14193
14351
  * Retrieves the reserves of the vault.
14194
14352
  * @param vault - The address of the vault.
14195
- * @param publicClient - PublicClient<HttpTransport>
14353
+ * @param publicClient - PublicClient
14196
14354
  * @returns An object containing tokens and their balances.
14197
14355
  */
14198
14356
  static async getVaultReserves(vault, publicClient) {
@@ -14210,7 +14368,7 @@ var EvmVaultTokenService = class {
14210
14368
  /**
14211
14369
  * Retrieves all token information for the vault.
14212
14370
  * @param vault - The address of the vault.
14213
- * @param publicClient - PublicClient<HttpTransport>
14371
+ * @param publicClient - PublicClient
14214
14372
  * @returns A promise that resolves to an object containing tokens, their infos, and reserves.
14215
14373
  */
14216
14374
  static async getAllTokenInfo(vault, publicClient) {
@@ -14570,6 +14728,10 @@ var EvmAssetManagerService = class _EvmAssetManagerService {
14570
14728
  });
14571
14729
  }
14572
14730
  };
14731
+ var HEDERA_NATIVE_VALUE_SCALE = 10n ** 10n;
14732
+ function scaleNativeMsgValue(chainKey, amount) {
14733
+ return chainKey === ChainKeys.HEDERA_MAINNET ? amount * HEDERA_NATIVE_VALUE_SCALE : amount;
14734
+ }
14573
14735
  var EvmSpokeService = class {
14574
14736
  config;
14575
14737
  // map containing the public clients for each evm spoke chain, lazy loaded on demand
@@ -14657,10 +14819,11 @@ var EvmSpokeService = class {
14657
14819
  async deposit(params) {
14658
14820
  const { srcChainKey, srcAddress: from, token, to, amount, data = "0x" } = params;
14659
14821
  const chainConfig = this.config.getChainConfig(srcChainKey);
14822
+ const isNative = token.toLowerCase() === chainConfig.nativeToken.toLowerCase();
14660
14823
  const rawTx = {
14661
14824
  from,
14662
14825
  to: chainConfig.addresses.assetManager,
14663
- value: token.toLowerCase() === chainConfig.nativeToken.toLowerCase() ? amount : 0n,
14826
+ value: isNative ? scaleNativeMsgValue(srcChainKey, amount) : 0n,
14664
14827
  data: viem.encodeFunctionData({
14665
14828
  abi: spokeAssetManagerAbi,
14666
14829
  functionName: "transfer",
@@ -14949,8 +15112,8 @@ var RadfiApiError = class extends Error {
14949
15112
  code;
14950
15113
  details;
14951
15114
  cause;
14952
- constructor(status, body, fallback) {
14953
- super(body?.message || fallback);
15115
+ constructor(status, body, fallback2) {
15116
+ super(body?.message || fallback2);
14954
15117
  this.name = "RadfiApiError";
14955
15118
  this.status = status;
14956
15119
  this.code = body?.code;
@@ -15318,7 +15481,7 @@ var RadfiProvider = class {
15318
15481
  * body as text first and parsing it ourselves lets us raise a `RadfiApiError` carrying the
15319
15482
  * actual status code and a body snippet instead.
15320
15483
  */
15321
- async parseJsonBody(res, fallback) {
15484
+ async parseJsonBody(res, fallback2) {
15322
15485
  const text = await res.text();
15323
15486
  try {
15324
15487
  return text.length ? JSON.parse(text) : {};
@@ -15327,7 +15490,7 @@ var RadfiProvider = class {
15327
15490
  throw new RadfiApiError(
15328
15491
  res.status,
15329
15492
  { message: `Bound Exchange returned a non-JSON response (HTTP ${res.status})${snippet ? `: ${snippet}` : ""}` },
15330
- fallback
15493
+ fallback2
15331
15494
  );
15332
15495
  }
15333
15496
  }
@@ -16031,7 +16194,7 @@ function hexToBytes2(hex) {
16031
16194
  const al = hl / 2;
16032
16195
  if (hl % 2)
16033
16196
  throw new Error("hex string expected, got unpadded hex of length " + hl);
16034
- const array3 = new Uint8Array(al);
16197
+ const array2 = new Uint8Array(al);
16035
16198
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
16036
16199
  const n1 = asciiToBase16(hex.charCodeAt(hi));
16037
16200
  const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
@@ -16039,9 +16202,9 @@ function hexToBytes2(hex) {
16039
16202
  const char = hex[hi] + hex[hi + 1];
16040
16203
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
16041
16204
  }
16042
- array3[ai] = n1 * 16 + n2;
16205
+ array2[ai] = n1 * 16 + n2;
16043
16206
  }
16044
- return array3;
16207
+ return array2;
16045
16208
  }
16046
16209
  function concatBytes(...arrays) {
16047
16210
  let sum = 0;
@@ -16671,22 +16834,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16671
16834
  const byte0 = Uint8Array.of(0);
16672
16835
  const byte1 = Uint8Array.of(1);
16673
16836
  const _maxDrbgIters = 1e3;
16674
- let v6 = u8n(hashLen);
16837
+ let v4 = u8n(hashLen);
16675
16838
  let k = u8n(hashLen);
16676
16839
  let i = 0;
16677
16840
  const reset = () => {
16678
- v6.fill(1);
16841
+ v4.fill(1);
16679
16842
  k.fill(0);
16680
16843
  i = 0;
16681
16844
  };
16682
- const h = (...msgs) => hmacFn(k, concatBytes(v6, ...msgs));
16845
+ const h = (...msgs) => hmacFn(k, concatBytes(v4, ...msgs));
16683
16846
  const reseed = (seed = NULL) => {
16684
16847
  k = h(byte0, seed);
16685
- v6 = h();
16848
+ v4 = h();
16686
16849
  if (seed.length === 0)
16687
16850
  return;
16688
16851
  k = h(byte1, seed);
16689
- v6 = h();
16852
+ v4 = h();
16690
16853
  };
16691
16854
  const gen = () => {
16692
16855
  if (i++ >= _maxDrbgIters)
@@ -16694,10 +16857,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16694
16857
  let len = 0;
16695
16858
  const out = [];
16696
16859
  while (len < qByteLen) {
16697
- v6 = h();
16698
- const sl = v6.slice();
16860
+ v4 = h();
16861
+ const sl = v4.slice();
16699
16862
  out.push(sl);
16700
- len += v6.length;
16863
+ len += v4.length;
16701
16864
  }
16702
16865
  return concatBytes(...out);
16703
16866
  };
@@ -16712,18 +16875,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16712
16875
  };
16713
16876
  return genUntil;
16714
16877
  }
16715
- function validateObject(object4, fields = {}, optFields = {}) {
16716
- if (!object4 || typeof object4 !== "object")
16878
+ function validateObject(object2, fields = {}, optFields = {}) {
16879
+ if (!object2 || typeof object2 !== "object")
16717
16880
  throw new Error("expected valid options object");
16718
16881
  function checkField(fieldName, expectedType, isOpt) {
16719
- const val = object4[fieldName];
16882
+ const val = object2[fieldName];
16720
16883
  if (isOpt && val === void 0)
16721
16884
  return;
16722
16885
  const current = typeof val;
16723
16886
  if (current !== expectedType || val === null)
16724
16887
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
16725
16888
  }
16726
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v6]) => checkField(k, v6, isOpt));
16889
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v4]) => checkField(k, v4, isOpt));
16727
16890
  iter(fields, false);
16728
16891
  iter(optFields, true);
16729
16892
  }
@@ -16762,12 +16925,12 @@ function pow2(x, power, modulo) {
16762
16925
  }
16763
16926
  return res;
16764
16927
  }
16765
- function invert(number4, modulo) {
16766
- if (number4 === _0n2)
16928
+ function invert(number2, modulo) {
16929
+ if (number2 === _0n2)
16767
16930
  throw new Error("invert: expected non-zero number");
16768
16931
  if (modulo <= _0n2)
16769
16932
  throw new Error("invert: expected positive modulus, got " + modulo);
16770
- let a = mod(number4, modulo);
16933
+ let a = mod(number2, modulo);
16771
16934
  let b = modulo;
16772
16935
  let x = _0n2, u = _1n2;
16773
16936
  while (a !== _0n2) {
@@ -16794,9 +16957,9 @@ function sqrt3mod4(Fp, n) {
16794
16957
  function sqrt5mod8(Fp, n) {
16795
16958
  const p5div8 = (Fp.ORDER - _5n) / _8n;
16796
16959
  const n2 = Fp.mul(n, _2n);
16797
- const v6 = Fp.pow(n2, p5div8);
16798
- const nv = Fp.mul(n, v6);
16799
- const i = Fp.mul(Fp.mul(nv, _2n), v6);
16960
+ const v4 = Fp.pow(n2, p5div8);
16961
+ const nv = Fp.mul(n, v4);
16962
+ const i = Fp.mul(Fp.mul(nv, _2n), v4);
16800
16963
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
16801
16964
  assertIsSquare(Fp, root, n);
16802
16965
  return root;
@@ -17271,27 +17434,27 @@ var wNAF = class {
17271
17434
  assert0(n);
17272
17435
  return acc;
17273
17436
  }
17274
- getPrecomputes(W, point, transform2) {
17437
+ getPrecomputes(W, point, transform) {
17275
17438
  let comp = pointPrecomputes.get(point);
17276
17439
  if (!comp) {
17277
17440
  comp = this.precomputeWindow(point, W);
17278
17441
  if (W !== 1) {
17279
- if (typeof transform2 === "function")
17280
- comp = transform2(comp);
17442
+ if (typeof transform === "function")
17443
+ comp = transform(comp);
17281
17444
  pointPrecomputes.set(point, comp);
17282
17445
  }
17283
17446
  }
17284
17447
  return comp;
17285
17448
  }
17286
- cached(point, scalar, transform2) {
17449
+ cached(point, scalar, transform) {
17287
17450
  const W = getW(point);
17288
- return this.wNAF(W, this.getPrecomputes(W, point, transform2), scalar);
17451
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
17289
17452
  }
17290
- unsafe(point, scalar, transform2, prev) {
17453
+ unsafe(point, scalar, transform, prev) {
17291
17454
  const W = getW(point);
17292
17455
  if (W === 1)
17293
17456
  return this._unsafeLadder(point, scalar, prev);
17294
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform2), scalar, prev);
17457
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
17295
17458
  }
17296
17459
  // We calculate precomputes for elliptic curve point multiplication
17297
17460
  // using windowed method. This specifies window size and
@@ -17378,9 +17541,9 @@ function edwards(params, extraOpts = {}) {
17378
17541
  validateObject(extraOpts, {}, { uvRatio: "function" });
17379
17542
  const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
17380
17543
  const modP = (n) => Fp.create(n);
17381
- const uvRatio2 = extraOpts.uvRatio || ((u, v6) => {
17544
+ const uvRatio2 = extraOpts.uvRatio || ((u, v4) => {
17382
17545
  try {
17383
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v6)) };
17546
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v4)) };
17384
17547
  } catch (e) {
17385
17548
  return { isValid: false, value: _0n4 };
17386
17549
  }
@@ -17476,8 +17639,8 @@ function edwards(params, extraOpts = {}) {
17476
17639
  aInRange("point.y", y, _0n4, max);
17477
17640
  const y2 = modP(y * y);
17478
17641
  const u = modP(y2 - _1n4);
17479
- const v6 = modP(d * y2 - a);
17480
- let { isValid, value: x } = uvRatio2(u, v6);
17642
+ const v4 = modP(d * y2 - a);
17643
+ let { isValid, value: x } = uvRatio2(u, v4);
17481
17644
  if (!isValid)
17482
17645
  throw new Error("bad point: invalid y coordinate");
17483
17646
  const isXOdd = (x & _1n4) === _1n4;
@@ -17817,13 +17980,13 @@ function adjustScalarBytes(bytes) {
17817
17980
  return bytes;
17818
17981
  }
17819
17982
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
17820
- function uvRatio(u, v6) {
17983
+ function uvRatio(u, v4) {
17821
17984
  const P = ed25519_CURVE_p;
17822
- const v32 = mod(v6 * v6 * v6, P);
17823
- const v7 = mod(v32 * v32 * v6, P);
17985
+ const v32 = mod(v4 * v4 * v4, P);
17986
+ const v7 = mod(v32 * v32 * v4, P);
17824
17987
  const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
17825
17988
  let x = mod(u * v32 * pow, P);
17826
- const vx2 = mod(v6 * x * x, P);
17989
+ const vx2 = mod(v4 * x * x, P);
17827
17990
  const root1 = x;
17828
17991
  const root2 = mod(x * ED25519_SQRT_M1, P);
17829
17992
  const useRoot1 = vx2 === u;
@@ -18154,7 +18317,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
18154
18317
  return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
18155
18318
  }
18156
18319
  function findSeatPriceForProtocolBefore49(validators, numSeats) {
18157
- const stakes = validators.map((v6) => BigInt(v6.stake)).sort(sortBigIntAsc);
18320
+ const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18158
18321
  const num = BigInt(numSeats);
18159
18322
  const stakesSum = stakes.reduce((a, b) => a + b);
18160
18323
  if (stakesSum < num) {
@@ -18183,7 +18346,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
18183
18346
  if (minimumStakeRatio.length != 2) {
18184
18347
  throw Error("minimumStakeRatio should have 2 elements");
18185
18348
  }
18186
- const stakes = validators.map((v6) => BigInt(v6.stake)).sort(sortBigIntAsc);
18349
+ const stakes = validators.map((v4) => BigInt(v4.stake)).sort(sortBigIntAsc);
18187
18350
  const stakesSum = stakes.reduce((a, b) => a + b);
18188
18351
  if (validators.length < maxNumberOfSeats) {
18189
18352
  return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
@@ -18355,10 +18518,10 @@ var DER = {
18355
18518
  if (length < 128)
18356
18519
  throw new E("tlv.decode(long): not minimal encoding");
18357
18520
  }
18358
- const v6 = data.subarray(pos, pos + length);
18359
- if (v6.length !== length)
18521
+ const v4 = data.subarray(pos, pos + length);
18522
+ if (v4.length !== length)
18360
18523
  throw new E("tlv.decode: wrong value length");
18361
- return { v: v6, l: data.subarray(pos + length) };
18524
+ return { v: v4, l: data.subarray(pos + length) };
18362
18525
  }
18363
18526
  },
18364
18527
  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
@@ -18926,9 +19089,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
18926
19089
  extraEntropy: false
18927
19090
  };
18928
19091
  const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
18929
- function isBiggerThanHalfOrder(number4) {
19092
+ function isBiggerThanHalfOrder(number2) {
18930
19093
  const HALF = CURVE_ORDER >> _1n6;
18931
- return number4 > HALF;
19094
+ return number2 > HALF;
18932
19095
  }
18933
19096
  function validateRS(title, num) {
18934
19097
  if (!Fn.isValidNot0(num))
@@ -19111,8 +19274,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19111
19274
  const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
19112
19275
  if (R.is0())
19113
19276
  return false;
19114
- const v6 = Fn.create(R.x);
19115
- return v6 === r;
19277
+ const v4 = Fn.create(R.x);
19278
+ return v4 === r;
19116
19279
  } catch (e) {
19117
19280
  return false;
19118
19281
  }
@@ -22108,6 +22271,15 @@ var NearSpokeService = class {
22108
22271
  };
22109
22272
  }
22110
22273
  };
22274
+ function buildEvmRpcTransport(cfg) {
22275
+ const configured = (cfg.rpcUrls ?? []).map((url) => url.trim()).filter((url) => url.length > 0);
22276
+ const urls = [...new Set(configured.length > 0 ? configured : [cfg.rpcUrl])];
22277
+ const rpcOptions = cfg.rpcOptions?.rank && urls.length < 2 ? { ...cfg.rpcOptions, rank: false } : cfg.rpcOptions;
22278
+ return viem.fallback(
22279
+ urls.map((url) => viem.http(url)),
22280
+ rpcOptions
22281
+ );
22282
+ }
22111
22283
 
22112
22284
  // src/shared/types/intent-types.ts
22113
22285
  var IntentDataType = /* @__PURE__ */ ((IntentDataType2) => {
@@ -22570,7 +22742,7 @@ var SonicSpokeService = class {
22570
22742
  this.config = config;
22571
22743
  const chainConfig = config.getChainConfig(ChainKeys.SONIC_MAINNET);
22572
22744
  this.publicClient = viem.createPublicClient({
22573
- transport: viem.http(chainConfig.rpcUrl),
22745
+ transport: buildEvmRpcTransport(chainConfig),
22574
22746
  chain: getEvmViemChain(ChainKeys.SONIC_MAINNET)
22575
22747
  });
22576
22748
  this.pollingIntervalMs = chainConfig.pollingConfig.pollingIntervalMs;
@@ -26169,7 +26341,7 @@ var EvmHubProvider = class {
26169
26341
  hubAddressMap = /* @__PURE__ */ new Map();
26170
26342
  constructor({ config }) {
26171
26343
  this.publicClient = viem.createPublicClient({
26172
- transport: viem.http(config.sodaxConfig.hub.rpcUrl),
26344
+ transport: buildEvmRpcTransport(config.sodaxConfig.hub),
26173
26345
  chain: getEvmViemChain(config.sodaxConfig.hub.chain.key)
26174
26346
  });
26175
26347
  this.chainConfig = config.sodaxConfig.hub;
@@ -26434,6 +26606,7 @@ var POST_EXECUTION_ERROR_CODES = /* @__PURE__ */ new Set([
26434
26606
  "UNKNOWN"
26435
26607
  ]);
26436
26608
  var SWAP_ERROR_CODES = /* @__PURE__ */ new Set([
26609
+ "USER_REJECTED",
26437
26610
  "VALIDATION_FAILED",
26438
26611
  "INTENT_CREATION_FAILED",
26439
26612
  "TX_VERIFICATION_FAILED",
@@ -26760,7 +26933,7 @@ var SwapService = class {
26760
26933
  /**
26761
26934
  * Backend 2-step swap path (opt-in via `swapsOptions.useBackendSubmitTx`): hand the broadcast
26762
26935
  * intent tx to the swaps API (`POST /swaps/submit-tx`); the backend relays + post-executes
26763
- * server-side. Polls `getSubmitTxStatus` until `executed`, then reconstructs the same
26936
+ * server-side. Polls `getSubmitTxStatus` until `solved`, then reconstructs the same
26764
26937
  * {@link SwapResponse} the client-side path returns (`result.dstIntentTxHash` → delivery info,
26765
26938
  * `result.intent_hash` → solver response).
26766
26939
  *
@@ -26797,7 +26970,7 @@ var SwapService = class {
26797
26970
  const statusResult = await this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey });
26798
26971
  if (statusResult.ok) {
26799
26972
  const { status, result, failureReason, abandonedAt } = statusResult.value.data;
26800
- if (status === "executed" && result?.dstIntentTxHash && result.intent_hash) {
26973
+ if (status === "solved" && result?.dstIntentTxHash && result.intent_hash) {
26801
26974
  return {
26802
26975
  ok: true,
26803
26976
  value: {
@@ -26822,7 +26995,7 @@ var SwapService = class {
26822
26995
  }
26823
26996
  await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
26824
26997
  }
26825
- return submitTxFailed(new Error("backend submit-tx polling timed out before reaching executed"));
26998
+ return submitTxFailed(new Error("backend submit-tx polling timed out before reaching solved"));
26826
26999
  } catch (error) {
26827
27000
  return { ok: false, error: unknownFailed("swap", error, { ...baseCtx, action: "swap" }) };
26828
27001
  }
@@ -26893,6 +27066,7 @@ var SwapService = class {
26893
27066
  */
26894
27067
  async approve(_params) {
26895
27068
  const { params } = _params;
27069
+ const wrapApproveFailure = (cause) => approveFailed("swap", cause);
26896
27070
  try {
26897
27071
  if (isHubChainKeyType(params.srcChainKey) || isEvmSpokeOnlyChainKeyType(params.srcChainKey)) {
26898
27072
  invariant(
@@ -26913,7 +27087,7 @@ var SwapService = class {
26913
27087
  walletProvider: _params.walletProvider
26914
27088
  });
26915
27089
  if (!result.ok) {
26916
- return result;
27090
+ return { ok: false, error: wrapApproveFailure(result.error) };
26917
27091
  }
26918
27092
  return {
26919
27093
  ok: true,
@@ -26941,7 +27115,7 @@ var SwapService = class {
26941
27115
  walletProvider: _params.walletProvider
26942
27116
  }
26943
27117
  );
26944
- if (!result.ok) return result;
27118
+ if (!result.ok) return { ok: false, error: wrapApproveFailure(result.error) };
26945
27119
  return {
26946
27120
  ok: true,
26947
27121
  value: result.value
@@ -27234,13 +27408,14 @@ var SwapService = class {
27234
27408
  walletProvider: _params.walletProvider
27235
27409
  };
27236
27410
  const txResult = await this.spoke.sendMessage(sendMessageParams);
27237
- if (!txResult.ok) return txResult;
27411
+ if (!txResult.ok) return { ok: false, error: intentCreationFailed("swap", txResult.error) };
27238
27412
  return {
27239
27413
  ok: true,
27240
27414
  value: txResult.value
27241
27415
  };
27242
27416
  } catch (error) {
27243
- return { ok: false, error };
27417
+ if (isSwapCreateIntentError(error)) return { ok: false, error };
27418
+ return { ok: false, error: intentCreationFailed("swap", error) };
27244
27419
  }
27245
27420
  }
27246
27421
  /**
@@ -27294,7 +27469,8 @@ var SwapService = class {
27294
27469
  }
27295
27470
  return { ok: true, value: { srcChainTxHash: cancelTxHash, dstChainTxHash: dstIntentTxHash } };
27296
27471
  } catch (error) {
27297
- return { ok: false, error };
27472
+ if (isSwapError(error)) return { ok: false, error };
27473
+ return { ok: false, error: executionFailed("swap", error, { action: "cancelIntent" }) };
27298
27474
  }
27299
27475
  }
27300
27476
  /**
@@ -27479,6 +27655,7 @@ var SwapService = class {
27479
27655
  // src/migration/errors.ts
27480
27656
  var migrationInvariant = createInvariant("migration");
27481
27657
  var MIGRATE_ORCH_CODES = /* @__PURE__ */ new Set([
27658
+ "USER_REJECTED",
27482
27659
  "VALIDATION_FAILED",
27483
27660
  "INTENT_CREATION_FAILED",
27484
27661
  "TX_VERIFICATION_FAILED",
@@ -27489,6 +27666,7 @@ var MIGRATE_ORCH_CODES = /* @__PURE__ */ new Set([
27489
27666
  "UNKNOWN"
27490
27667
  ]);
27491
27668
  var REVERT_ORCH_CODES = /* @__PURE__ */ new Set([
27669
+ "USER_REJECTED",
27492
27670
  "VALIDATION_FAILED",
27493
27671
  "INTENT_CREATION_FAILED",
27494
27672
  "TX_SUBMIT_FAILED",
@@ -27498,6 +27676,7 @@ var REVERT_ORCH_CODES = /* @__PURE__ */ new Set([
27498
27676
  "UNKNOWN"
27499
27677
  ]);
27500
27678
  var MIGRATION_CODES = /* @__PURE__ */ new Set([
27679
+ "USER_REJECTED",
27501
27680
  "VALIDATION_FAILED",
27502
27681
  "INTENT_CREATION_FAILED",
27503
27682
  "TX_VERIFICATION_FAILED",
@@ -29550,7 +29729,6 @@ var MigrationService = class {
29550
29729
  };
29551
29730
 
29552
29731
  // src/backendApi/api-utils.ts
29553
- var toJsonBody = (value) => JSON.stringify(value, (_key, val) => typeof val === "bigint" ? val.toString() : val);
29554
29732
  async function makeRequest(params) {
29555
29733
  const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
29556
29734
  const baseURL = overrideConfig.baseURL || config.baseURL || "";
@@ -29586,227 +29764,7 @@ async function makeRequest(params) {
29586
29764
  throw new Error("UNKNOWN_REQUEST_ERROR", { cause: error });
29587
29765
  }
29588
29766
  }
29589
- var SwapTokenSchema = v4__namespace.object({
29590
- symbol: v4__namespace.string(),
29591
- name: v4__namespace.string(),
29592
- decimals: v4__namespace.number(),
29593
- address: v4__namespace.string(),
29594
- chainKey: v4__namespace.string(),
29595
- hubAsset: v4__namespace.string(),
29596
- vault: v4__namespace.string()
29597
- });
29598
- var IntentResponseSchema = v4__namespace.object({
29599
- intentId: v4__namespace.string(),
29600
- creator: v4__namespace.string(),
29601
- inputToken: v4__namespace.string(),
29602
- outputToken: v4__namespace.string(),
29603
- inputAmount: v4__namespace.string(),
29604
- minOutputAmount: v4__namespace.string(),
29605
- deadline: v4__namespace.string(),
29606
- allowPartialFill: v4__namespace.boolean(),
29607
- srcChain: v4__namespace.string(),
29608
- dstChain: v4__namespace.string(),
29609
- srcAddress: v4__namespace.string(),
29610
- dstAddress: v4__namespace.string(),
29611
- solver: v4__namespace.string(),
29612
- data: v4__namespace.string()
29613
- });
29614
- var RelayExtraDataResponseSchema = v4__namespace.object({
29615
- address: v4__namespace.string(),
29616
- payload: v4__namespace.string()
29617
- });
29618
- var makeCreateIntentResponseSchema = (txSchema) => v4__namespace.object({
29619
- tx: txSchema,
29620
- intent: IntentResponseSchema,
29621
- relayData: RelayExtraDataResponseSchema
29622
- });
29623
- var GetSwapTokensResponseSchema = v4__namespace.record(v4__namespace.string(), v4__namespace.array(SwapTokenSchema));
29624
- var GetSwapTokensByChainResponseSchema = v4__namespace.array(SwapTokenSchema);
29625
- var makeQuoteResponseSchema = (txSchema) => v4__namespace.object({
29626
- quotedAmount: v4__namespace.string(),
29627
- txData: v4__namespace.optional(makeCreateIntentResponseSchema(txSchema))
29628
- });
29629
- var DeadlineResponseSchema = v4__namespace.object({
29630
- deadline: v4__namespace.string()
29631
- });
29632
- var AllowanceCheckResponseSchema = v4__namespace.object({
29633
- valid: v4__namespace.boolean()
29634
- });
29635
- var makeApproveResponseSchema = (txSchema) => v4__namespace.object({ tx: txSchema });
29636
- var SubmitIntentResponseSchema = v4__namespace.object({
29637
- result: v4__namespace.unknown()
29638
- });
29639
- var StatusResponseSchema = v4__namespace.object({
29640
- status: v4__namespace.picklist([-1, 1, 2, 3, 4]),
29641
- fillTxHash: v4__namespace.optional(v4__namespace.string())
29642
- });
29643
- var makeCancelIntentResponseSchema = (txSchema) => v4__namespace.object({ tx: txSchema });
29644
- var IntentHashResponseSchema = v4__namespace.object({
29645
- hash: v4__namespace.string()
29646
- });
29647
- var IntentPacketResponseSchema = v4__namespace.object({
29648
- srcChainId: v4__namespace.number(),
29649
- srcTxHash: v4__namespace.string(),
29650
- srcAddress: v4__namespace.string(),
29651
- status: v4__namespace.string(),
29652
- dstChainId: v4__namespace.number(),
29653
- connSn: v4__namespace.number(),
29654
- dstAddress: v4__namespace.string(),
29655
- dstTxHash: v4__namespace.string(),
29656
- signatures: v4__namespace.array(v4__namespace.string()),
29657
- payload: v4__namespace.string()
29658
- });
29659
- var IntentStateResponseSchema = v4__namespace.object({
29660
- exists: v4__namespace.boolean(),
29661
- remainingInput: v4__namespace.string(),
29662
- receivedOutput: v4__namespace.string(),
29663
- pendingPayment: v4__namespace.boolean()
29664
- });
29665
- var GasEstimateResponseSchema = v4__namespace.object({
29666
- gas: v4__namespace.unknown()
29667
- });
29668
- var FeeResponseSchema = v4__namespace.object({
29669
- fee: v4__namespace.string()
29670
- });
29671
- var SubmitTxResponseSchema = v4__namespace.object({
29672
- success: v4__namespace.boolean(),
29673
- data: v4__namespace.object({
29674
- status: v4__namespace.picklist(["inserted", "duplicate"]),
29675
- message: v4__namespace.string()
29676
- })
29677
- });
29678
- var SubmitSwapTxStatusSchema = v4__namespace.picklist([
29679
- "pending",
29680
- "relaying",
29681
- "relayed",
29682
- "posting_execution",
29683
- "executed",
29684
- "failed"
29685
- ]);
29686
- var PacketDataSchema = v4__namespace.object({
29687
- src_chain_id: v4__namespace.number(),
29688
- src_tx_hash: v4__namespace.string(),
29689
- src_address: v4__namespace.string(),
29690
- status: v4__namespace.picklist(["pending", "validating", "executing", "executed"]),
29691
- dst_chain_id: v4__namespace.number(),
29692
- conn_sn: v4__namespace.number(),
29693
- dst_address: v4__namespace.string(),
29694
- dst_tx_hash: v4__namespace.string(),
29695
- signatures: v4__namespace.array(v4__namespace.string()),
29696
- payload: v4__namespace.string()
29697
- });
29698
- var SubmitTxStatusResultSchema = v4__namespace.object({
29699
- dstIntentTxHash: v4__namespace.string(),
29700
- packetData: v4__namespace.optional(PacketDataSchema),
29701
- intent_hash: v4__namespace.optional(v4__namespace.string())
29702
- });
29703
- var SubmitTxStatusDataSchema = v4__namespace.object({
29704
- txHash: v4__namespace.string(),
29705
- srcChainKey: v4__namespace.string(),
29706
- status: SubmitSwapTxStatusSchema,
29707
- failedAtStep: v4__namespace.optional(SubmitSwapTxStatusSchema),
29708
- failureReason: v4__namespace.optional(v4__namespace.string()),
29709
- processingAttempts: v4__namespace.number(),
29710
- abandonedAt: v4__namespace.optional(v4__namespace.string()),
29711
- result: v4__namespace.optional(SubmitTxStatusResultSchema),
29712
- userMessage: v4__namespace.optional(v4__namespace.string()),
29713
- intentCancelled: v4__namespace.optional(v4__namespace.boolean())
29714
- });
29715
- var SubmitTxStatusResponseSchema = v4__namespace.object({
29716
- success: v4__namespace.boolean(),
29717
- data: SubmitTxStatusDataSchema
29718
- });
29719
- var AddressSchema = v4__namespace.custom((input) => typeof input === "string");
29720
- var HexSchema = v4__namespace.custom((input) => typeof input === "string");
29721
- var BigintFromString = v4__namespace.pipe(v4__namespace.string(), v4__namespace.toBigint());
29722
- var BytesFromIndexRecord = v4__namespace.pipe(
29723
- v4__namespace.record(v4__namespace.string(), v4__namespace.number()),
29724
- v4__namespace.transform((indexed) => Uint8Array.from(Object.values(indexed)))
29725
- );
29726
- var EvmRawTxSchema = v4__namespace.object({
29727
- from: AddressSchema,
29728
- to: AddressSchema,
29729
- value: BigintFromString,
29730
- data: HexSchema
29731
- });
29732
- var SolanaRawTxSchema = v4__namespace.object({
29733
- from: v4__namespace.string(),
29734
- to: v4__namespace.string(),
29735
- value: BigintFromString,
29736
- data: v4__namespace.string()
29737
- });
29738
- var SuiRawTxSchema = v4__namespace.object({
29739
- from: HexSchema,
29740
- to: v4__namespace.string(),
29741
- value: BigintFromString,
29742
- data: v4__namespace.string()
29743
- });
29744
- var StellarRawTxSchema = v4__namespace.object({
29745
- from: v4__namespace.string(),
29746
- to: v4__namespace.string(),
29747
- value: BigintFromString,
29748
- data: v4__namespace.string()
29749
- });
29750
- var InjectiveRawTxSchema = v4__namespace.object({
29751
- from: HexSchema,
29752
- to: HexSchema,
29753
- signedDoc: v4__namespace.object({
29754
- bodyBytes: BytesFromIndexRecord,
29755
- authInfoBytes: BytesFromIndexRecord,
29756
- chainId: v4__namespace.string(),
29757
- accountNumber: BigintFromString
29758
- })
29759
- });
29760
- var NearRawTxSchema = v4__namespace.object({
29761
- signerId: v4__namespace.string(),
29762
- params: v4__namespace.object({
29763
- contractId: v4__namespace.string(),
29764
- method: v4__namespace.string(),
29765
- args: v4__namespace.custom((input) => typeof input === "object" && input !== null),
29766
- gas: v4__namespace.optional(BigintFromString),
29767
- deposit: v4__namespace.optional(BigintFromString)
29768
- })
29769
- });
29770
- var IconRawTxSchema = v4__namespace.record(
29771
- v4__namespace.string(),
29772
- v4__namespace.union([v4__namespace.string(), v4__namespace.custom((input) => typeof input === "object" && input !== null)])
29773
- );
29774
- var StacksRawTxSchema = v4__namespace.object({
29775
- payload: v4__namespace.string(),
29776
- estimatedLength: v4__namespace.optional(v4__namespace.number())
29777
- });
29778
- var AnyRawTxSchema = v4__namespace.custom((input) => typeof input === "object" && input !== null);
29779
- function rawTxSchemaForChainKey(chainKey) {
29780
- let chainType;
29781
- try {
29782
- chainType = getChainType(chainKey);
29783
- } catch {
29784
- chainType = void 0;
29785
- }
29786
- switch (chainType) {
29787
- case "EVM":
29788
- return EvmRawTxSchema;
29789
- case "SOLANA":
29790
- return SolanaRawTxSchema;
29791
- case "SUI":
29792
- return SuiRawTxSchema;
29793
- case "STELLAR":
29794
- return StellarRawTxSchema;
29795
- case "INJECTIVE":
29796
- return InjectiveRawTxSchema;
29797
- case "ICON":
29798
- return IconRawTxSchema;
29799
- case "STACKS":
29800
- return StacksRawTxSchema;
29801
- case "NEAR":
29802
- return NearRawTxSchema;
29803
- default:
29804
- return AnyRawTxSchema;
29805
- }
29806
- }
29807
-
29808
- // src/backendApi/SwapsApiService.ts
29809
- var SwapsApiService = class {
29767
+ var SwapsApiService = class _SwapsApiService {
29810
29768
  // Fully-resolved swaps-API config supplied by the caller (BackendApiService resolves the
29811
29769
  // `ApiConfig` union via `resolveSwapsApiConfig`); this service does not resolve the union.
29812
29770
  config;
@@ -29818,347 +29776,189 @@ var SwapsApiService = class {
29818
29776
  this.logger = logger;
29819
29777
  }
29820
29778
  /**
29821
- * Issues a single HTTP request, validates the JSON body against `schema`, and
29822
- * wraps the result in `Result<T>`. The service-level `baseURL`/`timeout`/
29823
- * `headers` are merged with the optional per-call `overrideConfig` (which takes
29824
- * precedence) inside {@link makeRequest}. Every public method delegates here.
29779
+ * Build a `@sodax/swaps-api` client for a single call. Maps the SDK's `SwapsApiConfig`
29780
+ * (`baseURL`/`timeout`/`headers`) to the package's config (`baseUrl`/`timeout`/`headers`), layering
29781
+ * the optional per-call `RequestOverrideConfig` on top (override wins per field; headers merge).
29782
+ * `timeout` falls back to the backend-API default so a config that omits it still gets a ceiling
29783
+ * rather than an unbounded request. Constructed per call so `setHeaders` mutations and per-call
29784
+ * overrides both take effect without caching stale state.
29825
29785
  */
29826
- async request(endpoint, config, schema, overrideConfig) {
29786
+ buildClient(overrideConfig) {
29787
+ const baseUrl = overrideConfig?.baseURL || this.config.baseURL;
29788
+ const timeout = overrideConfig?.timeout ?? this.config.timeout ?? DEFAULT_BACKEND_API_TIMEOUT;
29789
+ const headers = { ...this.headers, ...overrideConfig?.headers };
29790
+ return new swapsApi.SwapsApi({ baseUrl, headers, timeout });
29791
+ }
29792
+ /**
29793
+ * Run one delegated `SwapsApi` call and wrap it in `Result<T>`. A thrown `SwapsApiError`
29794
+ * (network/timeout/HTTP/parse/validation) becomes `{ ok: false }` with a canonical
29795
+ * `SodaxError<'EXTERNAL_API_ERROR'>`; the original error is kept as `cause`, and its
29796
+ * `code`/`status`/`issues` are projected into `context` so consumers can discriminate failure
29797
+ * kinds without unwrapping `cause`. Only a RESPONSE-shape validation failure is tagged
29798
+ * `reason: 'invalid_response_shape'` — a request-side validation error is a caller bug, not a
29799
+ * backend fault.
29800
+ */
29801
+ async toResult(endpoint, call, overrideConfig) {
29827
29802
  try {
29828
- const raw = await makeRequest({
29829
- endpoint,
29830
- config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
29831
- overrideConfig,
29832
- logger: this.logger,
29833
- serviceLabel: "SwapsApiService"
29834
- });
29835
- const parsed = v4__namespace.safeParse(schema, raw);
29836
- if (!parsed.success) {
29837
- return {
29838
- ok: false,
29839
- error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from swaps API for ${endpoint}`, {
29840
- feature: "backend",
29841
- context: { api: "swaps", endpoint, reason: "invalid_response_shape", issues: v4__namespace.flatten(parsed.issues) }
29842
- })
29843
- };
29844
- }
29845
- return { ok: true, value: parsed.output };
29803
+ const value = await call(this.buildClient(overrideConfig));
29804
+ return { ok: true, value };
29846
29805
  } catch (error) {
29806
+ const context = { api: "swaps", endpoint };
29807
+ if (error instanceof swapsApi.SwapsApiError) {
29808
+ context.code = error.code;
29809
+ if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
29810
+ context.reason = "invalid_response_shape";
29811
+ const issues = error.context.issues;
29812
+ context.issues = issues instanceof v2__namespace.ValiError ? v2__namespace.flatten(issues.issues) : issues;
29813
+ }
29814
+ if (error.context.status !== void 0) context.status = error.context.status;
29815
+ }
29816
+ this.logger.error(`[SwapsApiService] Request to ${endpoint} failed`, error);
29847
29817
  return {
29848
29818
  ok: false,
29849
29819
  error: new SodaxError(
29850
29820
  "EXTERNAL_API_ERROR",
29851
29821
  error instanceof Error ? error.message : `Request to ${endpoint} failed`,
29852
- {
29853
- feature: "backend",
29854
- cause: error,
29855
- context: { api: "swaps", endpoint }
29856
- }
29822
+ { feature: "backend", cause: error, context }
29857
29823
  )
29858
29824
  };
29859
29825
  }
29860
29826
  }
29827
+ /**
29828
+ * Drop the SDK-only display field `feeAmount` before an intent reaches the strict wire serializer.
29829
+ * `sodax.swaps.createIntent` returns `Intent & FeeAmount`, which is structurally assignable to the
29830
+ * wire `IntentRequestV2` and so gets passed straight into the intent-carrying endpoints; the extra
29831
+ * bigint would trip `serializeIntentRequest`. This is a no-op for an already-clean `IntentRequestV2`.
29832
+ */
29833
+ static toWireIntent(intent) {
29834
+ const { feeAmount: _feeAmount, ...rest } = intent;
29835
+ return rest;
29836
+ }
29861
29837
  // ──────────────────────────────────────────────────────────────────────
29862
29838
  // Tokens
29863
29839
  // ──────────────────────────────────────────────────────────────────────
29864
- /**
29865
- * Fetch all supported swap tokens grouped by SpokeChainKey.
29866
- *
29867
- * @returns `Result<GetSwapTokensResponseV2>` — map of chain key → token list.
29868
- */
29840
+ /** Fetch all supported swap tokens grouped by SpokeChainKey. */
29869
29841
  async getTokens(config) {
29870
- return this.request("/swaps/tokens", { method: "GET" }, GetSwapTokensResponseSchema, config);
29842
+ return this.toResult("/swaps/tokens", (c) => c.getTokens(), config);
29871
29843
  }
29872
- /**
29873
- * Fetch supported swap tokens for a single SpokeChainKey.
29874
- *
29875
- * @param chainKey - SODAX SpokeChainKey (e.g. `0xa4b1.arbitrum`, `solana`).
29876
- * @returns `Result<GetSwapTokensByChainResponseV2>` — token list for the chain.
29877
- */
29844
+ /** Fetch supported swap tokens for a single SpokeChainKey. */
29878
29845
  async getTokensByChain(chainKey, config) {
29879
- return this.request(
29880
- `/swaps/tokens/${chainKey}`,
29881
- { method: "GET" },
29882
- GetSwapTokensByChainResponseSchema,
29883
- config
29884
- );
29846
+ return this.toResult(`/swaps/tokens/${chainKey}`, (c) => c.getTokensByChain(chainKey), config);
29885
29847
  }
29886
29848
  // ──────────────────────────────────────────────────────────────────────
29887
29849
  // Quote · deadline
29888
29850
  // ──────────────────────────────────────────────────────────────────────
29889
29851
  /**
29890
- * Get a solver quote for a cross-chain swap.
29891
- *
29892
- * Pass `query.includeTxData = true` to also build an unsigned create-intent
29893
- * transaction (`txData`) using the quoted amount as `minOutputAmount`; in that
29894
- * case `srcAddress`/`dstAddress` are required in the body.
29895
- *
29896
- * @returns `Result<QuoteResponseV2>` — `quotedAmount` (decimal string) and optional `txData`.
29852
+ * Get a solver quote for a cross-chain swap. Pass `query.includeTxData = true` to also build an
29853
+ * unsigned create-intent transaction (`txData`); in that case `srcAddress`/`dstAddress` are required.
29897
29854
  */
29898
29855
  async getQuote(body, query, config) {
29899
- const endpoint = query?.includeTxData ? "/swaps/quote?includeTxData=true" : "/swaps/quote";
29900
- const txSchema = rawTxSchemaForChainKey(body.tokenSrcChainKey);
29901
- return this.request(
29902
- endpoint,
29903
- { method: "POST", body: toJsonBody(body) },
29904
- makeQuoteResponseSchema(txSchema),
29905
- config
29906
- );
29856
+ return this.toResult("/swaps/quote", (c) => c.getQuote(body, query), config);
29907
29857
  }
29908
- /**
29909
- * Compute a swap deadline (hub timestamp + `offsetSeconds`, default 300s).
29910
- *
29911
- * @returns `Result<DeadlineResponseV2>` — unix-seconds deadline (decimal string).
29912
- */
29858
+ /** Compute a swap deadline (hub timestamp + `offsetSeconds`, default 300s). */
29913
29859
  async getDeadline(query, config) {
29914
- const queryParams = new URLSearchParams();
29915
- if (query?.offsetSeconds !== void 0) queryParams.append("offsetSeconds", String(query.offsetSeconds));
29916
- const queryString = queryParams.toString();
29917
- const endpoint = queryString.length > 0 ? `/swaps/deadline?${queryString}` : "/swaps/deadline";
29918
- return this.request(endpoint, { method: "GET" }, DeadlineResponseSchema, config);
29860
+ return this.toResult("/swaps/deadline", (c) => c.getDeadline(query), config);
29919
29861
  }
29920
29862
  // ──────────────────────────────────────────────────────────────────────
29921
29863
  // Allowance · approve · create intent
29922
29864
  // ──────────────────────────────────────────────────────────────────────
29923
- /**
29924
- * Check whether the source token allowance is already sufficient for the intent.
29925
- *
29926
- * @returns `Result<AllowanceCheckResponseV2>` — `{ valid }`.
29927
- */
29865
+ /** Check whether the source token allowance is already sufficient for the intent. */
29928
29866
  async checkAllowance(body, config) {
29929
- return this.request(
29930
- "/swaps/allowance/check",
29931
- { method: "POST", body: toJsonBody(body) },
29932
- AllowanceCheckResponseSchema,
29933
- config
29934
- );
29867
+ return this.toResult("/swaps/allowance/check", (c) => c.checkAllowance(body), config);
29935
29868
  }
29936
- /**
29937
- * Build an unsigned token-approval transaction for the source token.
29938
- *
29939
- * @returns `Result<ApproveResponseV2>` — `{ tx }` (chain-specific unsigned tx).
29940
- */
29869
+ /** Build an unsigned token-approval transaction for the source token. */
29941
29870
  async approve(body, config) {
29942
- const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
29943
- return this.request(
29944
- "/swaps/approve",
29945
- { method: "POST", body: toJsonBody(body) },
29946
- makeApproveResponseSchema(txSchema),
29947
- config
29948
- );
29871
+ return this.toResult("/swaps/approve", (c) => c.approve(body), config);
29949
29872
  }
29950
- /**
29951
- * Build an unsigned create-intent transaction.
29952
- *
29953
- * @returns `Result<CreateIntentResponseV2>` — `{ tx, intent, relayData }`.
29954
- */
29873
+ /** Build an unsigned create-intent transaction. */
29955
29874
  async createIntent(body, config) {
29956
- const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
29957
- return this.request(
29958
- "/swaps/intents",
29959
- { method: "POST", body: toJsonBody(body) },
29960
- makeCreateIntentResponseSchema(txSchema),
29961
- config
29962
- );
29875
+ return this.toResult("/swaps/intents", (c) => c.createIntent(body), config);
29963
29876
  }
29964
29877
  // ──────────────────────────────────────────────────────────────────────
29965
29878
  // Intent lifecycle: submit · status · cancel · hash · packet · extra-data
29966
29879
  // ──────────────────────────────────────────────────────────────────────
29967
- /**
29968
- * Submit the broadcast intent tx to the relay.
29969
- *
29970
- * @returns `Result<SubmitIntentResponseV2>` — `{ result }` (opaque relay response).
29971
- */
29880
+ /** Submit the broadcast intent tx to the relay. */
29972
29881
  async submitIntent(body, config) {
29973
- return this.request(
29974
- "/swaps/intents/submit",
29975
- { method: "POST", body: toJsonBody(body) },
29976
- SubmitIntentResponseSchema,
29977
- config
29978
- );
29882
+ return this.toResult("/swaps/intents/submit", (c) => c.submitIntent(body), config);
29979
29883
  }
29980
- /**
29981
- * Poll the solver for intent execution status.
29982
- *
29983
- * @returns `Result<StatusResponseV2>` — `{ status, fillTxHash? }` (`fillTxHash` set when `status === 3`).
29984
- */
29884
+ /** Poll the solver for intent execution status. */
29985
29885
  async getStatus(body, config) {
29986
- return this.request(
29987
- "/swaps/intents/status",
29988
- { method: "POST", body: toJsonBody(body) },
29989
- StatusResponseSchema,
29990
- config
29991
- );
29886
+ return this.toResult("/swaps/intents/status", (c) => c.getStatus(body), config);
29992
29887
  }
29993
- /**
29994
- * Build an unsigned cancel-intent transaction. The `intent` field carries
29995
- * `bigint` numerics — {@link toJsonBody} serializes them to decimal strings.
29996
- *
29997
- * @returns `Result<CancelIntentResponseV2>` — `{ tx }`.
29998
- */
29888
+ /** Build an unsigned cancel-intent transaction (the `intent` bigint numerics serialize to strings). */
29999
29889
  async cancelIntent(body, config) {
30000
- const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
30001
- return this.request(
29890
+ return this.toResult(
30002
29891
  "/swaps/intents/cancel",
30003
- { method: "POST", body: toJsonBody(body) },
30004
- makeCancelIntentResponseSchema(txSchema),
29892
+ (c) => c.cancelIntent({ ...body, intent: _SwapsApiService.toWireIntent(body.intent) }),
30005
29893
  config
30006
29894
  );
30007
29895
  }
30008
- /**
30009
- * Compute the keccak256 hash of an Intent struct. The `intent` field carries
30010
- * `bigint` numerics — {@link toJsonBody} serializes them to decimal strings.
30011
- *
30012
- * @returns `Result<IntentHashResponseV2>` — `{ hash }`.
30013
- */
29896
+ /** Compute the keccak256 hash of an Intent struct (bigint numerics serialize to strings). */
30014
29897
  async getIntentHash(body, config) {
30015
- return this.request(
29898
+ return this.toResult(
30016
29899
  "/swaps/intents/hash",
30017
- { method: "POST", body: toJsonBody(body) },
30018
- IntentHashResponseSchema,
29900
+ (c) => c.getIntentHash({ ...body, intent: _SwapsApiService.toWireIntent(body.intent) }),
30019
29901
  config
30020
29902
  );
30021
29903
  }
30022
- /**
30023
- * Long-poll the relayer until the fill packet lands on the destination chain.
30024
- *
30025
- * @returns `Result<IntentPacketResponseV2>` — delivered packet data.
30026
- */
29904
+ /** Long-poll the relayer until the fill packet lands on the destination chain. */
30027
29905
  async getSolvedIntentPacket(body, config) {
30028
- return this.request(
30029
- "/swaps/intents/packet",
30030
- { method: "POST", body: toJsonBody(body) },
30031
- IntentPacketResponseSchema,
30032
- config
30033
- );
29906
+ return this.toResult("/swaps/intents/packet", (c) => c.getSolvedIntentPacket(body), config);
30034
29907
  }
30035
- /**
30036
- * Recover the relay extra data needed by `/swaps/intents/submit`. Provide
30037
- * EITHER `txHash` OR `intent` (whose `bigint` numerics {@link toJsonBody} serializes).
30038
- *
30039
- * @returns `Result<IntentExtraDataResponseV2>` — `{ address, payload }`.
30040
- */
29908
+ /** Recover the relay extra data needed by `/swaps/intents/submit` (provide EITHER `txHash` OR `intent`). */
30041
29909
  async getIntentSubmitTxExtraData(body, config) {
30042
- return this.request(
30043
- "/swaps/intents/extra-data",
30044
- { method: "POST", body: toJsonBody(body) },
30045
- RelayExtraDataResponseSchema,
30046
- config
30047
- );
29910
+ const normalized = body.intent ? { ...body, intent: _SwapsApiService.toWireIntent(body.intent) } : body;
29911
+ return this.toResult("/swaps/intents/extra-data", (c) => c.getIntentSubmitTxExtraData(normalized), config);
30048
29912
  }
30049
- /**
30050
- * Get the on-chain fill state for an intent by its hub-chain tx hash.
30051
- *
30052
- * @returns `Result<IntentStateV2>` — `{ exists, remainingInput, receivedOutput, pendingPayment }`.
30053
- */
29913
+ /** Get the on-chain fill state for an intent by its hub-chain tx hash. */
30054
29914
  async getFilledIntent(txHash, config) {
30055
- return this.request(`/swaps/intents/${txHash}/fill`, { method: "GET" }, IntentStateResponseSchema, config);
29915
+ return this.toResult(`/swaps/intents/${txHash}/fill`, (c) => c.getFilledIntent(txHash), config);
30056
29916
  }
30057
- /**
30058
- * Look up an Intent struct by its hub-chain creation tx hash.
30059
- *
30060
- * @returns `Result<GetIntentResponseV2>` — the decoded intent (bigint fields as decimal strings).
30061
- */
29917
+ /** Look up an Intent struct by its hub-chain creation tx hash. */
30062
29918
  async getIntent(txHash, config) {
30063
- return this.request(`/swaps/intents/${txHash}`, { method: "GET" }, IntentResponseSchema, config);
29919
+ return this.toResult(`/swaps/intents/${txHash}`, (c) => c.getIntent(txHash), config);
30064
29920
  }
30065
29921
  // ──────────────────────────────────────────────────────────────────────
30066
29922
  // Limit orders · gas · fees
30067
29923
  // ──────────────────────────────────────────────────────────────────────
30068
- /**
30069
- * Build an unsigned create-limit-order-intent transaction (same as create-intent
30070
- * but `deadline` is optional).
30071
- *
30072
- * @returns `Result<CreateLimitOrderResponseV2>` — `{ tx, intent, relayData }`.
30073
- */
29924
+ /** Build an unsigned create-limit-order-intent transaction (create-intent with optional `deadline`). */
30074
29925
  async createLimitOrderIntent(body, config) {
30075
- const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
30076
- return this.request(
30077
- "/swaps/limit-orders",
30078
- { method: "POST", body: toJsonBody(body) },
30079
- makeCreateIntentResponseSchema(txSchema),
30080
- config
30081
- );
29926
+ return this.toResult("/swaps/limit-orders", (c) => c.createLimitOrderIntent(body), config);
30082
29927
  }
30083
- /**
30084
- * Estimate gas for a raw transaction on a spoke chain.
30085
- *
30086
- * @returns `Result<GasEstimateResponseV2>` — `{ gas }` (chain-specific shape).
30087
- */
29928
+ /** Estimate gas for a raw transaction on a spoke chain (bigint `tx` numerics serialize to strings). */
30088
29929
  async estimateGas(body, config) {
30089
- return this.request(
30090
- "/swaps/gas/estimate",
30091
- { method: "POST", body: toJsonBody(body) },
30092
- GasEstimateResponseSchema,
30093
- config
30094
- );
29930
+ return this.toResult("/swaps/gas/estimate", (c) => c.estimateGas(body), config);
30095
29931
  }
30096
- /**
30097
- * Compute the partner fee for a given input amount.
30098
- *
30099
- * @returns `Result<FeeResponseV2>` — `{ fee }` (decimal string).
30100
- */
29932
+ /** Compute the partner fee for a given input amount. */
30101
29933
  async getPartnerFee(query, config) {
30102
- const queryParams = new URLSearchParams({ amount: query.amount });
30103
- return this.request(
30104
- `/swaps/fees/partner?${queryParams.toString()}`,
30105
- { method: "GET" },
30106
- FeeResponseSchema,
30107
- config
30108
- );
29934
+ return this.toResult("/swaps/fees/partner", (c) => c.getPartnerFee(query), config);
30109
29935
  }
30110
- /**
30111
- * Compute the protocol (solver) fee for a given input amount.
30112
- *
30113
- * @returns `Result<FeeResponseV2>` — `{ fee }` (decimal string).
30114
- */
29936
+ /** Compute the protocol (solver) fee for a given input amount. */
30115
29937
  async getSolverFee(query, config) {
30116
- const queryParams = new URLSearchParams({ amount: query.amount });
30117
- return this.request(
30118
- `/swaps/fees/solver?${queryParams.toString()}`,
30119
- { method: "GET" },
30120
- FeeResponseSchema,
30121
- config
30122
- );
29938
+ return this.toResult("/swaps/fees/solver", (c) => c.getSolverFee(query), config);
30123
29939
  }
30124
29940
  // ──────────────────────────────────────────────────────────────────────
30125
29941
  // Submit-tx state machine
30126
29942
  // ──────────────────────────────────────────────────────────────────────
30127
- /**
30128
- * Submit a swap transaction to be processed (relay, post-execution, etc.). The
30129
- * `intent` field carries `bigint` numerics — {@link toJsonBody} serializes them.
30130
- * Idempotent on `(txHash, srcChainKey)`.
30131
- *
30132
- * @returns `Result<SubmitTxResponseV2>` — `{ success, data: { status, message } }`.
30133
- */
29943
+ /** Submit a swap transaction to be processed (relay, post-execution, etc.). Idempotent on `(txHash, srcChainKey)`. */
30134
29944
  async submitTx(body, config) {
30135
- return this.request(
29945
+ return this.toResult(
30136
29946
  "/swaps/submit-tx",
30137
- { method: "POST", body: toJsonBody(body) },
30138
- SubmitTxResponseSchema,
29947
+ (c) => c.submitTx({ ...body, intent: _SwapsApiService.toWireIntent(body.intent) }),
30139
29948
  config
30140
29949
  );
30141
29950
  }
30142
- /**
30143
- * Get the processing status of a submitted swap transaction by `(txHash, srcChainKey)`.
30144
- *
30145
- * @returns `Result<SubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
30146
- */
29951
+ /** Get the processing status of a submitted swap transaction by `(txHash, srcChainKey)`. */
30147
29952
  async getSubmitTxStatus(query, config) {
30148
- const queryParams = new URLSearchParams({ txHash: query.txHash, srcChainKey: query.srcChainKey });
30149
- return this.request(
30150
- `/swaps/submit-tx/status?${queryParams.toString()}`,
30151
- { method: "GET" },
30152
- SubmitTxStatusResponseSchema,
30153
- config
30154
- );
29953
+ return this.toResult("/swaps/submit-tx/status", (c) => c.getSubmitTxStatus(query), config);
30155
29954
  }
30156
29955
  // ──────────────────────────────────────────────────────────────────────
30157
29956
  // Utilities (parity with BackendApiService)
30158
29957
  // ──────────────────────────────────────────────────────────────────────
30159
29958
  /**
30160
29959
  * Merge additional headers into the service's default header set. Existing
30161
- * keys are overwritten; keys absent from `headers` are preserved.
29960
+ * keys are overwritten; keys absent from `headers` are preserved. Applied to
29961
+ * every subsequent call (the delegated client is rebuilt per call).
30162
29962
  */
30163
29963
  setHeaders(headers) {
30164
29964
  Object.entries(headers).forEach(([key, value]) => {
@@ -30201,137 +30001,137 @@ function resolveSwapsApiConfig(config) {
30201
30001
  }
30202
30002
  return layerConfigs(config);
30203
30003
  }
30204
- var ChainKeySchema = v4__namespace.custom((input) => typeof input === "string");
30205
- var SpokeChainKeySchema = v4__namespace.custom((input) => typeof input === "string");
30206
- var AddressSchema2 = v4__namespace.custom((input) => typeof input === "string");
30207
- var XTokenSchema = v4__namespace.object({
30208
- symbol: v4__namespace.string(),
30209
- name: v4__namespace.string(),
30210
- decimals: v4__namespace.number(),
30211
- address: v4__namespace.string(),
30004
+ var ChainKeySchema = v2__namespace.custom((input) => typeof input === "string");
30005
+ var SpokeChainKeySchema = v2__namespace.custom((input) => typeof input === "string");
30006
+ var AddressSchema = v2__namespace.custom((input) => typeof input === "string");
30007
+ var XTokenSchema = v2__namespace.object({
30008
+ symbol: v2__namespace.string(),
30009
+ name: v2__namespace.string(),
30010
+ decimals: v2__namespace.number(),
30011
+ address: v2__namespace.string(),
30212
30012
  chainKey: ChainKeySchema,
30213
- hubAsset: AddressSchema2,
30214
- vault: AddressSchema2,
30215
- access: v4__namespace.optional(v4__namespace.picklist(["withdrawOnly", "depositOnly"]))
30013
+ hubAsset: AddressSchema,
30014
+ vault: AddressSchema,
30015
+ access: v2__namespace.optional(v2__namespace.picklist(["withdrawOnly", "depositOnly"]))
30216
30016
  });
30217
- var IntentStructSchema = v4__namespace.object({
30218
- intentId: v4__namespace.string(),
30219
- creator: v4__namespace.string(),
30220
- inputToken: v4__namespace.string(),
30221
- outputToken: v4__namespace.string(),
30222
- inputAmount: v4__namespace.string(),
30223
- minOutputAmount: v4__namespace.string(),
30224
- deadline: v4__namespace.string(),
30225
- allowPartialFill: v4__namespace.boolean(),
30226
- srcChain: v4__namespace.number(),
30227
- dstChain: v4__namespace.number(),
30228
- srcAddress: v4__namespace.string(),
30229
- dstAddress: v4__namespace.string(),
30230
- solver: v4__namespace.string(),
30231
- data: v4__namespace.string()
30017
+ var IntentStructSchema = v2__namespace.object({
30018
+ intentId: v2__namespace.string(),
30019
+ creator: v2__namespace.string(),
30020
+ inputToken: v2__namespace.string(),
30021
+ outputToken: v2__namespace.string(),
30022
+ inputAmount: v2__namespace.string(),
30023
+ minOutputAmount: v2__namespace.string(),
30024
+ deadline: v2__namespace.string(),
30025
+ allowPartialFill: v2__namespace.boolean(),
30026
+ srcChain: v2__namespace.number(),
30027
+ dstChain: v2__namespace.number(),
30028
+ srcAddress: v2__namespace.string(),
30029
+ dstAddress: v2__namespace.string(),
30030
+ solver: v2__namespace.string(),
30031
+ data: v2__namespace.string()
30232
30032
  });
30233
- var IntentResponseSchema2 = v4__namespace.object({
30234
- intentHash: v4__namespace.string(),
30235
- txHash: v4__namespace.string(),
30236
- logIndex: v4__namespace.number(),
30237
- chainId: v4__namespace.number(),
30238
- blockNumber: v4__namespace.number(),
30239
- open: v4__namespace.boolean(),
30033
+ var IntentResponseSchema = v2__namespace.object({
30034
+ intentHash: v2__namespace.string(),
30035
+ txHash: v2__namespace.string(),
30036
+ logIndex: v2__namespace.number(),
30037
+ chainId: v2__namespace.number(),
30038
+ blockNumber: v2__namespace.number(),
30039
+ open: v2__namespace.boolean(),
30240
30040
  intent: IntentStructSchema,
30241
- events: v4__namespace.array(v4__namespace.unknown())
30041
+ events: v2__namespace.array(v2__namespace.unknown())
30242
30042
  });
30243
- var UserIntentsResponseSchema = v4__namespace.object({
30244
- total: v4__namespace.number(),
30245
- offset: v4__namespace.number(),
30246
- limit: v4__namespace.number(),
30247
- items: v4__namespace.array(IntentResponseSchema2)
30043
+ var UserIntentsResponseSchema = v2__namespace.object({
30044
+ total: v2__namespace.number(),
30045
+ offset: v2__namespace.number(),
30046
+ limit: v2__namespace.number(),
30047
+ items: v2__namespace.array(IntentResponseSchema)
30248
30048
  });
30249
- var OrderbookResponseSchema = v4__namespace.object({
30250
- total: v4__namespace.number(),
30251
- data: v4__namespace.array(
30252
- v4__namespace.object({
30253
- intentState: v4__namespace.object({
30254
- exists: v4__namespace.boolean(),
30255
- remainingInput: v4__namespace.string(),
30256
- receivedOutput: v4__namespace.string(),
30257
- pendingPayment: v4__namespace.boolean()
30049
+ var OrderbookResponseSchema = v2__namespace.object({
30050
+ total: v2__namespace.number(),
30051
+ data: v2__namespace.array(
30052
+ v2__namespace.object({
30053
+ intentState: v2__namespace.object({
30054
+ exists: v2__namespace.boolean(),
30055
+ remainingInput: v2__namespace.string(),
30056
+ receivedOutput: v2__namespace.string(),
30057
+ pendingPayment: v2__namespace.boolean()
30258
30058
  }),
30259
- intentData: v4__namespace.object({
30260
- intentId: v4__namespace.string(),
30261
- creator: v4__namespace.string(),
30262
- inputToken: v4__namespace.string(),
30263
- outputToken: v4__namespace.string(),
30264
- inputAmount: v4__namespace.string(),
30265
- minOutputAmount: v4__namespace.string(),
30266
- deadline: v4__namespace.string(),
30267
- allowPartialFill: v4__namespace.boolean(),
30268
- srcChain: v4__namespace.number(),
30269
- dstChain: v4__namespace.number(),
30270
- srcAddress: v4__namespace.string(),
30271
- dstAddress: v4__namespace.string(),
30272
- solver: v4__namespace.string(),
30273
- data: v4__namespace.string(),
30274
- intentHash: v4__namespace.string(),
30275
- txHash: v4__namespace.string(),
30276
- blockNumber: v4__namespace.number()
30059
+ intentData: v2__namespace.object({
30060
+ intentId: v2__namespace.string(),
30061
+ creator: v2__namespace.string(),
30062
+ inputToken: v2__namespace.string(),
30063
+ outputToken: v2__namespace.string(),
30064
+ inputAmount: v2__namespace.string(),
30065
+ minOutputAmount: v2__namespace.string(),
30066
+ deadline: v2__namespace.string(),
30067
+ allowPartialFill: v2__namespace.boolean(),
30068
+ srcChain: v2__namespace.number(),
30069
+ dstChain: v2__namespace.number(),
30070
+ srcAddress: v2__namespace.string(),
30071
+ dstAddress: v2__namespace.string(),
30072
+ solver: v2__namespace.string(),
30073
+ data: v2__namespace.string(),
30074
+ intentHash: v2__namespace.string(),
30075
+ txHash: v2__namespace.string(),
30076
+ blockNumber: v2__namespace.number()
30277
30077
  })
30278
30078
  })
30279
30079
  )
30280
30080
  });
30281
- var MoneyMarketPositionSchema = v4__namespace.object({
30282
- userAddress: v4__namespace.string(),
30283
- positions: v4__namespace.array(
30284
- v4__namespace.object({
30285
- reserveAddress: v4__namespace.string(),
30286
- aTokenAddress: v4__namespace.string(),
30287
- variableDebtTokenAddress: v4__namespace.string(),
30288
- aTokenBalance: v4__namespace.string(),
30289
- variableDebtTokenBalance: v4__namespace.string(),
30290
- blockNumber: v4__namespace.number()
30081
+ var MoneyMarketPositionSchema = v2__namespace.object({
30082
+ userAddress: v2__namespace.string(),
30083
+ positions: v2__namespace.array(
30084
+ v2__namespace.object({
30085
+ reserveAddress: v2__namespace.string(),
30086
+ aTokenAddress: v2__namespace.string(),
30087
+ variableDebtTokenAddress: v2__namespace.string(),
30088
+ aTokenBalance: v2__namespace.string(),
30089
+ variableDebtTokenBalance: v2__namespace.string(),
30090
+ blockNumber: v2__namespace.number()
30291
30091
  })
30292
30092
  )
30293
30093
  });
30294
- var MoneyMarketAssetSchema = v4__namespace.object({
30295
- reserveAddress: v4__namespace.string(),
30296
- aTokenAddress: v4__namespace.string(),
30297
- totalATokenBalance: v4__namespace.string(),
30298
- variableDebtTokenAddress: v4__namespace.string(),
30299
- totalVariableDebtTokenBalance: v4__namespace.string(),
30300
- liquidityRate: v4__namespace.string(),
30301
- symbol: v4__namespace.string(),
30302
- totalSuppliers: v4__namespace.number(),
30303
- totalBorrowers: v4__namespace.number(),
30304
- variableBorrowRate: v4__namespace.string(),
30305
- stableBorrowRate: v4__namespace.string(),
30306
- liquidityIndex: v4__namespace.string(),
30307
- variableBorrowIndex: v4__namespace.string(),
30308
- blockNumber: v4__namespace.number()
30094
+ var MoneyMarketAssetSchema = v2__namespace.object({
30095
+ reserveAddress: v2__namespace.string(),
30096
+ aTokenAddress: v2__namespace.string(),
30097
+ totalATokenBalance: v2__namespace.string(),
30098
+ variableDebtTokenAddress: v2__namespace.string(),
30099
+ totalVariableDebtTokenBalance: v2__namespace.string(),
30100
+ liquidityRate: v2__namespace.string(),
30101
+ symbol: v2__namespace.string(),
30102
+ totalSuppliers: v2__namespace.number(),
30103
+ totalBorrowers: v2__namespace.number(),
30104
+ variableBorrowRate: v2__namespace.string(),
30105
+ stableBorrowRate: v2__namespace.string(),
30106
+ liquidityIndex: v2__namespace.string(),
30107
+ variableBorrowIndex: v2__namespace.string(),
30108
+ blockNumber: v2__namespace.number()
30309
30109
  });
30310
- var MoneyMarketAssetsSchema = v4__namespace.array(MoneyMarketAssetSchema);
30311
- var MoneyMarketAssetBorrowersSchema = v4__namespace.object({
30312
- borrowers: v4__namespace.array(v4__namespace.string()),
30313
- total: v4__namespace.number(),
30314
- offset: v4__namespace.number(),
30315
- limit: v4__namespace.number()
30110
+ var MoneyMarketAssetsSchema = v2__namespace.array(MoneyMarketAssetSchema);
30111
+ var MoneyMarketAssetBorrowersSchema = v2__namespace.object({
30112
+ borrowers: v2__namespace.array(v2__namespace.string()),
30113
+ total: v2__namespace.number(),
30114
+ offset: v2__namespace.number(),
30115
+ limit: v2__namespace.number()
30316
30116
  });
30317
- var MoneyMarketAssetSuppliersSchema = v4__namespace.object({
30318
- suppliers: v4__namespace.array(v4__namespace.string()),
30319
- total: v4__namespace.number(),
30320
- offset: v4__namespace.number(),
30321
- limit: v4__namespace.number()
30117
+ var MoneyMarketAssetSuppliersSchema = v2__namespace.object({
30118
+ suppliers: v2__namespace.array(v2__namespace.string()),
30119
+ total: v2__namespace.number(),
30120
+ offset: v2__namespace.number(),
30121
+ limit: v2__namespace.number()
30322
30122
  });
30323
- var MoneyMarketBorrowersSchema = v4__namespace.object({
30324
- borrowers: v4__namespace.array(v4__namespace.string()),
30325
- total: v4__namespace.number(),
30326
- offset: v4__namespace.number(),
30327
- limit: v4__namespace.number()
30123
+ var MoneyMarketBorrowersSchema = v2__namespace.object({
30124
+ borrowers: v2__namespace.array(v2__namespace.string()),
30125
+ total: v2__namespace.number(),
30126
+ offset: v2__namespace.number(),
30127
+ limit: v2__namespace.number()
30328
30128
  });
30329
- var GetChainsResponseSchema = v4__namespace.array(SpokeChainKeySchema);
30330
- var TokensByChainMapSchema = v4__namespace.custom(
30331
- (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v4__namespace.is(XTokenSchema, t)))
30129
+ var GetChainsResponseSchema = v2__namespace.array(SpokeChainKeySchema);
30130
+ var TokensByChainMapSchema = v2__namespace.custom(
30131
+ (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v2__namespace.is(XTokenSchema, t)))
30332
30132
  );
30333
- var TokensListSchema = v4__namespace.array(XTokenSchema);
30334
- var ReserveAssetsSchema = v4__namespace.array(AddressSchema2);
30133
+ var TokensListSchema = v2__namespace.array(XTokenSchema);
30134
+ var ReserveAssetsSchema = v2__namespace.array(AddressSchema);
30335
30135
 
30336
30136
  // src/backendApi/BackendApiService.ts
30337
30137
  var BackendApiService = class {
@@ -30393,13 +30193,13 @@ var BackendApiService = class {
30393
30193
  logger: this.logger,
30394
30194
  serviceLabel: "BackendApiService"
30395
30195
  });
30396
- const parsed = v4__namespace.safeParse(schema, raw);
30196
+ const parsed = v2__namespace.safeParse(schema, raw);
30397
30197
  if (!parsed.success) {
30398
30198
  return {
30399
30199
  ok: false,
30400
30200
  error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from backend API for ${endpoint}`, {
30401
30201
  feature: "backend",
30402
- context: { api: "backend", endpoint, reason: "invalid_response_shape", issues: v4__namespace.flatten(parsed.issues) }
30202
+ context: { api: "backend", endpoint, reason: "invalid_response_shape", issues: v2__namespace.flatten(parsed.issues) }
30403
30203
  })
30404
30204
  };
30405
30205
  }
@@ -30440,7 +30240,7 @@ var BackendApiService = class {
30440
30240
  * open/closed state, token amounts, and any fill events.
30441
30241
  */
30442
30242
  async getIntentByTxHash(txHash, config) {
30443
- return this.request(`/intent/tx/${txHash}`, { ...config, method: "GET" }, IntentResponseSchema2);
30243
+ return this.request(`/intent/tx/${txHash}`, { ...config, method: "GET" }, IntentResponseSchema);
30444
30244
  }
30445
30245
  /**
30446
30246
  * Fetch a swap intent by its canonical intent hash.
@@ -30449,7 +30249,7 @@ var BackendApiService = class {
30449
30249
  * @returns `Result<IntentResponse>` — on success, the full intent details.
30450
30250
  */
30451
30251
  async getIntentByHash(intentHash, config) {
30452
- return this.request(`/intent/${intentHash}`, { ...config, method: "GET" }, IntentResponseSchema2);
30252
+ return this.request(`/intent/${intentHash}`, { ...config, method: "GET" }, IntentResponseSchema);
30453
30253
  }
30454
30254
  // Solver endpoints
30455
30255
  /**
@@ -30749,6 +30549,7 @@ var BackendApiService = class {
30749
30549
  // src/bridge/errors.ts
30750
30550
  var bridgeInvariant = createInvariant("bridge");
30751
30551
  var ORCHESTRATION_CODES = /* @__PURE__ */ new Set([
30552
+ "USER_REJECTED",
30752
30553
  "VALIDATION_FAILED",
30753
30554
  "INTENT_CREATION_FAILED",
30754
30555
  "TX_VERIFICATION_FAILED",
@@ -30759,6 +30560,7 @@ var ORCHESTRATION_CODES = /* @__PURE__ */ new Set([
30759
30560
  "UNKNOWN"
30760
30561
  ]);
30761
30562
  var BRIDGE_CODES = /* @__PURE__ */ new Set([
30563
+ "USER_REJECTED",
30762
30564
  "VALIDATION_FAILED",
30763
30565
  "INTENT_CREATION_FAILED",
30764
30566
  "TX_VERIFICATION_FAILED",
@@ -31835,6 +31637,7 @@ var StakingLogic = class _StakingLogic {
31835
31637
  // src/staking/errors.ts
31836
31638
  var stakingInvariant = createInvariant("staking");
31837
31639
  var STAKE_ORCHESTRATION_CODES = /* @__PURE__ */ new Set([
31640
+ "USER_REJECTED",
31838
31641
  "VALIDATION_FAILED",
31839
31642
  "INTENT_CREATION_FAILED",
31840
31643
  "TX_VERIFICATION_FAILED",
@@ -31845,6 +31648,7 @@ var STAKE_ORCHESTRATION_CODES = /* @__PURE__ */ new Set([
31845
31648
  "UNKNOWN"
31846
31649
  ]);
31847
31650
  var STAKING_ORCHESTRATION_CODES = /* @__PURE__ */ new Set([
31651
+ "USER_REJECTED",
31848
31652
  "VALIDATION_FAILED",
31849
31653
  "INTENT_CREATION_FAILED",
31850
31654
  "TX_SUBMIT_FAILED",
@@ -31854,6 +31658,7 @@ var STAKING_ORCHESTRATION_CODES = /* @__PURE__ */ new Set([
31854
31658
  "UNKNOWN"
31855
31659
  ]);
31856
31660
  var STAKING_CODES = /* @__PURE__ */ new Set([
31661
+ "USER_REJECTED",
31857
31662
  "VALIDATION_FAILED",
31858
31663
  "INTENT_CREATION_FAILED",
31859
31664
  "TX_VERIFICATION_FAILED",
@@ -33157,6 +32962,14 @@ var StakingService = class {
33157
32962
  });
33158
32963
  }
33159
32964
  };
32965
+
32966
+ // src/dex/errors.ts
32967
+ var dexInvariant = createInvariant("dex");
32968
+ var isDexError = isCodeMember(LOOKUP_CODES);
32969
+ var isDexCreateIntentError = isCodeMember(CREATE_INTENT_CODES);
32970
+ var isDexApproveError = isCodeMember(APPROVE_CODES);
32971
+
32972
+ // src/dex/AssetService.ts
33160
32973
  var AssetService = class {
33161
32974
  relayerApiEndpoint;
33162
32975
  hubProvider;
@@ -33262,7 +33075,7 @@ var AssetService = class {
33262
33075
  walletProvider: _params.walletProvider
33263
33076
  }
33264
33077
  );
33265
- if (!result.ok) return result;
33078
+ if (!result.ok) return { ok: false, error: approveFailed("dex", result.error) };
33266
33079
  return {
33267
33080
  ok: true,
33268
33081
  value: result.value
@@ -33287,23 +33100,16 @@ var AssetService = class {
33287
33100
  raw: _params.raw,
33288
33101
  walletProvider: _params.walletProvider
33289
33102
  });
33290
- if (!result.ok) {
33291
- return result;
33292
- }
33103
+ if (!result.ok) return { ok: false, error: approveFailed("dex", result.error) };
33293
33104
  return {
33294
33105
  ok: true,
33295
33106
  value: result.value
33296
33107
  };
33297
33108
  }
33298
- return {
33299
- ok: false,
33300
- error: new Error("Approve only supported for EVM/Stellar spoke chains")
33301
- };
33109
+ dexInvariant(false, "Approve only supported for EVM/Stellar spoke chains");
33302
33110
  } catch (error) {
33303
- return {
33304
- ok: false,
33305
- error
33306
- };
33111
+ if (isDexApproveError(error)) return { ok: false, error };
33112
+ return { ok: false, error: approveFailed("dex", error) };
33307
33113
  }
33308
33114
  }
33309
33115
  /**
@@ -33361,12 +33167,7 @@ var AssetService = class {
33361
33167
  walletProvider: _params.walletProvider
33362
33168
  }
33363
33169
  );
33364
- if (!txResult.ok) {
33365
- return {
33366
- ok: false,
33367
- error: txResult.error
33368
- };
33369
- }
33170
+ if (!txResult.ok) return { ok: false, error: intentCreationFailed("dex", txResult.error) };
33370
33171
  return {
33371
33172
  ok: true,
33372
33173
  value: {
@@ -33375,10 +33176,8 @@ var AssetService = class {
33375
33176
  }
33376
33177
  };
33377
33178
  } catch (error) {
33378
- return {
33379
- ok: false,
33380
- error
33381
- };
33179
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33180
+ return { ok: false, error: intentCreationFailed("dex", error) };
33382
33181
  }
33383
33182
  }
33384
33183
  /**
@@ -33436,12 +33235,7 @@ var AssetService = class {
33436
33235
  walletProvider: _params.walletProvider
33437
33236
  };
33438
33237
  const txResult = await this.spoke.sendMessage(sendMessageParams);
33439
- if (!txResult.ok) {
33440
- return {
33441
- ok: false,
33442
- error: txResult.error
33443
- };
33444
- }
33238
+ if (!txResult.ok) return { ok: false, error: intentCreationFailed("dex", txResult.error) };
33445
33239
  return {
33446
33240
  ok: true,
33447
33241
  value: {
@@ -33450,10 +33244,8 @@ var AssetService = class {
33450
33244
  }
33451
33245
  };
33452
33246
  } catch (error) {
33453
- return {
33454
- ok: false,
33455
- error
33456
- };
33247
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33248
+ return { ok: false, error: intentCreationFailed("dex", error) };
33457
33249
  }
33458
33250
  }
33459
33251
  /**
@@ -33515,7 +33307,8 @@ var AssetService = class {
33515
33307
  }
33516
33308
  return { ok: true, value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: hubTxHash } };
33517
33309
  } catch (error) {
33518
- return { ok: false, error };
33310
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33311
+ return { ok: false, error: intentCreationFailed("dex", error) };
33519
33312
  }
33520
33313
  }
33521
33314
  /**
@@ -33551,7 +33344,8 @@ var AssetService = class {
33551
33344
  }
33552
33345
  return { ok: true, value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: hubTxHash } };
33553
33346
  } catch (error) {
33554
- return { ok: false, error };
33347
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33348
+ return { ok: false, error: intentCreationFailed("dex", error) };
33555
33349
  }
33556
33350
  }
33557
33351
  /**
@@ -33683,10 +33477,10 @@ var AssetService = class {
33683
33477
  async getWrappedAmount(dexToken, assetAmount) {
33684
33478
  try {
33685
33479
  const shares = await Erc4626Service.convertToShares(dexToken, assetAmount, this.hubProvider.publicClient);
33686
- if (!shares.ok) return shares;
33480
+ if (!shares.ok) return { ok: false, error: lookupFailed("dex", "getWrappedAmount", shares.error) };
33687
33481
  return { ok: true, value: shares.value };
33688
33482
  } catch (error) {
33689
- return { ok: false, error };
33483
+ return { ok: false, error: lookupFailed("dex", "getWrappedAmount", error) };
33690
33484
  }
33691
33485
  }
33692
33486
  /**
@@ -33702,10 +33496,10 @@ var AssetService = class {
33702
33496
  async getUnwrappedAmount(dexToken, shareAmount) {
33703
33497
  try {
33704
33498
  const assetAmount = await Erc4626Service.convertToAssets(dexToken, shareAmount, this.hubProvider.publicClient);
33705
- if (!assetAmount.ok) return assetAmount;
33499
+ if (!assetAmount.ok) return { ok: false, error: lookupFailed("dex", "getUnwrappedAmount", assetAmount.error) };
33706
33500
  return { ok: true, value: assetAmount.value };
33707
33501
  } catch (error) {
33708
- return { ok: false, error };
33502
+ return { ok: false, error: lookupFailed("dex", "getUnwrappedAmount", error) };
33709
33503
  }
33710
33504
  }
33711
33505
  /**
@@ -33731,14 +33525,10 @@ var AssetService = class {
33731
33525
  });
33732
33526
  return { ok: true, value };
33733
33527
  } catch (error) {
33734
- return { ok: false, error };
33528
+ return { ok: false, error: lookupFailed("dex", "getDeposit", error) };
33735
33529
  }
33736
33530
  }
33737
33531
  };
33738
-
33739
- // src/dex/errors.ts
33740
- var dexInvariant = createInvariant("dex");
33741
- var isDexError = isCodeMember(LOOKUP_CODES);
33742
33532
  var ClService = class _ClService {
33743
33533
  relayerApiEndpoint;
33744
33534
  hubProvider;
@@ -33853,7 +33643,7 @@ var ClService = class _ClService {
33853
33643
  this.config.logger.error("executeSupplyLiquidity error", txResult.error);
33854
33644
  return {
33855
33645
  ok: false,
33856
- error: txResult.error
33646
+ error: intentCreationFailed("dex", txResult.error)
33857
33647
  };
33858
33648
  }
33859
33649
  return {
@@ -33865,10 +33655,8 @@ var ClService = class _ClService {
33865
33655
  };
33866
33656
  } catch (error) {
33867
33657
  this.config.logger.error("executeSupplyLiquidity error", error);
33868
- return {
33869
- ok: false,
33870
- error
33871
- };
33658
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33659
+ return { ok: false, error: intentCreationFailed("dex", error) };
33872
33660
  }
33873
33661
  }
33874
33662
  /**
@@ -33980,7 +33768,7 @@ var ClService = class _ClService {
33980
33768
  if (!txResult.ok) {
33981
33769
  return {
33982
33770
  ok: false,
33983
- error: txResult.error
33771
+ error: intentCreationFailed("dex", txResult.error)
33984
33772
  };
33985
33773
  }
33986
33774
  return {
@@ -33991,10 +33779,8 @@ var ClService = class _ClService {
33991
33779
  }
33992
33780
  };
33993
33781
  } catch (error) {
33994
- return {
33995
- ok: false,
33996
- error
33997
- };
33782
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33783
+ return { ok: false, error: intentCreationFailed("dex", error) };
33998
33784
  }
33999
33785
  }
34000
33786
  /**
@@ -34053,7 +33839,7 @@ var ClService = class _ClService {
34053
33839
  if (!txResult.ok) {
34054
33840
  return {
34055
33841
  ok: false,
34056
- error: txResult.error
33842
+ error: intentCreationFailed("dex", txResult.error)
34057
33843
  };
34058
33844
  }
34059
33845
  return {
@@ -34064,10 +33850,8 @@ var ClService = class _ClService {
34064
33850
  }
34065
33851
  };
34066
33852
  } catch (error) {
34067
- return {
34068
- ok: false,
34069
- error
34070
- };
33853
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33854
+ return { ok: false, error: intentCreationFailed("dex", error) };
34071
33855
  }
34072
33856
  }
34073
33857
  /**
@@ -34142,10 +33926,8 @@ var ClService = class _ClService {
34142
33926
  return { ok: true, value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: hubTxHash } };
34143
33927
  } catch (error) {
34144
33928
  this.config.logger.error("supplyLiquidity error", error);
34145
- return {
34146
- ok: false,
34147
- error
34148
- };
33929
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33930
+ return { ok: false, error: intentCreationFailed("dex", error) };
34149
33931
  }
34150
33932
  },
34151
33933
  {
@@ -34205,10 +33987,8 @@ var ClService = class _ClService {
34205
33987
  }
34206
33988
  return { ok: true, value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: hubTxHash } };
34207
33989
  } catch (error) {
34208
- return {
34209
- ok: false,
34210
- error
34211
- };
33990
+ if (isDexCreateIntentError(error)) return { ok: false, error };
33991
+ return { ok: false, error: intentCreationFailed("dex", error) };
34212
33992
  }
34213
33993
  },
34214
33994
  {
@@ -34269,10 +34049,8 @@ var ClService = class _ClService {
34269
34049
  }
34270
34050
  return { ok: true, value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: hubTxHash } };
34271
34051
  } catch (error) {
34272
- return {
34273
- ok: false,
34274
- error
34275
- };
34052
+ if (isDexCreateIntentError(error)) return { ok: false, error };
34053
+ return { ok: false, error: intentCreationFailed("dex", error) };
34276
34054
  }
34277
34055
  },
34278
34056
  {
@@ -34411,7 +34189,7 @@ var ClService = class _ClService {
34411
34189
  this.config.logger.error("executeClaimRewards error", txResult.error);
34412
34190
  return {
34413
34191
  ok: false,
34414
- error: txResult.error
34192
+ error: intentCreationFailed("dex", txResult.error)
34415
34193
  };
34416
34194
  }
34417
34195
  return {
@@ -34423,10 +34201,8 @@ var ClService = class _ClService {
34423
34201
  };
34424
34202
  } catch (error) {
34425
34203
  this.config.logger.error("executeClaimRewards error", error);
34426
- return {
34427
- ok: false,
34428
- error
34429
- };
34204
+ if (isDexCreateIntentError(error)) return { ok: false, error };
34205
+ return { ok: false, error: intentCreationFailed("dex", error) };
34430
34206
  }
34431
34207
  }
34432
34208
  /**
@@ -34469,10 +34245,8 @@ var ClService = class _ClService {
34469
34245
  return { ok: true, value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: hubTxHash } };
34470
34246
  } catch (error) {
34471
34247
  this.config.logger.error("claimRewards error", error);
34472
- return {
34473
- ok: false,
34474
- error
34475
- };
34248
+ if (isDexCreateIntentError(error)) return { ok: false, error };
34249
+ return { ok: false, error: intentCreationFailed("dex", error) };
34476
34250
  }
34477
34251
  },
34478
34252
  {
@@ -35073,6 +34847,7 @@ var DexService = class {
35073
34847
  // src/moneyMarket/errors.ts
35074
34848
  var mmInvariant = createInvariant("moneyMarket");
35075
34849
  var ORCHESTRATION_CODES2 = /* @__PURE__ */ new Set([
34850
+ "USER_REJECTED",
35076
34851
  "VALIDATION_FAILED",
35077
34852
  "INTENT_CREATION_FAILED",
35078
34853
  "TX_VERIFICATION_FAILED",
@@ -35083,6 +34858,7 @@ var ORCHESTRATION_CODES2 = /* @__PURE__ */ new Set([
35083
34858
  "UNKNOWN"
35084
34859
  ]);
35085
34860
  var MONEY_MARKET_CODES = /* @__PURE__ */ new Set([
34861
+ "USER_REJECTED",
35086
34862
  "VALIDATION_FAILED",
35087
34863
  "INTENT_CREATION_FAILED",
35088
34864
  "TX_VERIFICATION_FAILED",
@@ -38839,11 +38615,7 @@ var PartnerFeeClaimService = class {
38839
38615
  } catch (error) {
38840
38616
  return {
38841
38617
  ok: false,
38842
- error: new SodaxError("APPROVE_FAILED", error instanceof Error ? error.message : "approveToken failed", {
38843
- feature: "partner",
38844
- cause: error,
38845
- context: { phase: "approve" }
38846
- })
38618
+ error: approveFailed("partner", error)
38847
38619
  };
38848
38620
  }
38849
38621
  }
@@ -39359,6 +39131,7 @@ var RecoveryService = class {
39359
39131
  // src/leverageYield/errors.ts
39360
39132
  var leverageYieldInvariant = createInvariant("leverageYield");
39361
39133
  var LEVERAGE_YIELD_CODES = /* @__PURE__ */ new Set([
39134
+ "USER_REJECTED",
39362
39135
  "VALIDATION_FAILED",
39363
39136
  "INTENT_CREATION_FAILED",
39364
39137
  "APPROVE_FAILED",
@@ -39378,6 +39151,7 @@ var LEVERAGE_YIELD_POST_EXECUTION_CODES = /* @__PURE__ */ new Set([
39378
39151
  "UNKNOWN"
39379
39152
  ]);
39380
39153
  var LEVERAGE_YIELD_SWAP_CODES = /* @__PURE__ */ new Set([
39154
+ "USER_REJECTED",
39381
39155
  "VALIDATION_FAILED",
39382
39156
  "INTENT_CREATION_FAILED",
39383
39157
  "TX_VERIFICATION_FAILED",
@@ -39454,7 +39228,7 @@ var LeverageYieldService = class {
39454
39228
  }
39455
39229
  /** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
39456
39230
  getVault(name) {
39457
- return this.listVaults().find((v6) => v6.name === name);
39231
+ return this.listVaults().find((v4) => v4.name === name);
39458
39232
  }
39459
39233
  /**
39460
39234
  * Looks up a registered vault by its on-chain proxy address (case-insensitive).
@@ -39462,7 +39236,7 @@ var LeverageYieldService = class {
39462
39236
  */
39463
39237
  getVaultByAddress(address) {
39464
39238
  const normalized = address.toLowerCase();
39465
- return this.listVaults().find((v6) => v6.vault.toLowerCase() === normalized);
39239
+ return this.listVaults().find((v4) => v4.vault.toLowerCase() === normalized);
39466
39240
  }
39467
39241
  /**
39468
39242
  * Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
@@ -40347,6 +40121,7 @@ var Sodax = class {
40347
40121
  // src/partner/errors.ts
40348
40122
  var partnerInvariant = createInvariant("partner");
40349
40123
  var PARTNER_CODES = /* @__PURE__ */ new Set([
40124
+ "USER_REJECTED",
40350
40125
  "VALIDATION_FAILED",
40351
40126
  "LOOKUP_FAILED",
40352
40127
  "APPROVE_FAILED",
@@ -40372,6 +40147,10 @@ var isPartnerError = isCodeMember(PARTNER_CODES);
40372
40147
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
40373
40148
  */
40374
40149
 
40150
+ Object.defineProperty(exports, "SwapsApiError", {
40151
+ enumerable: true,
40152
+ get: function () { return swapsApi.SwapsApiError; }
40153
+ });
40375
40154
  exports.ALLOWANCE_CHECK_CODES = ALLOWANCE_CHECK_CODES;
40376
40155
  exports.APPROVE_CODES = APPROVE_CODES;
40377
40156
  exports.AssetService = AssetService;
@@ -40598,6 +40377,7 @@ exports.getStagingSolverTokens = getStagingSolverTokens;
40598
40377
  exports.getSupportedSolverTokens = getSupportedSolverTokens;
40599
40378
  exports.getTransactionPackets = getTransactionPackets;
40600
40379
  exports.getbnUSDToken = getbnUSDToken;
40380
+ exports.hederaSupportedTokens = hederaSupportedTokens;
40601
40381
  exports.hexToBigInt = hexToBigInt;
40602
40382
  exports.hexToSolanaAddress = hexToSolanaAddress;
40603
40383
  exports.hubConfig = hubConfig;
@@ -40617,6 +40397,8 @@ exports.isBridgeError = isBridgeError;
40617
40397
  exports.isBridgeLookupError = isBridgeLookupError;
40618
40398
  exports.isBridgeOrchestrationError = isBridgeOrchestrationError;
40619
40399
  exports.isCodeMember = isCodeMember;
40400
+ exports.isDexApproveError = isDexApproveError;
40401
+ exports.isDexCreateIntentError = isDexCreateIntentError;
40620
40402
  exports.isDexError = isDexError;
40621
40403
  exports.isEvmChainKey = isEvmChainKey;
40622
40404
  exports.isEvmChainKeyType = isEvmChainKeyType;