@sodax/sdk 2.1.0-rc.1 → 2.1.0-rc.3

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,7 @@ 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 v7 = require('valibot');
23
23
  var swapsApi = require('@sodax/swaps-api');
24
24
  var BigNumber5 = require('bignumber.js');
25
25
  var swapSdkCore = require('@pancakeswap/swap-sdk-core');
@@ -49,7 +49,7 @@ var rlp__namespace = /*#__PURE__*/_interopNamespace(rlp);
49
49
  var ecc__namespace = /*#__PURE__*/_interopNamespace(ecc);
50
50
  var BN__default = /*#__PURE__*/_interopDefault(BN);
51
51
  var IconSdkRaw__namespace = /*#__PURE__*/_interopNamespace(IconSdkRaw);
52
- var v4__namespace = /*#__PURE__*/_interopNamespace(v4);
52
+ var v7__namespace = /*#__PURE__*/_interopNamespace(v7);
53
53
  var BigNumber5__default = /*#__PURE__*/_interopDefault(BigNumber5);
54
54
 
55
55
  // src/errors/SodaxError.ts
@@ -122,8 +122,8 @@ function serializeCause(cause, depth) {
122
122
  }
123
123
  function sanitizeContext(value, depth) {
124
124
  const out = {};
125
- for (const [key, v6] of Object.entries(value)) {
126
- out[key] = sanitizeValue(v6, depth + 1);
125
+ for (const [key, v9] of Object.entries(value)) {
126
+ out[key] = sanitizeValue(v9, depth + 1);
127
127
  }
128
128
  return out;
129
129
  }
@@ -134,13 +134,13 @@ function sanitizeValue(value, depth) {
134
134
  if (t === "bigint") return value.toString();
135
135
  if (t === "string" || t === "number" || t === "boolean") return value;
136
136
  if (t === "function" || t === "symbol") return safeString(value);
137
- if (Array.isArray(value)) return value.map((v6) => sanitizeValue(v6, depth + 1));
137
+ if (Array.isArray(value)) return value.map((v9) => sanitizeValue(v9, depth + 1));
138
138
  if (value instanceof Date) return value.toISOString();
139
139
  if (value instanceof Map) {
140
- return Array.from(value.entries()).map(([k, v6]) => [sanitizeValue(k, depth + 1), sanitizeValue(v6, depth + 1)]);
140
+ return Array.from(value.entries()).map(([k, v9]) => [sanitizeValue(k, depth + 1), sanitizeValue(v9, depth + 1)]);
141
141
  }
142
142
  if (value instanceof Set) {
143
- return Array.from(value.values()).map((v6) => sanitizeValue(v6, depth + 1));
143
+ return Array.from(value.values()).map((v9) => sanitizeValue(v9, depth + 1));
144
144
  }
145
145
  if (value instanceof Error) return { name: value.name, message: value.message };
146
146
  if (t === "object") {
@@ -152,9 +152,9 @@ function sanitizeValue(value, depth) {
152
152
  }
153
153
  return safeString(value);
154
154
  }
155
- function safeString(v6) {
155
+ function safeString(v9) {
156
156
  try {
157
- return String(v6);
157
+ return String(v9);
158
158
  } catch {
159
159
  return "[unserializable]";
160
160
  }
@@ -513,7 +513,7 @@ var SodaTokens = {
513
513
  name: "Soda RBNT",
514
514
  decimals: 18,
515
515
  address: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac",
516
- chainKey: ChainKeys.REDBELLY_MAINNET,
516
+ chainKey: ChainKeys.SONIC_MAINNET,
517
517
  hubAsset: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac",
518
518
  vault: "0x4B207114F9118dEAC56436e1aE3c45648783c7Ac"
519
519
  },
@@ -4272,6 +4272,11 @@ var SPONSORING_API_ERROR_CODES = [
4272
4272
  ];
4273
4273
 
4274
4274
  // ../types/dist/bitcoin/bitcoin.js
4275
+ var BITCOIN_DUST_SATS = 546n;
4276
+ function isNativeBitcoinToken(chainConfig, token) {
4277
+ const nativeBtcTokens = new Set(["btc", chainConfig.nativeToken, chainConfig.supportedTokens.BTC?.address].filter((value) => !!value).map((value) => value.toLowerCase()));
4278
+ return nativeBtcTokens.has(token.toLowerCase());
4279
+ }
4275
4280
  function isSupportedBitcoinAddressType(addressType) {
4276
4281
  return BTC_ADDRESS_TYPES.includes(addressType);
4277
4282
  }
@@ -4295,7 +4300,13 @@ var BTC_ADDRESS_TYPES = ["P2PKH", "P2SH", "P2WPKH", "P2TR"];
4295
4300
  // ../types/dist/hooks/hooks.js
4296
4301
  var HookKind = {
4297
4302
  /** Deposits delivered USDC into the recipient's HyperCore perps account (HyperEVM). */
4298
- HYPERCORE_DEPOSIT: "hyperCoreDeposit"
4303
+ HYPERCORE_DEPOSIT: "hyperCoreDeposit",
4304
+ /**
4305
+ * Requests an ERC-7540 deposit of delivered USDC into the Flint RWA vault (Ethereum), with the
4306
+ * recipient as the request's controller. Asynchronous: the request mints no shares — Flint's
4307
+ * curator settles a NAV and then claims the shares on the controller's behalf.
4308
+ */
4309
+ FLINT_DEPOSIT: "flintDeposit"
4299
4310
  };
4300
4311
  var spokeHooks = {
4301
4312
  [ChainKeys.HYPEREVM_MAINNET]: [
@@ -4306,6 +4317,20 @@ var spokeHooks = {
4306
4317
  // USDC on HyperEVM
4307
4318
  }
4308
4319
  ]
4320
+ // HookKind.FLINT_DEPOSIT is not registered yet: FlintDepositHook is not deployed to Ethereum
4321
+ // mainnet (icon-project/sodax-contracts#693). Registering it with a placeholder address would
4322
+ // route real intent output to that address, so the entry lands with the deployment:
4323
+ //
4324
+ // [ChainKeys.ETHEREUM_MAINNET]: [
4325
+ // {
4326
+ // kind: HookKind.FLINT_DEPOSIT,
4327
+ // address: '0x…',
4328
+ // supportedTokens: [spokeChainConfig[ChainKeys.ETHEREUM_MAINNET].supportedTokens.USDC.address],
4329
+ // },
4330
+ // ],
4331
+ //
4332
+ // Until then `getSpokeHook` returns undefined and `resolveDeliveryHook` throws, which is the
4333
+ // correct behaviour for a hook that does not exist on chain.
4309
4334
  };
4310
4335
  var getSpokeHook = (chainKey, kind) => spokeHooks[chainKey]?.find((h) => h.kind === kind);
4311
4336
  var getSpokeHooks = (chainKey) => spokeHooks[chainKey] ?? [];
@@ -4431,7 +4456,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
4431
4456
  }
4432
4457
 
4433
4458
  // ../types/dist/index.js
4434
- var CONFIG_VERSION = 221;
4459
+ var CONFIG_VERSION = 223;
4435
4460
  function isEvmSpokeChainConfig(value) {
4436
4461
  return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
4437
4462
  }
@@ -4542,6 +4567,9 @@ function isUndefinedOrValidWalletProviderForChainKey(chainKey, walletProvider) {
4542
4567
  function isOptionalBitcoinWalletProviderType(walletProvider) {
4543
4568
  return walletProvider === void 0 || isBitcoinWalletProviderType(walletProvider);
4544
4569
  }
4570
+ function isNativeBitcoinTransfer(config, chainKey, token) {
4571
+ return isBitcoinChainKeyType(chainKey) && !!token && isNativeBitcoinToken(config.getChainConfig(chainKey), token.address);
4572
+ }
4545
4573
  async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_RETRY_DELAY_MS) {
4546
4574
  do {
4547
4575
  try {
@@ -4558,11 +4586,11 @@ async function retry(action, retryCount = DEFAULT_MAX_RETRY, delayMs = DEFAULT_R
4558
4586
  throw new Error(`Retry exceeded MAX_RETRY_DEFAULT=${DEFAULT_MAX_RETRY}`);
4559
4587
  }
4560
4588
  function getRandomBytes(length) {
4561
- const array2 = new Uint8Array(length);
4589
+ const array3 = new Uint8Array(length);
4562
4590
  for (let i = 0; i < length; i++) {
4563
- array2[i] = Math.floor(Math.random() * 256);
4591
+ array3[i] = Math.floor(Math.random() * 256);
4564
4592
  }
4565
- return array2;
4593
+ return array3;
4566
4594
  }
4567
4595
  function randomUint256() {
4568
4596
  const bytes = getRandomBytes(32);
@@ -4724,6 +4752,7 @@ var HttpRelayError = class extends Error {
4724
4752
  }
4725
4753
  };
4726
4754
  var RELAY_REQUEST_TIMEOUT_MS = 15e3;
4755
+ var RELAY_FALLBACK_FLOOR_MS = 5e3;
4727
4756
  function isAbortError(error) {
4728
4757
  return error instanceof Error && error.name === "AbortError";
4729
4758
  }
@@ -14022,6 +14051,13 @@ var ConfigService = class {
14022
14051
  * a client-side option set via `new Sodax({ fee })`. Per-feature overrides live on the feature config.
14023
14052
  */
14024
14053
  fee;
14054
+ /**
14055
+ * RadFi/Bound request signer. Resolved once at construction and kept independent of {@link sodax}
14056
+ * so that {@link initialize}'s dynamic-config swap never clobbers it. Read by `BitcoinSpokeService`
14057
+ * via `config.radfiSigner`; `undefined` unless the consumer passed `radfi.signRequest` to
14058
+ * `new Sodax(...)`. Holds the function reference only — never a credential.
14059
+ */
14060
+ radfiSigner;
14025
14061
  initialized = false;
14026
14062
  // data structures for quick lookup
14027
14063
  supportedHubAssetsSet;
@@ -14035,11 +14071,12 @@ var ConfigService = class {
14035
14071
  hubAssetToXTokenMap;
14036
14072
  // `api` / `userConfig` are accepted but unused while initialize()'s dynamic fetch is disabled
14037
14073
  // (see TODO(config-v2) below); restore their assignments when re-enabling.
14038
- constructor({ api, config, userConfig, logger, analytics, fee }) {
14074
+ constructor({ api, config, userConfig, logger, analytics, fee, radfiSigner }) {
14039
14075
  this.sodax = config;
14040
14076
  this.logger = logger ?? resolveLogger(void 0);
14041
14077
  this.analytics = analytics ?? noopAnalytics;
14042
14078
  this.fee = fee;
14079
+ this.radfiSigner = radfiSigner;
14043
14080
  this.loadSodaxConfigDataStructures(config);
14044
14081
  }
14045
14082
  async initialize() {
@@ -14338,7 +14375,7 @@ function mergeSodaxConfig(base2, override) {
14338
14375
  }
14339
14376
  function encodeContractCalls(calls) {
14340
14377
  return viem.encodeAbiParameters(viem.parseAbiParameters("(address,uint256,bytes)[]"), [
14341
- calls.map((v6) => [v6.address, v6.value, v6.data])
14378
+ calls.map((v9) => [v9.address, v9.value, v9.data])
14342
14379
  ]);
14343
14380
  }
14344
14381
  async function waitForTransactionReceipt(hash, provider) {
@@ -14614,7 +14651,7 @@ var EvmVaultTokenService = class {
14614
14651
  return amount * BigInt(10 ** (decimals - 18));
14615
14652
  }
14616
14653
  };
14617
- var Erc20Service = class {
14654
+ var Erc20Service = class _Erc20Service {
14618
14655
  constructor() {
14619
14656
  }
14620
14657
  static async getErc20Token(token, publicClient) {
@@ -14640,6 +14677,19 @@ var Erc20Service = class {
14640
14677
  });
14641
14678
  return { name, symbol, decimals, address: token };
14642
14679
  }
14680
+ /**
14681
+ * Read the current on-chain allowance of `spender` over `owner`'s balance.
14682
+ * @param params - Token, owner, spender, and publicClient for the chain.
14683
+ * @returns The raw allowance.
14684
+ */
14685
+ static async getAllowance(params) {
14686
+ return params.publicClient.readContract({
14687
+ address: params.token,
14688
+ abi: viem.erc20Abi,
14689
+ functionName: "allowance",
14690
+ args: [params.owner, params.spender]
14691
+ });
14692
+ }
14643
14693
  /**
14644
14694
  * Check if spender has enough ERC20 allowance for given amount.
14645
14695
  * @param params - Token, amount, owner, spender, chainKey, and publicClient for the chain.
@@ -14653,12 +14703,7 @@ var Erc20Service = class {
14653
14703
  value: true
14654
14704
  };
14655
14705
  }
14656
- const allowedAmount = await params.publicClient.readContract({
14657
- address: params.token,
14658
- abi: viem.erc20Abi,
14659
- functionName: "allowance",
14660
- args: [params.owner, params.spender]
14661
- });
14706
+ const allowedAmount = await _Erc20Service.getAllowance(params);
14662
14707
  return {
14663
14708
  ok: true,
14664
14709
  value: allowedAmount >= params.amount
@@ -14670,6 +14715,59 @@ var Erc20Service = class {
14670
14715
  };
14671
14716
  }
14672
14717
  }
14718
+ /**
14719
+ * Decide how many approve transactions this token needs for `amount`.
14720
+ *
14721
+ * Tokens of the 2017 TetherToken lineage reject an allowance change from one non-zero value to
14722
+ * another, so a wallet holding a stale allowance can never approve — every retry reverts the same
14723
+ * way. Such a token needs `approve(0)` first.
14724
+ *
14725
+ * Detection is behavioural: a simulated approve either reverts or it does not. That answers the
14726
+ * question that actually matters ("will this approve revert?") instead of "is this token USDT?",
14727
+ * so a token listed later, or upgraded later behind the same address, is covered without a code
14728
+ * change — and no token list is hardcoded.
14729
+ *
14730
+ * The probes only run once an allowance is already set. The common path (nothing approved yet)
14731
+ * costs a single read.
14732
+ */
14733
+ static async planApproval(params) {
14734
+ const single = (reason) => ({ approveAmount: params.amount, reason });
14735
+ if (params.token.toLowerCase() === params.nativeToken.toLowerCase()) {
14736
+ return single("native-token");
14737
+ }
14738
+ let allowance;
14739
+ try {
14740
+ allowance = await _Erc20Service.getAllowance(params);
14741
+ } catch {
14742
+ return single("allowance-read-failed");
14743
+ }
14744
+ if (allowance === 0n) {
14745
+ return single("zero-allowance");
14746
+ }
14747
+ if (await _Erc20Service.canApprove(params, params.amount)) {
14748
+ return single("probe-passed");
14749
+ }
14750
+ if (!await _Erc20Service.canApprove(params, 0n)) {
14751
+ return single("reset-not-viable");
14752
+ }
14753
+ return { resetAmount: 0n, approveAmount: params.amount, reason: "reset-required" };
14754
+ }
14755
+ /**
14756
+ * Simulate `approve(spender, amount)` as `owner`.
14757
+ *
14758
+ * `call` rather than `simulateContract`, because a TetherToken-lineage `approve` returns no value
14759
+ * and ABI decoding would fail even on a successful call. `account` is required: the guard reads
14760
+ * `allowed[msg.sender][spender]`.
14761
+ */
14762
+ static async canApprove(params, amount) {
14763
+ const { data } = _Erc20Service.encodeApprove(params.token, params.spender, amount);
14764
+ try {
14765
+ await params.publicClient.call({ account: params.owner, to: params.token, data });
14766
+ return true;
14767
+ } catch {
14768
+ return false;
14769
+ }
14770
+ }
14673
14771
  /**
14674
14772
  * Approve ERC20 amount spending
14675
14773
  * @param token - ERC20 token address
@@ -15250,10 +15348,14 @@ var RadfiApiError = class extends Error {
15250
15348
  };
15251
15349
  var RadfiProvider = class {
15252
15350
  config;
15351
+ // Client-side runtime signer (e.g. a backend's HMAC closure). Holds no credential itself — the SDK
15352
+ // only keeps the reference and invokes it per outbound `apiUrl` request. See `RadfiOptions` / gh-831.
15353
+ signer;
15253
15354
  accessToken = "";
15254
15355
  refreshToken = "";
15255
- constructor(config) {
15356
+ constructor(config, options) {
15256
15357
  this.config = config;
15358
+ this.signer = options?.signer;
15257
15359
  this.accessToken = config.accessToken ?? "";
15258
15360
  this.refreshToken = config.refreshToken ?? "";
15259
15361
  if (config.apiUrl.endsWith("/")) {
@@ -15364,6 +15466,9 @@ var RadfiProvider = class {
15364
15466
  }
15365
15467
  return body.data;
15366
15468
  }
15469
+ // UMS call: goes out unsigned even when a signer is configured. Bound scopes the backend
15470
+ // credential to the Sodax endpoints on `apiUrl`, so a signature here is unverified — this
15471
+ // deliberately does not go through `request()`. Same for `getExpiredUtxos` below. See gh-831.
15367
15472
  async getBalance(address) {
15368
15473
  if (!this.config.umsUrl) {
15369
15474
  throw new Error("RadfiConfig.umsUrl is required for getBalance");
@@ -15441,6 +15546,9 @@ var RadfiProvider = class {
15441
15546
  }
15442
15547
  /**
15443
15548
  * Fetch expired (or near-expiry) UTXOs for a trading wallet address from UMS API.
15549
+ *
15550
+ * UMS call — unsigned by design, like `getBalance`: the backend credential is scoped to the
15551
+ * Sodax endpoints on `apiUrl`, so a configured signer intentionally does not reach here.
15444
15552
  */
15445
15553
  async getExpiredUtxos(tradingAddress, params) {
15446
15554
  if (!this.config.umsUrl) {
@@ -15622,11 +15730,13 @@ var RadfiProvider = class {
15622
15730
  }
15623
15731
  }
15624
15732
  async request(endpoint, options) {
15733
+ const signed = this.signer ? await this.signer({ method: options?.method ?? "GET", path: endpoint }) : void 0;
15625
15734
  return fetch(`${this.config.apiUrl}${endpoint}`, {
15626
15735
  ...options,
15627
15736
  headers: {
15628
15737
  "Content-Type": "application/json",
15629
- ...options?.headers || {}
15738
+ ...options?.headers || {},
15739
+ ...signed
15630
15740
  }
15631
15741
  });
15632
15742
  }
@@ -15689,7 +15799,7 @@ function normalizeSignatureToBase64(signature) {
15689
15799
  // src/shared/services/spoke/BitcoinSpokeService.ts
15690
15800
  bitcoinjsLib.initEccLib(ecc__namespace);
15691
15801
  var BITCOIN_DEFAULT_FEE_RATE = 3;
15692
- var DUST_THRESHOLD = 546;
15802
+ var DUST_THRESHOLD = Number(BITCOIN_DUST_SATS);
15693
15803
  var BitcoinSpokeService = class {
15694
15804
  config;
15695
15805
  rpcUrl;
@@ -15701,7 +15811,7 @@ var BitcoinSpokeService = class {
15701
15811
  this.config = config;
15702
15812
  const chainConfig = config.getChainConfig(ChainKeys.BITCOIN_MAINNET);
15703
15813
  this.rpcUrl = chainConfig.rpcUrl;
15704
- this.radfi = new RadfiProvider(chainConfig.radfi);
15814
+ this.radfi = new RadfiProvider(chainConfig.radfi, { signer: config.radfiSigner });
15705
15815
  this.walletMode = chainConfig.radfi.walletMode ?? "TRADING";
15706
15816
  this.pollingIntervalMs = chainConfig.pollingConfig.pollingIntervalMs;
15707
15817
  this.maxTimeoutMs = chainConfig.pollingConfig.maxTimeoutMs;
@@ -16058,11 +16168,7 @@ var BitcoinSpokeService = class {
16058
16168
  async buildDepositPsbt(walletAddress, walletProvider, srcChainKey, token, amount, data, utxos) {
16059
16169
  const chainConfig = this.config.getChainConfig(srcChainKey);
16060
16170
  const assetManagerAddress = chainConfig.addresses.assetManager;
16061
- const normalizedToken = token.toLocaleLowerCase();
16062
- const nativeBtcTokens = new Set(
16063
- ["btc", chainConfig.nativeToken, chainConfig.supportedTokens.BTC?.address].filter((value) => !!value).map((value) => value.toLocaleLowerCase())
16064
- );
16065
- const isNativeBtc = nativeBtcTokens.has(normalizedToken);
16171
+ const isNativeBtc = isNativeBitcoinToken(chainConfig, token);
16066
16172
  if (isNativeBtc) {
16067
16173
  const OP_RETURN = bitcoinjsLib.opcodes.OP_RETURN;
16068
16174
  const OP_12 = bitcoinjsLib.opcodes.OP_12;
@@ -16321,7 +16427,7 @@ function hexToBytes2(hex) {
16321
16427
  const al = hl / 2;
16322
16428
  if (hl % 2)
16323
16429
  throw new Error("hex string expected, got unpadded hex of length " + hl);
16324
- const array2 = new Uint8Array(al);
16430
+ const array3 = new Uint8Array(al);
16325
16431
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
16326
16432
  const n1 = asciiToBase16(hex.charCodeAt(hi));
16327
16433
  const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
@@ -16329,9 +16435,9 @@ function hexToBytes2(hex) {
16329
16435
  const char = hex[hi] + hex[hi + 1];
16330
16436
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
16331
16437
  }
16332
- array2[ai] = n1 * 16 + n2;
16438
+ array3[ai] = n1 * 16 + n2;
16333
16439
  }
16334
- return array2;
16440
+ return array3;
16335
16441
  }
16336
16442
  function concatBytes(...arrays) {
16337
16443
  let sum = 0;
@@ -16961,22 +17067,22 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16961
17067
  const byte0 = Uint8Array.of(0);
16962
17068
  const byte1 = Uint8Array.of(1);
16963
17069
  const _maxDrbgIters = 1e3;
16964
- let v6 = u8n(hashLen);
17070
+ let v9 = u8n(hashLen);
16965
17071
  let k = u8n(hashLen);
16966
17072
  let i = 0;
16967
17073
  const reset = () => {
16968
- v6.fill(1);
17074
+ v9.fill(1);
16969
17075
  k.fill(0);
16970
17076
  i = 0;
16971
17077
  };
16972
- const h = (...msgs) => hmacFn(k, concatBytes(v6, ...msgs));
17078
+ const h = (...msgs) => hmacFn(k, concatBytes(v9, ...msgs));
16973
17079
  const reseed = (seed = NULL) => {
16974
17080
  k = h(byte0, seed);
16975
- v6 = h();
17081
+ v9 = h();
16976
17082
  if (seed.length === 0)
16977
17083
  return;
16978
17084
  k = h(byte1, seed);
16979
- v6 = h();
17085
+ v9 = h();
16980
17086
  };
16981
17087
  const gen = () => {
16982
17088
  if (i++ >= _maxDrbgIters)
@@ -16984,10 +17090,10 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
16984
17090
  let len = 0;
16985
17091
  const out = [];
16986
17092
  while (len < qByteLen) {
16987
- v6 = h();
16988
- const sl = v6.slice();
17093
+ v9 = h();
17094
+ const sl = v9.slice();
16989
17095
  out.push(sl);
16990
- len += v6.length;
17096
+ len += v9.length;
16991
17097
  }
16992
17098
  return concatBytes(...out);
16993
17099
  };
@@ -17002,18 +17108,18 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
17002
17108
  };
17003
17109
  return genUntil;
17004
17110
  }
17005
- function validateObject(object3, fields = {}, optFields = {}) {
17006
- if (!object3 || typeof object3 !== "object")
17111
+ function validateObject(object5, fields = {}, optFields = {}) {
17112
+ if (!object5 || typeof object5 !== "object")
17007
17113
  throw new Error("expected valid options object");
17008
17114
  function checkField(fieldName, expectedType, isOpt) {
17009
- const val = object3[fieldName];
17115
+ const val = object5[fieldName];
17010
17116
  if (isOpt && val === void 0)
17011
17117
  return;
17012
17118
  const current = typeof val;
17013
17119
  if (current !== expectedType || val === null)
17014
17120
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
17015
17121
  }
17016
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v6]) => checkField(k, v6, isOpt));
17122
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v9]) => checkField(k, v9, isOpt));
17017
17123
  iter(fields, false);
17018
17124
  iter(optFields, true);
17019
17125
  }
@@ -17052,12 +17158,12 @@ function pow2(x, power, modulo) {
17052
17158
  }
17053
17159
  return res;
17054
17160
  }
17055
- function invert(number3, modulo) {
17056
- if (number3 === _0n2)
17161
+ function invert(number5, modulo) {
17162
+ if (number5 === _0n2)
17057
17163
  throw new Error("invert: expected non-zero number");
17058
17164
  if (modulo <= _0n2)
17059
17165
  throw new Error("invert: expected positive modulus, got " + modulo);
17060
- let a = mod(number3, modulo);
17166
+ let a = mod(number5, modulo);
17061
17167
  let b = modulo;
17062
17168
  let x = _0n2, u = _1n2;
17063
17169
  while (a !== _0n2) {
@@ -17084,9 +17190,9 @@ function sqrt3mod4(Fp, n) {
17084
17190
  function sqrt5mod8(Fp, n) {
17085
17191
  const p5div8 = (Fp.ORDER - _5n) / _8n;
17086
17192
  const n2 = Fp.mul(n, _2n);
17087
- const v6 = Fp.pow(n2, p5div8);
17088
- const nv = Fp.mul(n, v6);
17089
- const i = Fp.mul(Fp.mul(nv, _2n), v6);
17193
+ const v9 = Fp.pow(n2, p5div8);
17194
+ const nv = Fp.mul(n, v9);
17195
+ const i = Fp.mul(Fp.mul(nv, _2n), v9);
17090
17196
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
17091
17197
  assertIsSquare(Fp, root, n);
17092
17198
  return root;
@@ -17561,27 +17667,27 @@ var wNAF = class {
17561
17667
  assert0(n);
17562
17668
  return acc;
17563
17669
  }
17564
- getPrecomputes(W, point, transform) {
17670
+ getPrecomputes(W, point, transform2) {
17565
17671
  let comp = pointPrecomputes.get(point);
17566
17672
  if (!comp) {
17567
17673
  comp = this.precomputeWindow(point, W);
17568
17674
  if (W !== 1) {
17569
- if (typeof transform === "function")
17570
- comp = transform(comp);
17675
+ if (typeof transform2 === "function")
17676
+ comp = transform2(comp);
17571
17677
  pointPrecomputes.set(point, comp);
17572
17678
  }
17573
17679
  }
17574
17680
  return comp;
17575
17681
  }
17576
- cached(point, scalar, transform) {
17682
+ cached(point, scalar, transform2) {
17577
17683
  const W = getW(point);
17578
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
17684
+ return this.wNAF(W, this.getPrecomputes(W, point, transform2), scalar);
17579
17685
  }
17580
- unsafe(point, scalar, transform, prev) {
17686
+ unsafe(point, scalar, transform2, prev) {
17581
17687
  const W = getW(point);
17582
17688
  if (W === 1)
17583
17689
  return this._unsafeLadder(point, scalar, prev);
17584
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
17690
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform2), scalar, prev);
17585
17691
  }
17586
17692
  // We calculate precomputes for elliptic curve point multiplication
17587
17693
  // using windowed method. This specifies window size and
@@ -17668,9 +17774,9 @@ function edwards(params, extraOpts = {}) {
17668
17774
  validateObject(extraOpts, {}, { uvRatio: "function" });
17669
17775
  const MASK = _2n2 << BigInt(Fn.BYTES * 8) - _1n4;
17670
17776
  const modP = (n) => Fp.create(n);
17671
- const uvRatio2 = extraOpts.uvRatio || ((u, v6) => {
17777
+ const uvRatio2 = extraOpts.uvRatio || ((u, v9) => {
17672
17778
  try {
17673
- return { isValid: true, value: Fp.sqrt(Fp.div(u, v6)) };
17779
+ return { isValid: true, value: Fp.sqrt(Fp.div(u, v9)) };
17674
17780
  } catch (e) {
17675
17781
  return { isValid: false, value: _0n4 };
17676
17782
  }
@@ -17766,8 +17872,8 @@ function edwards(params, extraOpts = {}) {
17766
17872
  aInRange("point.y", y, _0n4, max);
17767
17873
  const y2 = modP(y * y);
17768
17874
  const u = modP(y2 - _1n4);
17769
- const v6 = modP(d * y2 - a);
17770
- let { isValid, value: x } = uvRatio2(u, v6);
17875
+ const v9 = modP(d * y2 - a);
17876
+ let { isValid, value: x } = uvRatio2(u, v9);
17771
17877
  if (!isValid)
17772
17878
  throw new Error("bad point: invalid y coordinate");
17773
17879
  const isXOdd = (x & _1n4) === _1n4;
@@ -18107,13 +18213,13 @@ function adjustScalarBytes(bytes) {
18107
18213
  return bytes;
18108
18214
  }
18109
18215
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
18110
- function uvRatio(u, v6) {
18216
+ function uvRatio(u, v9) {
18111
18217
  const P = ed25519_CURVE_p;
18112
- const v32 = mod(v6 * v6 * v6, P);
18113
- const v7 = mod(v32 * v32 * v6, P);
18114
- const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
18218
+ const v32 = mod(v9 * v9 * v9, P);
18219
+ const v72 = mod(v32 * v32 * v9, P);
18220
+ const pow = ed25519_pow_2_252_3(u * v72).pow_p_5_8;
18115
18221
  let x = mod(u * v32 * pow, P);
18116
- const vx2 = mod(v6 * x * x, P);
18222
+ const vx2 = mod(v9 * x * x, P);
18117
18223
  const root1 = x;
18118
18224
  const root2 = mod(x * ED25519_SQRT_M1, P);
18119
18225
  const useRoot1 = vx2 === u;
@@ -18444,7 +18550,7 @@ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocol
18444
18550
  return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
18445
18551
  }
18446
18552
  function findSeatPriceForProtocolBefore49(validators, numSeats) {
18447
- const stakes = validators.map((v6) => BigInt(v6.stake)).sort(sortBigIntAsc);
18553
+ const stakes = validators.map((v9) => BigInt(v9.stake)).sort(sortBigIntAsc);
18448
18554
  const num = BigInt(numSeats);
18449
18555
  const stakesSum = stakes.reduce((a, b) => a + b);
18450
18556
  if (stakesSum < num) {
@@ -18473,7 +18579,7 @@ function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumSt
18473
18579
  if (minimumStakeRatio.length != 2) {
18474
18580
  throw Error("minimumStakeRatio should have 2 elements");
18475
18581
  }
18476
- const stakes = validators.map((v6) => BigInt(v6.stake)).sort(sortBigIntAsc);
18582
+ const stakes = validators.map((v9) => BigInt(v9.stake)).sort(sortBigIntAsc);
18477
18583
  const stakesSum = stakes.reduce((a, b) => a + b);
18478
18584
  if (validators.length < maxNumberOfSeats) {
18479
18585
  return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
@@ -18645,10 +18751,10 @@ var DER = {
18645
18751
  if (length < 128)
18646
18752
  throw new E("tlv.decode(long): not minimal encoding");
18647
18753
  }
18648
- const v6 = data.subarray(pos, pos + length);
18649
- if (v6.length !== length)
18754
+ const v9 = data.subarray(pos, pos + length);
18755
+ if (v9.length !== length)
18650
18756
  throw new E("tlv.decode: wrong value length");
18651
- return { v: v6, l: data.subarray(pos + length) };
18757
+ return { v: v9, l: data.subarray(pos + length) };
18652
18758
  }
18653
18759
  },
18654
18760
  // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
@@ -19216,9 +19322,9 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19216
19322
  extraEntropy: false
19217
19323
  };
19218
19324
  const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
19219
- function isBiggerThanHalfOrder(number3) {
19325
+ function isBiggerThanHalfOrder(number5) {
19220
19326
  const HALF = CURVE_ORDER >> _1n6;
19221
- return number3 > HALF;
19327
+ return number5 > HALF;
19222
19328
  }
19223
19329
  function validateRS(title, num) {
19224
19330
  if (!Fn.isValidNot0(num))
@@ -19401,8 +19507,8 @@ function ecdsa(Point, hash, ecdsaOpts = {}) {
19401
19507
  const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
19402
19508
  if (R.is0())
19403
19509
  return false;
19404
- const v6 = Fn.create(R.x);
19405
- return v6 === r;
19510
+ const v9 = Fn.create(R.x);
19511
+ return v9 === r;
19406
19512
  } catch (e) {
19407
19513
  return false;
19408
19514
  }
@@ -22418,7 +22524,17 @@ var IntentDataType = /* @__PURE__ */ ((IntentDataType2) => {
22418
22524
  })(IntentDataType || {});
22419
22525
  var HOOK_DELIVERY_ABI = {
22420
22526
  // HyperCoreDepositHook expects `abi.encode(address)` — the HyperCore account to credit.
22421
- [HookKind.HYPERCORE_DEPOSIT]: [{ name: "recipient", type: "address" }]
22527
+ [HookKind.HYPERCORE_DEPOSIT]: [{ name: "recipient", type: "address" }],
22528
+ // FlintDepositHook expects `abi.encode(address)` — the ERC-7540 controller the deposit request is
22529
+ // recorded against, i.e. the account that ends up owning the resulting flUSD shares. Same shape as
22530
+ // HyperCore's today; kept as its own entry so the two can diverge without touching each other.
22531
+ [HookKind.FLINT_DEPOSIT]: [{ name: "recipient", type: "address" }]
22532
+ };
22533
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
22534
+ var assertUnsupportedHook = (request) => {
22535
+ throw new Error(
22536
+ `[HookService.encodeDeliveryData] Unsupported delivery hook kind: ${request.kind}`
22537
+ );
22422
22538
  };
22423
22539
  var HookService = class _HookService {
22424
22540
  constructor() {
@@ -22427,17 +22543,28 @@ var HookService = class _HookService {
22427
22543
  * Encodes a hook's `deliveryData` payload. One common entry point for all hooks — the encoding is
22428
22544
  * selected by {@link HookRequest.kind} and uses that hook's schema from {@link HOOK_DELIVERY_ABI}.
22429
22545
  *
22546
+ * Rejects the zero address. Every hook treats its recipient as the account to credit, and a
22547
+ * zero recipient is unrecoverable on arrival: the receiver reverts, which rolls back the whole
22548
+ * cross-chain withdrawal inside `SpokeAssetManager.recvMessage` and leaves the message wedged —
22549
+ * every retry hits the same revert. Failing here keeps that mistake client-side, before an intent
22550
+ * exists. Malformed and non-EVM addresses already throw inside viem's encoder.
22551
+ *
22430
22552
  * @param request - The hook selection (and any hook-specific params).
22431
22553
  * @param recipient - The end recipient the hook should credit (the intent's `dstAddress`).
22432
22554
  */
22433
22555
  static encodeDeliveryData(request, recipient) {
22556
+ invariant(
22557
+ recipient.toLowerCase() !== ZERO_ADDRESS,
22558
+ "[HookService.encodeDeliveryData] recipient (dstAddress) must not be the zero address"
22559
+ );
22434
22560
  switch (request.kind) {
22435
22561
  case HookKind.HYPERCORE_DEPOSIT:
22436
22562
  return viem.encodeAbiParameters(HOOK_DELIVERY_ABI[HookKind.HYPERCORE_DEPOSIT], [recipient]);
22563
+ case HookKind.FLINT_DEPOSIT:
22564
+ return viem.encodeAbiParameters(HOOK_DELIVERY_ABI[HookKind.FLINT_DEPOSIT], [recipient]);
22565
+ default:
22566
+ return assertUnsupportedHook(request);
22437
22567
  }
22438
- throw new Error(
22439
- `[HookService.encodeDeliveryData] Unsupported delivery hook kind: ${request.kind}`
22440
- );
22441
22568
  }
22442
22569
  /**
22443
22570
  * Resolves a high-level {@link HookRequest} to the on-chain delivery pair: the deployed hook address
@@ -24805,6 +24932,12 @@ var SpokeService = class _SpokeService {
24805
24932
  /**
24806
24933
  * Approve ERC-20 spending on hub / EVM spoke or request a Stellar trustline using unified params.
24807
24934
  * Feature services map their action payloads into {@link SpokeApproveParams}.
24935
+ *
24936
+ * A signed ERC-20 approval can take **two** transactions: a token of the TetherToken lineage
24937
+ * rejects an allowance change from one non-zero value to another, so a stale allowance is zeroed
24938
+ * first and the user signs twice. The returned hash is always the last transaction's, so the
24939
+ * contract callers see is unchanged. An unsigned caller still gets exactly one transaction — use
24940
+ * {@link SpokeService.buildApproveTxs} to get the whole plan.
24808
24941
  */
24809
24942
  async approve(params) {
24810
24943
  try {
@@ -24812,53 +24945,168 @@ var SpokeService = class _SpokeService {
24812
24945
  isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, params.walletProvider),
24813
24946
  `Invalid wallet provider for chain key: ${params.srcChainKey}, walletProvider.chainType: ${params.walletProvider?.chainType}`
24814
24947
  );
24815
- if (isSpokeApproveParamsHub(params)) {
24816
- const result = await Erc20Service.approve({
24817
- ...params,
24818
- token: params.token,
24819
- amount: params.amount,
24820
- from: params.owner,
24821
- spender: params.spender
24822
- });
24948
+ if (isSpokeApproveParamsHub(params) || isSpokeApproveParamsEvmSpoke(params)) {
24949
+ if (params.raw) {
24950
+ const tx = await Erc20Service.approve({
24951
+ ...params,
24952
+ token: params.token,
24953
+ amount: params.amount,
24954
+ from: params.owner,
24955
+ spender: params.spender
24956
+ });
24957
+ return { ok: true, value: tx };
24958
+ }
24959
+ const result = await this.executeErc20ApprovalPlan(params);
24960
+ if (!result.ok) {
24961
+ return result;
24962
+ }
24823
24963
  return {
24824
24964
  ok: true,
24825
- value: result
24965
+ value: result.value
24826
24966
  };
24827
24967
  }
24828
- if (isSpokeApproveParamsEvmSpoke(params)) {
24829
- const result = await Erc20Service.approve({
24830
- ...params,
24831
- token: params.token,
24832
- amount: params.amount,
24833
- from: params.owner,
24834
- spender: params.spender
24835
- });
24968
+ if (isSpokeApproveParamsStellar(params)) {
24969
+ const result = await this.requestTrustlineForApproval(params);
24836
24970
  return {
24837
24971
  ok: true,
24838
24972
  value: result
24839
24973
  };
24840
24974
  }
24841
- if (isSpokeApproveParamsStellar(params)) {
24842
- const result = await this.stellar.requestTrustline({
24843
- ...params,
24844
- srcAddress: params.owner,
24845
- srcChainKey: params.srcChainKey,
24975
+ return {
24976
+ ok: false,
24977
+ error: new Error("[SpokeService.approve] Only hub (Sonic), EVM spokes, and Stellar are supported")
24978
+ };
24979
+ } catch (error) {
24980
+ return { ok: false, error };
24981
+ }
24982
+ }
24983
+ /**
24984
+ * The unsigned approval transactions, named rather than ordered (see {@link ApprovalTxs}).
24985
+ *
24986
+ * `resetTx` is present only when the token needs its stale allowance cleared first (see
24987
+ * {@link Erc20Service.planApproval}); broadcast it and wait for it to be mined before `approveTx`,
24988
+ * which is not valid until the reset has landed. Unsigned callers — the swaps API and the apps
24989
+ * built on it — need this, because {@link SpokeService.approve} can only hand back a single `tx`.
24990
+ *
24991
+ * Deliberately separate from {@link SpokeService.approve} rather than a mode of it: the two return
24992
+ * genuinely different shapes, and folding them together would put a union in the return type of
24993
+ * the method every feature approves through.
24994
+ */
24995
+ async buildApproveTxs(params) {
24996
+ try {
24997
+ if (isSpokeApproveParamsHub(params) || isSpokeApproveParamsEvmSpoke(params)) {
24998
+ const plan = await this.planErc20Approval(params, "buildApproveTxs");
24999
+ const encode3 = (amount) => Erc20Service.approve({
24846
25000
  token: params.token,
24847
- amount: params.amount
25001
+ amount,
25002
+ from: params.owner,
25003
+ spender: params.spender,
25004
+ raw: true
24848
25005
  });
25006
+ const resetTx = plan.resetAmount === void 0 ? void 0 : await encode3(plan.resetAmount);
25007
+ const approveTx = await encode3(plan.approveAmount);
25008
+ return { ok: true, value: resetTx === void 0 ? { approveTx } : { resetTx, approveTx } };
25009
+ }
25010
+ if (isSpokeApproveParamsStellar(params)) {
25011
+ const tx = await this.requestTrustlineForApproval({ ...params, raw: true });
24849
25012
  return {
24850
25013
  ok: true,
24851
- value: result
25014
+ value: { approveTx: tx }
24852
25015
  };
24853
25016
  }
24854
25017
  return {
24855
25018
  ok: false,
24856
- error: new Error("[SpokeService.approve] Only hub (Sonic), EVM spokes, and Stellar are supported")
25019
+ error: new Error("[SpokeService.buildApproveTxs] Only hub (Sonic), EVM spokes, and Stellar are supported")
24857
25020
  };
24858
25021
  } catch (error) {
24859
25022
  return { ok: false, error };
24860
25023
  }
24861
25024
  }
25025
+ /**
25026
+ * Sign and broadcast the approval plan for an ERC-20 on the hub or an EVM spoke.
25027
+ *
25028
+ * A token of the TetherToken lineage rejects an allowance change from one non-zero value to
25029
+ * another, so a wallet holding a stale allowance needs `approve(0)` first. The transactions cannot
25030
+ * be batched: each one is only valid once its predecessor has been mined. The hash of the last is
25031
+ * returned, so the contract callers see is unchanged.
25032
+ */
25033
+ async executeErc20ApprovalPlan(params) {
25034
+ const { walletProvider } = params;
25035
+ invariant(
25036
+ walletProvider !== void 0 && isEvmWalletProviderType(walletProvider),
25037
+ "[SpokeService.approve] Expected an EVM wallet provider for a signed approval"
25038
+ );
25039
+ const plan = await this.planErc20Approval(params, "approve");
25040
+ const sendApprove = (amount) => Erc20Service.approve({
25041
+ token: params.token,
25042
+ amount,
25043
+ from: params.owner,
25044
+ spender: params.spender,
25045
+ raw: false,
25046
+ walletProvider
25047
+ });
25048
+ if (plan.resetAmount !== void 0) {
25049
+ const resetHash = await sendApprove(plan.resetAmount);
25050
+ const receipt = await this.waitForTxReceipt({ txHash: resetHash, chainKey: params.srcChainKey });
25051
+ if (!receipt.ok || receipt.value.status !== "success") {
25052
+ return {
25053
+ ok: false,
25054
+ error: new Error(
25055
+ `[SpokeService.approve] allowance reset transaction ${resetHash} did not confirm. Retry the approval \u2014 once the reset has landed it takes a single transaction.`
25056
+ )
25057
+ };
25058
+ }
25059
+ }
25060
+ const txHash = await sendApprove(plan.approveAmount);
25061
+ return { ok: true, value: txHash };
25062
+ }
25063
+ /**
25064
+ * Stellar approves by adding a trustline — always a single transaction, with no allowance to plan
25065
+ * around. Shared by both entry points so the param mapping and its cast live in one place.
25066
+ */
25067
+ requestTrustlineForApproval(params) {
25068
+ return this.stellar.requestTrustline({
25069
+ ...params,
25070
+ srcAddress: params.owner,
25071
+ srcChainKey: params.srcChainKey,
25072
+ token: params.token,
25073
+ amount: params.amount
25074
+ });
25075
+ }
25076
+ /** Resolve the chain-specific inputs {@link Erc20Service.planApproval} needs, and record the plan. */
25077
+ async planErc20Approval(params, caller) {
25078
+ const plan = await Erc20Service.planApproval({
25079
+ token: params.token,
25080
+ owner: params.owner,
25081
+ spender: params.spender,
25082
+ amount: params.amount,
25083
+ nativeToken: this.config.getChainConfig(params.srcChainKey).nativeToken,
25084
+ publicClient: this.getEvmPublicClient(params.srcChainKey)
25085
+ });
25086
+ this.logApprovalPlan(caller, params.srcChainKey, params.token, plan);
25087
+ return plan;
25088
+ }
25089
+ /** The read client for an EVM chain, whether it is the hub or a spoke. */
25090
+ getEvmPublicClient(chainKey) {
25091
+ return isHubChainKeyType(chainKey) ? this.sonic.publicClient : this.evm.getPublicClient(chainKey);
25092
+ }
25093
+ /**
25094
+ * Log a plan only when it says something: an extra transaction the user will have to sign, or a
25095
+ * probe that could not reach a verdict. The ordinary single approve is the vast majority of calls
25096
+ * and stays silent.
25097
+ */
25098
+ logApprovalPlan(caller, chainKey, token, plan) {
25099
+ const isNoteworthy = plan.resetAmount !== void 0 || plan.reason === "reset-not-viable" || plan.reason === "allowance-read-failed";
25100
+ if (!isNoteworthy) {
25101
+ return;
25102
+ }
25103
+ this.config.logger.debug(`[SpokeService.${caller}] approval plan`, {
25104
+ chainKey,
25105
+ token,
25106
+ needsReset: plan.resetAmount !== void 0,
25107
+ reason: plan.reason
25108
+ });
25109
+ }
24862
25110
  /**
24863
25111
  * Estimate the gas for a raw transaction.
24864
25112
  * @param {TxReturnType<T, true>} params - The parameters for the raw transaction.
@@ -26696,6 +26944,36 @@ var SolverApiService = class {
26696
26944
  }
26697
26945
  }
26698
26946
  };
26947
+
26948
+ // src/backendApi/pollBackendSubmitTx.ts
26949
+ async function pollBackendSubmitTx({
26950
+ deadline,
26951
+ terminalStatus,
26952
+ getStatus,
26953
+ onExecuted,
26954
+ intervalMs = 1e3,
26955
+ requestTimeoutMs
26956
+ }) {
26957
+ const reserveMs = Math.min(Math.ceil((deadline - Date.now()) / 3), 2e4);
26958
+ const pollDeadline = deadline - reserveMs;
26959
+ const requestOverride = () => requestTimeoutMs === void 0 ? void 0 : { timeout: Math.min(pollDeadline - Date.now(), requestTimeoutMs) };
26960
+ while (Date.now() < pollDeadline) {
26961
+ const statusResult = await getStatus(requestOverride());
26962
+ if (statusResult.ok) {
26963
+ const { status, result, failureReason, abandonedAt } = statusResult.value.data;
26964
+ if (status === terminalStatus) {
26965
+ const value = onExecuted(result);
26966
+ if (value !== void 0) return { ok: true, value };
26967
+ }
26968
+ if (status === "failed" || abandonedAt) {
26969
+ const reason = failureReason ? `: ${failureReason}` : "";
26970
+ return { ok: false, cause: new Error(`backend submit-tx ${status}${reason}`) };
26971
+ }
26972
+ }
26973
+ await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, pollDeadline - Date.now())));
26974
+ }
26975
+ return { ok: false, cause: new Error(`backend submit-tx polling timed out before reaching ${terminalStatus}`) };
26976
+ }
26699
26977
  function decodePacketIntentTarget(payload) {
26700
26978
  try {
26701
26979
  const hex = payload.startsWith("0x") ? payload.slice(2) : payload;
@@ -27018,7 +27296,7 @@ var SwapService = class {
27018
27296
  relayerApiEndpoint: this.relayerApiEndpoint,
27019
27297
  // Remaining shared budget: ≈ full `timeout` on the flag-off path (called immediately), or
27020
27298
  // the reserve `submitTx` left on the backend path. Floor keeps a stalled-backend fallback viable.
27021
- timeout: Math.max(deadline - Date.now(), 5e3)
27299
+ timeout: Math.max(deadline - Date.now(), RELAY_FALLBACK_FLOOR_MS)
27022
27300
  });
27023
27301
  if (!packet.ok) {
27024
27302
  return { ok: false, error: mapRelayFailure(packet.error, { feature: "swap", action: "swap", ...baseCtx }) };
@@ -27080,39 +27358,26 @@ var SwapService = class {
27080
27358
  relayData: relayData.payload
27081
27359
  });
27082
27360
  if (!submitted.ok) return submitTxFailed(submitted.error);
27083
- const reserveMs = Math.min(Math.ceil((deadline - Date.now()) / 3), 2e4);
27084
- const pollDeadline = deadline - reserveMs;
27085
- const pollIntervalMs = 1e3;
27086
- while (Date.now() < pollDeadline) {
27087
- const statusResult = await this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey });
27088
- if (statusResult.ok) {
27089
- const { status, result, failureReason, abandonedAt } = statusResult.value.data;
27090
- if (status === "solved" && result?.dstIntentTxHash && result.intent_hash) {
27091
- return {
27092
- ok: true,
27093
- value: {
27094
- // Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
27095
- solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
27096
- intent,
27097
- intentDeliveryInfo: {
27098
- srcChainKey,
27099
- srcTxHash: spokeTxHash,
27100
- srcAddress: params.srcAddress,
27101
- dstChainKey: params.dstChainKey,
27102
- dstTxHash: result.dstIntentTxHash,
27103
- dstAddress: params.dstAddress
27104
- }
27105
- }
27106
- };
27107
- }
27108
- if (status === "failed" || abandonedAt) {
27109
- const reason = failureReason ? `: ${failureReason}` : "";
27110
- return submitTxFailed(new Error(`backend submit-tx ${status}${reason}`));
27361
+ const polled = await pollBackendSubmitTx({
27362
+ deadline,
27363
+ // Swaps terminal success is `solved` (solver filled) — not the bridge `executed`.
27364
+ terminalStatus: "solved",
27365
+ getStatus: () => this.backendApi.swaps.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey }),
27366
+ onExecuted: (result) => result?.dstIntentTxHash && result.intent_hash ? {
27367
+ // Backend serializes the hex intent_hash as a plain string; brand it at the boundary.
27368
+ solverExecutionResponse: { answer: "OK", intent_hash: result.intent_hash },
27369
+ intent,
27370
+ intentDeliveryInfo: {
27371
+ srcChainKey,
27372
+ srcTxHash: spokeTxHash,
27373
+ srcAddress: params.srcAddress,
27374
+ dstChainKey: params.dstChainKey,
27375
+ dstTxHash: result.dstIntentTxHash,
27376
+ dstAddress: params.dstAddress
27111
27377
  }
27112
- }
27113
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
27114
- }
27115
- return submitTxFailed(new Error("backend submit-tx polling timed out before reaching solved"));
27378
+ } : void 0
27379
+ });
27380
+ return polled.ok ? { ok: true, value: polled.value } : submitTxFailed(polled.cause);
27116
27381
  } catch (error) {
27117
27382
  return { ok: false, error: unknownFailed("swap", error, { ...baseCtx, action: "swap" }) };
27118
27383
  }
@@ -27174,9 +27439,13 @@ var SwapService = class {
27174
27439
  * - Stellar: approves the trustline (adds/increases it).
27175
27440
  * - Other chain types: returns an error — approval is not supported.
27176
27441
  *
27177
- * When `raw: true`, returns unsigned transaction data instead of broadcasting.
27442
+ * When `raw: true`, returns unsigned transaction data instead of broadcasting. That is always a
27443
+ * single transaction, which cannot express the two-step approval a TetherToken-lineage token
27444
+ * needs when a stale allowance already exists — use {@link SwapService.buildApproveTxs} for the
27445
+ * whole plan.
27178
27446
  * When `raw: false`, a matching wallet provider for `K` must be supplied and the transaction
27179
- * is signed and broadcast immediately.
27447
+ * is signed and broadcast immediately. Such an approval can take **two** transactions, so the
27448
+ * user may sign twice; the returned hash is the last one's.
27180
27449
  *
27181
27450
  * @param _params - Swap action params including the source chain key, input token, amount, and wallet provider.
27182
27451
  * @returns A `Result` wrapping the chain-specific transaction return type (`TxReturnType<K, Raw>`).
@@ -27246,6 +27515,62 @@ var SwapService = class {
27246
27515
  return { ok: false, error };
27247
27516
  }
27248
27517
  }
27518
+ /**
27519
+ * The unsigned approval transactions for the swap's source token, in the order they must be
27520
+ * broadcast.
27521
+ *
27522
+ * Two transactions when the source token needs its stale allowance cleared first, one otherwise.
27523
+ * {@link SwapService.approve} is unchanged and still returns a single transaction; this is the
27524
+ * entry point for unsigned callers that need to handle the two-step case. When `resetTx` is
27525
+ * present, broadcast it and wait for it to be mined first — `approveTx` is not valid until the
27526
+ * reset has landed.
27527
+ */
27528
+ async buildApproveTxs(_params) {
27529
+ const { params } = _params;
27530
+ const wrapApproveFailure = (cause) => approveFailed("swap", cause);
27531
+ try {
27532
+ if (isHubChainKeyType(params.srcChainKey) || isEvmSpokeOnlyChainKeyType(params.srcChainKey)) {
27533
+ const spender = isHubChainKeyType(params.srcChainKey) ? this.solver.intentsContract : this.config.getChainConfig(params.srcChainKey).addresses.assetManager;
27534
+ const result = await this.spoke.buildApproveTxs({
27535
+ srcChainKey: params.srcChainKey,
27536
+ owner: params.srcAddress,
27537
+ token: params.inputToken,
27538
+ amount: params.inputAmount,
27539
+ spender,
27540
+ raw: true
27541
+ });
27542
+ if (!result.ok) {
27543
+ return { ok: false, error: wrapApproveFailure(result.error) };
27544
+ }
27545
+ return {
27546
+ ok: true,
27547
+ value: result.value
27548
+ };
27549
+ }
27550
+ if (isStellarChainKeyType(params.srcChainKey)) {
27551
+ const result = await this.spoke.buildApproveTxs({
27552
+ srcChainKey: params.srcChainKey,
27553
+ token: params.inputToken,
27554
+ amount: params.inputAmount,
27555
+ owner: params.srcAddress,
27556
+ raw: true
27557
+ });
27558
+ if (!result.ok) {
27559
+ return { ok: false, error: wrapApproveFailure(result.error) };
27560
+ }
27561
+ return {
27562
+ ok: true,
27563
+ value: result.value
27564
+ };
27565
+ }
27566
+ return {
27567
+ ok: false,
27568
+ error: new Error("Approve only supported for hub (Sonic), EVM spokes, and Stellar")
27569
+ };
27570
+ } catch (error) {
27571
+ return { ok: false, error };
27572
+ }
27573
+ }
27249
27574
  /**
27250
27575
  * Creates a swap intent on the user's source spoke chain without submitting it to the solver.
27251
27576
  *
@@ -27304,10 +27629,19 @@ var SwapService = class {
27304
27629
  `Invalid spoke chain (params.dstChain): ${params.dstChainKey}`,
27305
27630
  { ...baseCtx, field: "dstChainKey" }
27306
27631
  );
27307
- if (isBitcoinChainKey(params.dstChainKey) && params.outputToken === "BTC") {
27632
+ const inputTokenInfo = this.config.getSpokeTokenFromOriginalAssetAddress(params.srcChainKey, params.inputToken);
27633
+ if (isNativeBitcoinTransfer(this.config, params.srcChainKey, inputTokenInfo)) {
27308
27634
  swapInvariant(
27309
- params.minOutputAmount >= 546n,
27310
- `Invalid minOutputAmount (params.minOutputAmount): ${params.minOutputAmount}`,
27635
+ params.inputAmount >= BITCOIN_DUST_SATS,
27636
+ `Invalid inputAmount (${params.inputAmount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
27637
+ { ...baseCtx, field: "inputAmount" }
27638
+ );
27639
+ }
27640
+ const outputTokenInfo = this.config.getSpokeTokenFromOriginalAssetAddress(params.dstChainKey, params.outputToken);
27641
+ if (isNativeBitcoinTransfer(this.config, params.dstChainKey, outputTokenInfo)) {
27642
+ swapInvariant(
27643
+ params.minOutputAmount >= BITCOIN_DUST_SATS,
27644
+ `Invalid minOutputAmount (${params.minOutputAmount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
27311
27645
  { ...baseCtx, field: "minOutputAmount" }
27312
27646
  );
27313
27647
  }
@@ -29876,6 +30210,7 @@ function trimTrailingSlashes(baseURL) {
29876
30210
  while (end > 0 && baseURL[end - 1] === "/") end -= 1;
29877
30211
  return baseURL.slice(0, end);
29878
30212
  }
30213
+ var toJsonBody = (value) => JSON.stringify(value, (_key, val) => typeof val === "bigint" ? val.toString() : val);
29879
30214
  async function makeRequest(params) {
29880
30215
  const { endpoint, config, overrideConfig = {}, logger, serviceLabel } = params;
29881
30216
  const baseURL = overrideConfig.baseURL || config.baseURL || "";
@@ -29982,7 +30317,7 @@ var SwapsApiService = class _SwapsApiService {
29982
30317
  if (error.code === "VALIDATION_ERROR" && error.context.issues !== void 0) {
29983
30318
  context.reason = "invalid_response_shape";
29984
30319
  const issues = error.context.issues;
29985
- context.issues = issues instanceof v4__namespace.ValiError ? v4__namespace.flatten(issues.issues) : issues;
30320
+ context.issues = issues instanceof v7__namespace.ValiError ? v7__namespace.flatten(issues.issues) : issues;
29986
30321
  }
29987
30322
  if (error.context.status !== void 0) context.status = error.context.status;
29988
30323
  }
@@ -30143,21 +30478,21 @@ var SwapsApiService = class _SwapsApiService {
30143
30478
  return this.config.baseURL;
30144
30479
  }
30145
30480
  };
30146
- var StellarSponsorConfigSchema = v4__namespace.object({
30147
- sponsorAccount: v4__namespace.string(),
30148
- networkPassphrase: v4__namespace.string(),
30149
- minTotalFeeStroops: v4__namespace.string(),
30150
- maxTotalFeeStroops: v4__namespace.string(),
30151
- operationCount: v4__namespace.number(),
30152
- minPerOperationFeeStroops: v4__namespace.string(),
30153
- maxPerOperationFeeStroops: v4__namespace.string(),
30154
- recommendedPerOperationFeeStroops: v4__namespace.string(),
30155
- maxTimeboundSeconds: v4__namespace.number(),
30156
- requiredStartingBalance: v4__namespace.string()
30481
+ var StellarSponsorConfigSchema = v7__namespace.object({
30482
+ sponsorAccount: v7__namespace.string(),
30483
+ networkPassphrase: v7__namespace.string(),
30484
+ minTotalFeeStroops: v7__namespace.string(),
30485
+ maxTotalFeeStroops: v7__namespace.string(),
30486
+ operationCount: v7__namespace.number(),
30487
+ minPerOperationFeeStroops: v7__namespace.string(),
30488
+ maxPerOperationFeeStroops: v7__namespace.string(),
30489
+ recommendedPerOperationFeeStroops: v7__namespace.string(),
30490
+ maxTimeboundSeconds: v7__namespace.number(),
30491
+ requiredStartingBalance: v7__namespace.string()
30157
30492
  });
30158
- var StellarSponsoredAccountResponseSchema = v4__namespace.variant("alreadyActive", [
30159
- v4__namespace.object({ hash: v4__namespace.string(), alreadyActive: v4__namespace.literal(false) }),
30160
- v4__namespace.object({ hash: v4__namespace.null(), alreadyActive: v4__namespace.literal(true) })
30493
+ var StellarSponsoredAccountResponseSchema = v7__namespace.variant("alreadyActive", [
30494
+ v7__namespace.object({ hash: v7__namespace.string(), alreadyActive: v7__namespace.literal(false) }),
30495
+ v7__namespace.object({ hash: v7__namespace.null(), alreadyActive: v7__namespace.literal(true) })
30161
30496
  ]);
30162
30497
 
30163
30498
  // src/backendApi/SponsoringApiService.ts
@@ -30185,7 +30520,7 @@ var SponsoringApiService = class {
30185
30520
  logger: this.logger,
30186
30521
  serviceLabel: "SponsoringApiService"
30187
30522
  });
30188
- const parsed = v4__namespace.safeParse(schema, raw);
30523
+ const parsed = v7__namespace.safeParse(schema, raw);
30189
30524
  if (!parsed.success) {
30190
30525
  return {
30191
30526
  ok: false,
@@ -30193,7 +30528,7 @@ var SponsoringApiService = class {
30193
30528
  api: "sponsoring",
30194
30529
  feature: "backend",
30195
30530
  endpoint,
30196
- issues: v4__namespace.flatten(parsed.issues)
30531
+ issues: v7__namespace.flatten(parsed.issues)
30197
30532
  })
30198
30533
  };
30199
30534
  }
@@ -30231,6 +30566,411 @@ var SponsoringApiService = class {
30231
30566
  return this.config.baseURL;
30232
30567
  }
30233
30568
  };
30569
+ var RelayExtraDataResponseSchema = v7__namespace.object({
30570
+ address: v7__namespace.string(),
30571
+ payload: v7__namespace.string()
30572
+ });
30573
+ var BridgeTokenSchema = v7__namespace.object({
30574
+ symbol: v7__namespace.string(),
30575
+ name: v7__namespace.string(),
30576
+ decimals: v7__namespace.number(),
30577
+ address: v7__namespace.string(),
30578
+ chainKey: v7__namespace.string(),
30579
+ hubAsset: v7__namespace.string(),
30580
+ vault: v7__namespace.string()
30581
+ });
30582
+ var BridgeTokensResponseSchema = v7__namespace.record(v7__namespace.string(), v7__namespace.array(BridgeTokenSchema));
30583
+ var BridgeTokensByChainResponseSchema = v7__namespace.array(BridgeTokenSchema);
30584
+ var BridgeAllowanceCheckResponseSchema = v7__namespace.object({
30585
+ valid: v7__namespace.boolean()
30586
+ });
30587
+ var makeBridgeApproveResponseSchema = (txSchema) => v7__namespace.object({ tx: txSchema });
30588
+ var makeCreateBridgeIntentResponseSchema = (txSchema) => v7__namespace.object({
30589
+ tx: txSchema,
30590
+ relayData: RelayExtraDataResponseSchema
30591
+ });
30592
+ var BridgeSubmitTxResponseSchema = v7__namespace.object({
30593
+ success: v7__namespace.boolean(),
30594
+ data: v7__namespace.object({
30595
+ status: v7__namespace.picklist(["inserted", "duplicate"]),
30596
+ message: v7__namespace.string()
30597
+ })
30598
+ });
30599
+ var BridgePacketDataSchema = v7__namespace.object({
30600
+ src_chain_id: v7__namespace.number(),
30601
+ src_tx_hash: v7__namespace.string(),
30602
+ src_address: v7__namespace.string(),
30603
+ status: v7__namespace.picklist(["pending", "validating", "executing", "executed"]),
30604
+ dst_chain_id: v7__namespace.number(),
30605
+ conn_sn: v7__namespace.number(),
30606
+ dst_address: v7__namespace.string(),
30607
+ dst_tx_hash: v7__namespace.string(),
30608
+ signatures: v7__namespace.array(v7__namespace.string()),
30609
+ payload: v7__namespace.string()
30610
+ });
30611
+ var BridgeSubmitTxStatusResultSchema = v7__namespace.object({
30612
+ dstIntentTxHash: v7__namespace.string(),
30613
+ packetData: v7__namespace.optional(BridgePacketDataSchema)
30614
+ });
30615
+ var BridgeSubmitTxStatusDataSchema = v7__namespace.object({
30616
+ txHash: v7__namespace.string(),
30617
+ srcChainKey: v7__namespace.string(),
30618
+ status: v7__namespace.string(),
30619
+ failedAtStep: v7__namespace.optional(v7__namespace.string()),
30620
+ failureReason: v7__namespace.optional(v7__namespace.string()),
30621
+ processingAttempts: v7__namespace.number(),
30622
+ abandonedAt: v7__namespace.optional(v7__namespace.string()),
30623
+ result: v7__namespace.optional(BridgeSubmitTxStatusResultSchema),
30624
+ userMessage: v7__namespace.optional(v7__namespace.string())
30625
+ });
30626
+ var BridgeSubmitTxStatusResponseSchema = v7__namespace.object({
30627
+ success: v7__namespace.boolean(),
30628
+ data: BridgeSubmitTxStatusDataSchema
30629
+ });
30630
+ var BridgeFeeResponseSchema = v7__namespace.object({ fee: v7__namespace.string() });
30631
+ var BridgeLimitSchema = v7__namespace.object({
30632
+ amount: v7__namespace.string(),
30633
+ decimals: v7__namespace.number(),
30634
+ type: v7__namespace.picklist(["DEPOSIT_LIMIT", "WITHDRAWAL_LIMIT"])
30635
+ });
30636
+ var BridgeableAmountResponseSchema = v7__namespace.object({ limit: BridgeLimitSchema });
30637
+ var BridgeableCheckResponseSchema = v7__namespace.object({ bridgeable: v7__namespace.boolean() });
30638
+ var AddressSchema = v7__namespace.custom((input) => typeof input === "string");
30639
+ var HexSchema = v7__namespace.custom((input) => typeof input === "string");
30640
+ var BigintFromString = v7__namespace.pipe(v7__namespace.string(), v7__namespace.toBigint());
30641
+ var BytesFromIndexRecord = v7__namespace.pipe(
30642
+ v7__namespace.record(v7__namespace.string(), v7__namespace.number()),
30643
+ v7__namespace.transform((indexed) => Uint8Array.from(Object.values(indexed)))
30644
+ );
30645
+ var EvmRawTxSchema = v7__namespace.object({
30646
+ from: AddressSchema,
30647
+ to: AddressSchema,
30648
+ value: BigintFromString,
30649
+ data: HexSchema
30650
+ });
30651
+ var SolanaRawTxSchema = v7__namespace.object({
30652
+ from: v7__namespace.string(),
30653
+ to: v7__namespace.string(),
30654
+ value: BigintFromString,
30655
+ data: v7__namespace.string()
30656
+ });
30657
+ var SuiRawTxSchema = v7__namespace.object({
30658
+ from: HexSchema,
30659
+ to: v7__namespace.string(),
30660
+ value: BigintFromString,
30661
+ data: v7__namespace.string()
30662
+ });
30663
+ var StellarRawTxSchema = v7__namespace.object({
30664
+ from: v7__namespace.string(),
30665
+ to: v7__namespace.string(),
30666
+ value: BigintFromString,
30667
+ data: v7__namespace.string()
30668
+ });
30669
+ var BitcoinRawTxSchema = v7__namespace.object({
30670
+ from: v7__namespace.string(),
30671
+ to: v7__namespace.string(),
30672
+ value: BigintFromString,
30673
+ data: v7__namespace.string()
30674
+ });
30675
+ var InjectiveRawTxSchema = v7__namespace.object({
30676
+ from: HexSchema,
30677
+ to: HexSchema,
30678
+ signedDoc: v7__namespace.object({
30679
+ bodyBytes: BytesFromIndexRecord,
30680
+ authInfoBytes: BytesFromIndexRecord,
30681
+ chainId: v7__namespace.string(),
30682
+ accountNumber: BigintFromString
30683
+ })
30684
+ });
30685
+ var NearRawTxSchema = v7__namespace.object({
30686
+ signerId: v7__namespace.string(),
30687
+ params: v7__namespace.object({
30688
+ contractId: v7__namespace.string(),
30689
+ method: v7__namespace.string(),
30690
+ args: v7__namespace.custom((input) => typeof input === "object" && input !== null),
30691
+ gas: v7__namespace.optional(BigintFromString),
30692
+ deposit: v7__namespace.optional(BigintFromString)
30693
+ })
30694
+ });
30695
+ var IconRawTxSchema = v7__namespace.record(
30696
+ v7__namespace.string(),
30697
+ v7__namespace.union([v7__namespace.string(), v7__namespace.custom((input) => typeof input === "object" && input !== null)])
30698
+ );
30699
+ var StacksRawTxSchema = v7__namespace.object({
30700
+ payload: v7__namespace.string(),
30701
+ estimatedLength: v7__namespace.optional(v7__namespace.number())
30702
+ });
30703
+ var AnyRawTxSchema = v7__namespace.custom((input) => typeof input === "object" && input !== null);
30704
+ function rawTxSchemaForChainKey(chainKey) {
30705
+ let chainType;
30706
+ try {
30707
+ chainType = getChainType(chainKey);
30708
+ } catch {
30709
+ chainType = void 0;
30710
+ }
30711
+ switch (chainType) {
30712
+ case "EVM":
30713
+ return EvmRawTxSchema;
30714
+ case "SOLANA":
30715
+ return SolanaRawTxSchema;
30716
+ case "SUI":
30717
+ return SuiRawTxSchema;
30718
+ case "STELLAR":
30719
+ return StellarRawTxSchema;
30720
+ case "INJECTIVE":
30721
+ return InjectiveRawTxSchema;
30722
+ case "ICON":
30723
+ return IconRawTxSchema;
30724
+ case "STACKS":
30725
+ return StacksRawTxSchema;
30726
+ case "NEAR":
30727
+ return NearRawTxSchema;
30728
+ case "BITCOIN":
30729
+ return BitcoinRawTxSchema;
30730
+ default:
30731
+ return AnyRawTxSchema;
30732
+ }
30733
+ }
30734
+
30735
+ // src/backendApi/BridgeApiService.ts
30736
+ function toCreateBridgeIntentParamsV2(params, extras) {
30737
+ return {
30738
+ srcChainKey: params.srcChainKey,
30739
+ dstChainKey: params.dstChainKey,
30740
+ inputToken: params.srcToken,
30741
+ outputToken: params.dstToken,
30742
+ inputAmount: params.amount.toString(),
30743
+ srcAddress: params.srcAddress,
30744
+ dstAddress: params.recipient,
30745
+ ...extras?.srcPublicKey !== void 0 ? { srcPublicKey: extras.srcPublicKey } : {},
30746
+ ...extras?.bound !== void 0 ? { bound: extras.bound } : {},
30747
+ ...extras?.partnerFee !== void 0 ? { partnerFee: extras.partnerFee } : {}
30748
+ };
30749
+ }
30750
+ var BridgeApiService = class {
30751
+ // Fully-resolved bridge-API config supplied by the caller (BackendApiService resolves the
30752
+ // `ApiConfig` union via `resolveBridgeApiConfig`); this service does not resolve the union.
30753
+ config;
30754
+ headers;
30755
+ logger;
30756
+ constructor(config, logger = consoleLogger) {
30757
+ this.config = config;
30758
+ this.headers = { ...config.headers };
30759
+ this.logger = logger;
30760
+ }
30761
+ /**
30762
+ * Issues a single HTTP request, validates the JSON body against `schema`, and
30763
+ * wraps the result in `Result<T>`. The service-level `baseURL`/`timeout`/
30764
+ * `headers` are merged with the optional per-call `overrideConfig` (which takes
30765
+ * precedence) inside {@link makeRequest}. Every public method delegates here.
30766
+ */
30767
+ async request(endpoint, config, schema, overrideConfig) {
30768
+ try {
30769
+ const raw = await makeRequest({
30770
+ endpoint,
30771
+ config: { baseURL: this.config.baseURL, timeout: this.config.timeout, headers: this.headers, ...config },
30772
+ overrideConfig,
30773
+ logger: this.logger,
30774
+ serviceLabel: "BridgeApiService"
30775
+ });
30776
+ const parsed = v7__namespace.safeParse(schema, raw);
30777
+ if (!parsed.success) {
30778
+ return {
30779
+ ok: false,
30780
+ error: new SodaxError("EXTERNAL_API_ERROR", `Invalid response shape from bridge API for ${endpoint}`, {
30781
+ feature: "backend",
30782
+ context: { api: "bridge", endpoint, reason: "invalid_response_shape", issues: v7__namespace.flatten(parsed.issues) }
30783
+ })
30784
+ };
30785
+ }
30786
+ return { ok: true, value: parsed.output };
30787
+ } catch (error) {
30788
+ return {
30789
+ ok: false,
30790
+ error: new SodaxError(
30791
+ "EXTERNAL_API_ERROR",
30792
+ error instanceof Error ? error.message : `Request to ${endpoint} failed`,
30793
+ {
30794
+ feature: "backend",
30795
+ cause: error,
30796
+ context: { api: "bridge", endpoint }
30797
+ }
30798
+ )
30799
+ };
30800
+ }
30801
+ }
30802
+ // ──────────────────────────────────────────────────────────────────────
30803
+ // Tokens
30804
+ // ──────────────────────────────────────────────────────────────────────
30805
+ /**
30806
+ * Fetch all supported bridge tokens grouped by SpokeChainKey.
30807
+ *
30808
+ * @returns `Result<GetBridgeTokensResponseV2>` — map of chain key → token list.
30809
+ */
30810
+ async getTokens(config) {
30811
+ return this.request("/bridge/tokens", { method: "GET" }, BridgeTokensResponseSchema, config);
30812
+ }
30813
+ /**
30814
+ * Fetch supported bridge tokens for a single SpokeChainKey.
30815
+ *
30816
+ * @param chainKey - SODAX SpokeChainKey (e.g. `0xa4b1.arbitrum`, `solana`).
30817
+ * @returns `Result<GetBridgeTokensByChainResponseV2>` — token list for the chain.
30818
+ */
30819
+ async getTokensByChain(chainKey, config) {
30820
+ return this.request(
30821
+ `/bridge/tokens/${chainKey}`,
30822
+ { method: "GET" },
30823
+ BridgeTokensByChainResponseSchema,
30824
+ config
30825
+ );
30826
+ }
30827
+ // ──────────────────────────────────────────────────────────────────────
30828
+ // Allowance · approve · create intent
30829
+ // ──────────────────────────────────────────────────────────────────────
30830
+ /**
30831
+ * Check whether the source token allowance is already sufficient for the bridge.
30832
+ *
30833
+ * @returns `Result<BridgeAllowanceCheckResponseV2>` — `{ valid }`.
30834
+ */
30835
+ async checkAllowance(body, config) {
30836
+ return this.request(
30837
+ "/bridge/allowance/check",
30838
+ { method: "POST", body: toJsonBody(body) },
30839
+ BridgeAllowanceCheckResponseSchema,
30840
+ config
30841
+ );
30842
+ }
30843
+ /**
30844
+ * Build an unsigned token-approval transaction for the source token.
30845
+ *
30846
+ * @returns `Result<BridgeApproveResponseV2>` — `{ tx }` (chain-specific unsigned tx).
30847
+ */
30848
+ async approve(body, config) {
30849
+ const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
30850
+ return this.request(
30851
+ "/bridge/approve",
30852
+ { method: "POST", body: toJsonBody(body) },
30853
+ makeBridgeApproveResponseSchema(txSchema),
30854
+ config
30855
+ );
30856
+ }
30857
+ /**
30858
+ * Build an unsigned spoke-deposit (create-bridge-intent) transaction.
30859
+ *
30860
+ * @returns `Result<CreateBridgeIntentResponseV2>` — `{ tx, relayData }` (no intent struct).
30861
+ */
30862
+ async createBridgeIntent(body, config) {
30863
+ const txSchema = rawTxSchemaForChainKey(body.srcChainKey);
30864
+ return this.request(
30865
+ "/bridge/intents",
30866
+ { method: "POST", body: toJsonBody(body) },
30867
+ makeCreateBridgeIntentResponseSchema(txSchema),
30868
+ config
30869
+ );
30870
+ }
30871
+ // ──────────────────────────────────────────────────────────────────────
30872
+ // Submit-tx state machine
30873
+ // ──────────────────────────────────────────────────────────────────────
30874
+ /**
30875
+ * Submit a broadcast bridge (spoke-deposit) transaction to be processed (relayed).
30876
+ * Carries the FULL `relayData { address, payload }` envelope. Idempotent on `(txHash, srcChainKey)`.
30877
+ *
30878
+ * @returns `Result<BridgeSubmitTxResponseV2>` — `{ success, data: { status, message } }`.
30879
+ */
30880
+ async submitTx(body, config) {
30881
+ return this.request(
30882
+ "/bridge/submit-tx",
30883
+ { method: "POST", body: toJsonBody(body) },
30884
+ BridgeSubmitTxResponseSchema,
30885
+ config
30886
+ );
30887
+ }
30888
+ /**
30889
+ * Get the processing status of a submitted bridge transaction by `(txHash, srcChainKey)`.
30890
+ *
30891
+ * @returns `Result<BridgeSubmitTxStatusResponseV2>` — `{ success, data }` (processing state).
30892
+ */
30893
+ async getSubmitTxStatus(query, config) {
30894
+ const queryParams = new URLSearchParams({ txHash: query.txHash, srcChainKey: query.srcChainKey });
30895
+ return this.request(
30896
+ `/bridge/submit-tx/status?${queryParams.toString()}`,
30897
+ { method: "GET" },
30898
+ BridgeSubmitTxStatusResponseSchema,
30899
+ config
30900
+ );
30901
+ }
30902
+ // ──────────────────────────────────────────────────────────────────────
30903
+ // Fee · bridgeable quote (read-only; mirror the SDK-core client-side methods)
30904
+ // ──────────────────────────────────────────────────────────────────────
30905
+ /**
30906
+ * Bridge partner fee for an input amount (per-request `partnerFee` override, else the configured default).
30907
+ * NOTE: this is a pure client-side computation
30908
+ * in the SDK core (`sodax.bridge.getFee`) — prefer that (no round-trip); this HTTP variant exists for
30909
+ * parity with the backend `/bridge/fee` endpoint (for consumers using only `sodax.api.bridge`).
30910
+ *
30911
+ * @returns `Result<BridgeFeeResponseV2>` — `{ fee }` (decimal string).
30912
+ */
30913
+ async getFee(body, config) {
30914
+ return this.request(
30915
+ "/bridge/fee",
30916
+ { method: "POST", body: toJsonBody(body) },
30917
+ BridgeFeeResponseSchema,
30918
+ config
30919
+ );
30920
+ }
30921
+ /**
30922
+ * Deposit capacity / withdrawal liquidity for a (from, to) token pair. Computable client-side in the
30923
+ * SDK core (`sodax.bridge.getBridgeableAmount`); this HTTP variant mirrors `/bridge/bridgeable-amount`.
30924
+ *
30925
+ * @returns `Result<BridgeableAmountResponseV2>` — `{ limit }`.
30926
+ */
30927
+ async getBridgeableAmount(body, config) {
30928
+ return this.request(
30929
+ "/bridge/bridgeable-amount",
30930
+ { method: "POST", body: toJsonBody(body) },
30931
+ BridgeableAmountResponseSchema,
30932
+ config
30933
+ );
30934
+ }
30935
+ /**
30936
+ * Whether a (from, to) token pair is bridgeable. Computable client-side in the SDK core
30937
+ * (`sodax.bridge.isBridgeable`); this HTTP variant mirrors `/bridge/bridgeable/check`.
30938
+ *
30939
+ * @returns `Result<BridgeableCheckResponseV2>` — `{ bridgeable }`.
30940
+ */
30941
+ async isBridgeable(body, config) {
30942
+ return this.request(
30943
+ "/bridge/bridgeable/check",
30944
+ { method: "POST", body: toJsonBody(body) },
30945
+ BridgeableCheckResponseSchema,
30946
+ config
30947
+ );
30948
+ }
30949
+ // ──────────────────────────────────────────────────────────────────────
30950
+ // Utilities (parity with SwapsApiService)
30951
+ // ──────────────────────────────────────────────────────────────────────
30952
+ /**
30953
+ * Merge additional headers into the service's default header set. Existing
30954
+ * keys are overwritten; keys absent from `headers` are preserved.
30955
+ */
30956
+ setHeaders(headers) {
30957
+ Object.entries(headers).forEach(([key, value]) => {
30958
+ this.headers[key] = value;
30959
+ });
30960
+ }
30961
+ /** Return the base URL the service is currently pointing at. */
30962
+ getBaseURL() {
30963
+ return this.config.baseURL;
30964
+ }
30965
+ /**
30966
+ * Return the effective per-request timeout (ms). Callers that bound a request tighter than the
30967
+ * service default (e.g. `pollBackendSubmitTx` clamping to its poll cutoff) need this as the ceiling,
30968
+ * because a `RequestOverrideConfig.timeout` REPLACES the service value rather than lowering it.
30969
+ */
30970
+ getTimeout() {
30971
+ return this.config.timeout;
30972
+ }
30973
+ };
30234
30974
 
30235
30975
  // src/backendApi/apiConfig.ts
30236
30976
  function flatLayer({ baseURL, timeout, headers }) {
@@ -30275,143 +31015,147 @@ function resolveSponsoringApiConfig(config) {
30275
31015
  ...slice?.apiKey === void 0 ? {} : { apiKey: slice.apiKey }
30276
31016
  };
30277
31017
  }
30278
- var ChainKeySchema = v4__namespace.custom((input) => typeof input === "string");
30279
- var SpokeChainKeySchema = v4__namespace.custom((input) => typeof input === "string");
30280
- var AddressSchema = v4__namespace.custom((input) => typeof input === "string");
30281
- var XTokenSchema = v4__namespace.object({
30282
- symbol: v4__namespace.string(),
30283
- name: v4__namespace.string(),
30284
- decimals: v4__namespace.number(),
30285
- address: v4__namespace.string(),
31018
+ function resolveBridgeApiConfig(config) {
31019
+ return resolveBaseApiConfig(config);
31020
+ }
31021
+ var ChainKeySchema = v7__namespace.custom((input) => typeof input === "string");
31022
+ var SpokeChainKeySchema = v7__namespace.custom((input) => typeof input === "string");
31023
+ var AddressSchema2 = v7__namespace.custom((input) => typeof input === "string");
31024
+ var XTokenSchema = v7__namespace.object({
31025
+ symbol: v7__namespace.string(),
31026
+ name: v7__namespace.string(),
31027
+ decimals: v7__namespace.number(),
31028
+ address: v7__namespace.string(),
30286
31029
  chainKey: ChainKeySchema,
30287
- hubAsset: AddressSchema,
30288
- vault: AddressSchema,
30289
- access: v4__namespace.optional(v4__namespace.picklist(["withdrawOnly", "depositOnly"]))
31030
+ hubAsset: AddressSchema2,
31031
+ vault: AddressSchema2,
31032
+ access: v7__namespace.optional(v7__namespace.picklist(["withdrawOnly", "depositOnly"]))
30290
31033
  });
30291
- var IntentStructSchema = v4__namespace.object({
30292
- intentId: v4__namespace.string(),
30293
- creator: v4__namespace.string(),
30294
- inputToken: v4__namespace.string(),
30295
- outputToken: v4__namespace.string(),
30296
- inputAmount: v4__namespace.string(),
30297
- minOutputAmount: v4__namespace.string(),
30298
- deadline: v4__namespace.string(),
30299
- allowPartialFill: v4__namespace.boolean(),
30300
- srcChain: v4__namespace.number(),
30301
- dstChain: v4__namespace.number(),
30302
- srcAddress: v4__namespace.string(),
30303
- dstAddress: v4__namespace.string(),
30304
- solver: v4__namespace.string(),
30305
- data: v4__namespace.string()
31034
+ var IntentStructSchema = v7__namespace.object({
31035
+ intentId: v7__namespace.string(),
31036
+ creator: v7__namespace.string(),
31037
+ inputToken: v7__namespace.string(),
31038
+ outputToken: v7__namespace.string(),
31039
+ inputAmount: v7__namespace.string(),
31040
+ minOutputAmount: v7__namespace.string(),
31041
+ deadline: v7__namespace.string(),
31042
+ allowPartialFill: v7__namespace.boolean(),
31043
+ srcChain: v7__namespace.number(),
31044
+ dstChain: v7__namespace.number(),
31045
+ srcAddress: v7__namespace.string(),
31046
+ dstAddress: v7__namespace.string(),
31047
+ solver: v7__namespace.string(),
31048
+ data: v7__namespace.string()
30306
31049
  });
30307
- var IntentResponseSchema = v4__namespace.object({
30308
- intentHash: v4__namespace.string(),
30309
- txHash: v4__namespace.string(),
30310
- logIndex: v4__namespace.number(),
30311
- chainId: v4__namespace.number(),
30312
- blockNumber: v4__namespace.number(),
30313
- open: v4__namespace.boolean(),
31050
+ var IntentResponseSchema = v7__namespace.object({
31051
+ intentHash: v7__namespace.string(),
31052
+ txHash: v7__namespace.string(),
31053
+ logIndex: v7__namespace.number(),
31054
+ chainId: v7__namespace.number(),
31055
+ blockNumber: v7__namespace.number(),
31056
+ open: v7__namespace.boolean(),
30314
31057
  intent: IntentStructSchema,
30315
- events: v4__namespace.array(v4__namespace.unknown())
31058
+ events: v7__namespace.array(v7__namespace.unknown())
30316
31059
  });
30317
- var UserIntentsResponseSchema = v4__namespace.object({
30318
- total: v4__namespace.number(),
30319
- offset: v4__namespace.number(),
30320
- limit: v4__namespace.number(),
30321
- items: v4__namespace.array(IntentResponseSchema)
31060
+ var UserIntentsResponseSchema = v7__namespace.object({
31061
+ total: v7__namespace.number(),
31062
+ offset: v7__namespace.number(),
31063
+ limit: v7__namespace.number(),
31064
+ items: v7__namespace.array(IntentResponseSchema)
30322
31065
  });
30323
- var OrderbookResponseSchema = v4__namespace.object({
30324
- total: v4__namespace.number(),
30325
- data: v4__namespace.array(
30326
- v4__namespace.object({
30327
- intentState: v4__namespace.object({
30328
- exists: v4__namespace.boolean(),
30329
- remainingInput: v4__namespace.string(),
30330
- receivedOutput: v4__namespace.string(),
30331
- pendingPayment: v4__namespace.boolean()
31066
+ var OrderbookResponseSchema = v7__namespace.object({
31067
+ total: v7__namespace.number(),
31068
+ data: v7__namespace.array(
31069
+ v7__namespace.object({
31070
+ intentState: v7__namespace.object({
31071
+ exists: v7__namespace.boolean(),
31072
+ remainingInput: v7__namespace.string(),
31073
+ receivedOutput: v7__namespace.string(),
31074
+ pendingPayment: v7__namespace.boolean()
30332
31075
  }),
30333
- intentData: v4__namespace.object({
30334
- intentId: v4__namespace.string(),
30335
- creator: v4__namespace.string(),
30336
- inputToken: v4__namespace.string(),
30337
- outputToken: v4__namespace.string(),
30338
- inputAmount: v4__namespace.string(),
30339
- minOutputAmount: v4__namespace.string(),
30340
- deadline: v4__namespace.string(),
30341
- allowPartialFill: v4__namespace.boolean(),
30342
- srcChain: v4__namespace.number(),
30343
- dstChain: v4__namespace.number(),
30344
- srcAddress: v4__namespace.string(),
30345
- dstAddress: v4__namespace.string(),
30346
- solver: v4__namespace.string(),
30347
- data: v4__namespace.string(),
30348
- intentHash: v4__namespace.string(),
30349
- txHash: v4__namespace.string(),
30350
- blockNumber: v4__namespace.number()
31076
+ intentData: v7__namespace.object({
31077
+ intentId: v7__namespace.string(),
31078
+ creator: v7__namespace.string(),
31079
+ inputToken: v7__namespace.string(),
31080
+ outputToken: v7__namespace.string(),
31081
+ inputAmount: v7__namespace.string(),
31082
+ minOutputAmount: v7__namespace.string(),
31083
+ deadline: v7__namespace.string(),
31084
+ allowPartialFill: v7__namespace.boolean(),
31085
+ srcChain: v7__namespace.number(),
31086
+ dstChain: v7__namespace.number(),
31087
+ srcAddress: v7__namespace.string(),
31088
+ dstAddress: v7__namespace.string(),
31089
+ solver: v7__namespace.string(),
31090
+ data: v7__namespace.string(),
31091
+ intentHash: v7__namespace.string(),
31092
+ txHash: v7__namespace.string(),
31093
+ blockNumber: v7__namespace.number()
30351
31094
  })
30352
31095
  })
30353
31096
  )
30354
31097
  });
30355
- var MoneyMarketPositionSchema = v4__namespace.object({
30356
- userAddress: v4__namespace.string(),
30357
- positions: v4__namespace.array(
30358
- v4__namespace.object({
30359
- reserveAddress: v4__namespace.string(),
30360
- aTokenAddress: v4__namespace.string(),
30361
- variableDebtTokenAddress: v4__namespace.string(),
30362
- aTokenBalance: v4__namespace.string(),
30363
- variableDebtTokenBalance: v4__namespace.string(),
30364
- blockNumber: v4__namespace.number()
31098
+ var MoneyMarketPositionSchema = v7__namespace.object({
31099
+ userAddress: v7__namespace.string(),
31100
+ positions: v7__namespace.array(
31101
+ v7__namespace.object({
31102
+ reserveAddress: v7__namespace.string(),
31103
+ aTokenAddress: v7__namespace.string(),
31104
+ variableDebtTokenAddress: v7__namespace.string(),
31105
+ aTokenBalance: v7__namespace.string(),
31106
+ variableDebtTokenBalance: v7__namespace.string(),
31107
+ blockNumber: v7__namespace.number()
30365
31108
  })
30366
31109
  )
30367
31110
  });
30368
- var MoneyMarketAssetSchema = v4__namespace.object({
30369
- reserveAddress: v4__namespace.string(),
30370
- aTokenAddress: v4__namespace.string(),
30371
- totalATokenBalance: v4__namespace.string(),
30372
- variableDebtTokenAddress: v4__namespace.string(),
30373
- totalVariableDebtTokenBalance: v4__namespace.string(),
30374
- liquidityRate: v4__namespace.string(),
30375
- symbol: v4__namespace.string(),
30376
- totalSuppliers: v4__namespace.number(),
30377
- totalBorrowers: v4__namespace.number(),
30378
- variableBorrowRate: v4__namespace.string(),
30379
- stableBorrowRate: v4__namespace.string(),
30380
- liquidityIndex: v4__namespace.string(),
30381
- variableBorrowIndex: v4__namespace.string(),
30382
- blockNumber: v4__namespace.number()
31111
+ var MoneyMarketAssetSchema = v7__namespace.object({
31112
+ reserveAddress: v7__namespace.string(),
31113
+ aTokenAddress: v7__namespace.string(),
31114
+ totalATokenBalance: v7__namespace.string(),
31115
+ variableDebtTokenAddress: v7__namespace.string(),
31116
+ totalVariableDebtTokenBalance: v7__namespace.string(),
31117
+ liquidityRate: v7__namespace.string(),
31118
+ symbol: v7__namespace.string(),
31119
+ totalSuppliers: v7__namespace.number(),
31120
+ totalBorrowers: v7__namespace.number(),
31121
+ variableBorrowRate: v7__namespace.string(),
31122
+ stableBorrowRate: v7__namespace.string(),
31123
+ liquidityIndex: v7__namespace.string(),
31124
+ variableBorrowIndex: v7__namespace.string(),
31125
+ blockNumber: v7__namespace.number()
30383
31126
  });
30384
- var MoneyMarketAssetsSchema = v4__namespace.array(MoneyMarketAssetSchema);
30385
- var MoneyMarketAssetBorrowersSchema = v4__namespace.object({
30386
- borrowers: v4__namespace.array(v4__namespace.string()),
30387
- total: v4__namespace.number(),
30388
- offset: v4__namespace.number(),
30389
- limit: v4__namespace.number()
31127
+ var MoneyMarketAssetsSchema = v7__namespace.array(MoneyMarketAssetSchema);
31128
+ var MoneyMarketAssetBorrowersSchema = v7__namespace.object({
31129
+ borrowers: v7__namespace.array(v7__namespace.string()),
31130
+ total: v7__namespace.number(),
31131
+ offset: v7__namespace.number(),
31132
+ limit: v7__namespace.number()
30390
31133
  });
30391
- var MoneyMarketAssetSuppliersSchema = v4__namespace.object({
30392
- suppliers: v4__namespace.array(v4__namespace.string()),
30393
- total: v4__namespace.number(),
30394
- offset: v4__namespace.number(),
30395
- limit: v4__namespace.number()
31134
+ var MoneyMarketAssetSuppliersSchema = v7__namespace.object({
31135
+ suppliers: v7__namespace.array(v7__namespace.string()),
31136
+ total: v7__namespace.number(),
31137
+ offset: v7__namespace.number(),
31138
+ limit: v7__namespace.number()
30396
31139
  });
30397
- var MoneyMarketBorrowersSchema = v4__namespace.object({
30398
- borrowers: v4__namespace.array(v4__namespace.string()),
30399
- total: v4__namespace.number(),
30400
- offset: v4__namespace.number(),
30401
- limit: v4__namespace.number()
31140
+ var MoneyMarketBorrowersSchema = v7__namespace.object({
31141
+ borrowers: v7__namespace.array(v7__namespace.string()),
31142
+ total: v7__namespace.number(),
31143
+ offset: v7__namespace.number(),
31144
+ limit: v7__namespace.number()
30402
31145
  });
30403
- var GetChainsResponseSchema = v4__namespace.array(SpokeChainKeySchema);
30404
- var TokensByChainMapSchema = v4__namespace.custom(
30405
- (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v4__namespace.is(XTokenSchema, t)))
31146
+ var GetChainsResponseSchema = v7__namespace.array(SpokeChainKeySchema);
31147
+ var TokensByChainMapSchema = v7__namespace.custom(
31148
+ (input) => typeof input === "object" && input !== null && Object.values(input).every((tokens) => Array.isArray(tokens) && tokens.every((t) => v7__namespace.is(XTokenSchema, t)))
30406
31149
  );
30407
- var TokensListSchema = v4__namespace.array(XTokenSchema);
30408
- var ReserveAssetsSchema = v4__namespace.array(AddressSchema);
31150
+ var TokensListSchema = v7__namespace.array(XTokenSchema);
31151
+ var ReserveAssetsSchema = v7__namespace.array(AddressSchema2);
30409
31152
 
30410
31153
  // src/backendApi/BackendApiService.ts
30411
31154
  var BackendApiService = class {
30412
31155
  // sub-services exposing domain-specific APIs
30413
31156
  swaps;
30414
31157
  sponsoring;
31158
+ bridge;
30415
31159
  // resolved base-API config: the flat fields of the ApiConfig union with any `baseApiConfig` layered on top
30416
31160
  config;
30417
31161
  headers;
@@ -30422,6 +31166,7 @@ var BackendApiService = class {
30422
31166
  this.logger = logger;
30423
31167
  this.swaps = new SwapsApiService(resolveSwapsApiConfig(config), this.logger);
30424
31168
  this.sponsoring = new SponsoringApiService(resolveSponsoringApiConfig(config), this.logger);
31169
+ this.bridge = new BridgeApiService(resolveBridgeApiConfig(config), this.logger);
30425
31170
  }
30426
31171
  /**
30427
31172
  * Issue a request and validate the JSON body against `schema`, wrapping the result in `Result<T>`.
@@ -30438,7 +31183,7 @@ var BackendApiService = class {
30438
31183
  logger: this.logger,
30439
31184
  serviceLabel: "BackendApiService"
30440
31185
  });
30441
- const parsed = v4__namespace.safeParse(schema, raw);
31186
+ const parsed = v7__namespace.safeParse(schema, raw);
30442
31187
  if (!parsed.success) {
30443
31188
  return {
30444
31189
  ok: false,
@@ -30446,7 +31191,7 @@ var BackendApiService = class {
30446
31191
  api: "backend",
30447
31192
  feature: "backend",
30448
31193
  endpoint,
30449
- issues: v4__namespace.flatten(parsed.issues)
31194
+ issues: v7__namespace.flatten(parsed.issues)
30450
31195
  })
30451
31196
  };
30452
31197
  }
@@ -30781,6 +31526,7 @@ var BackendApiService = class {
30781
31526
  this.headers[key] = value;
30782
31527
  });
30783
31528
  this.swaps.setHeaders(headers);
31529
+ this.bridge.setHeaders(headers);
30784
31530
  }
30785
31531
  /**
30786
31532
  * Return the base URL the service is currently pointing at.
@@ -30831,25 +31577,32 @@ var BridgeService = class {
30831
31577
  hubProvider;
30832
31578
  config;
30833
31579
  spoke;
30834
- constructor({ hubProvider, config, spoke }) {
31580
+ // backend bridge-API client + opt-in backend submit-tx flag
31581
+ backendApi;
31582
+ useBackendSubmitTx;
31583
+ constructor({ hubProvider, config, spoke, backendApi, useBackendSubmitTx }) {
30835
31584
  this.config = config;
30836
31585
  this.hubProvider = hubProvider;
30837
31586
  this.spoke = spoke;
31587
+ this.backendApi = backendApi;
31588
+ this.useBackendSubmitTx = useBackendSubmitTx ?? false;
30838
31589
  }
30839
31590
  /**
30840
31591
  * Calculates the partner fee deducted from a given bridge input amount.
30841
31592
  *
30842
- * Returns `0n` when no partner fee is configured. The fee is denominated in the
30843
- * same units as `inputAmount` (vault token decimals, 18 dp).
31593
+ * Returns `0n` when no partner fee is configured. `inputAmount` must be in 18-dp hub/vault
31594
+ * units — the units the hub deducts the fee in (see `buildBridgeData`) — NOT the spoke token's
31595
+ * native base units. This matters for a fixed `PartnerFee.amount`, which is wei-denominated
31596
+ * (18 dp); a percentage fee is unit-agnostic.
30844
31597
  *
30845
- * @param inputAmount - Gross amount being bridged, in vault token base units.
31598
+ * @param inputAmount - Gross amount being bridged, in 18-dp hub/vault units.
30846
31599
  * @returns Fee amount to be deducted, in the same units as `inputAmount`.
30847
31600
  */
30848
- getFee(inputAmount) {
30849
- if (!this.config.bridgePartnerFee) {
31601
+ getFee(inputAmount, partnerFee = this.config.bridgePartnerFee) {
31602
+ if (!partnerFee) {
30850
31603
  return 0n;
30851
31604
  }
30852
- return calculateFeeAmount(inputAmount, this.config.bridgePartnerFee);
31605
+ return calculateFeeAmount(inputAmount, partnerFee);
30853
31606
  }
30854
31607
  /**
30855
31608
  * Checks whether the caller has sufficient token allowance to execute the bridge.
@@ -31034,42 +31787,21 @@ var BridgeService = class {
31034
31787
  "bridge",
31035
31788
  "bridge",
31036
31789
  async () => {
31037
- const { params, timeout } = _params;
31790
+ const { params } = _params;
31038
31791
  const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
31039
31792
  try {
31040
- const txResult = await this.createBridgeIntent(_params);
31041
- if (!txResult.ok) return { ok: false, error: txResult.error };
31042
- const verifyTxHashResult = await this.spoke.verifyTxHash({
31043
- txHash: txResult.value.tx,
31044
- chainKey: params.srcChainKey
31045
- });
31046
- if (!verifyTxHashResult.ok) {
31047
- return {
31048
- ok: false,
31049
- error: verifyFailed("bridge", verifyTxHashResult.error, baseCtx)
31050
- };
31793
+ const created = await this.createBridgeIntent(_params);
31794
+ if (!created.ok) return { ok: false, error: created.error };
31795
+ const deadline = Date.now() + (_params.timeout ?? DEFAULT_RELAY_TX_TIMEOUT);
31796
+ if (this.useBackendSubmitTx) {
31797
+ const submitted = await this.submitTx(_params, created.value, deadline);
31798
+ if (submitted.ok) return submitted;
31799
+ this.config.logger.warn(
31800
+ "[bridge] backend submit-tx did not complete; falling back to the client-side relay",
31801
+ { error: submitted.error }
31802
+ );
31051
31803
  }
31052
- const packetResult = await relayTxAndWaitPacket({
31053
- srcTxHash: txResult.value.tx,
31054
- data: txResult.value.relayData,
31055
- chainKey: params.srcChainKey,
31056
- relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
31057
- timeout
31058
- });
31059
- if (!packetResult.ok)
31060
- return {
31061
- ok: false,
31062
- error: mapRelayFailure(packetResult.error, {
31063
- feature: "bridge",
31064
- action: "bridge",
31065
- srcChainKey: baseCtx.srcChainKey,
31066
- dstChainKey: baseCtx.dstChainKey
31067
- })
31068
- };
31069
- return {
31070
- ok: true,
31071
- value: { srcChainTxHash: txResult.value.tx, dstChainTxHash: packetResult.value.dst_tx_hash }
31072
- };
31804
+ return this.fallbackBridgeSteps(_params, created.value, deadline);
31073
31805
  } catch (error) {
31074
31806
  if (isBridgeOrchestrationError(error)) return { ok: false, error };
31075
31807
  return {
@@ -31096,6 +31828,98 @@ var BridgeService = class {
31096
31828
  }
31097
31829
  );
31098
31830
  }
31831
+ /**
31832
+ * Client-side bridge completion (the default path): verify the broadcast spoke-deposit tx, then
31833
+ * relay it to the hub and wait for the settlement packet. Extracted verbatim from `bridge()` so the
31834
+ * opt-in backend submit-tx path ({@link submitTx}) can fall back to it on any non-success. Bridge
31835
+ * always relays — there is no hub-source short-circuit.
31836
+ */
31837
+ async fallbackBridgeSteps(_params, created, deadline) {
31838
+ const { params } = _params;
31839
+ const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
31840
+ const verifyTxHashResult = await this.spoke.verifyTxHash({
31841
+ txHash: created.tx,
31842
+ chainKey: params.srcChainKey
31843
+ });
31844
+ if (!verifyTxHashResult.ok) {
31845
+ return { ok: false, error: verifyFailed("bridge", verifyTxHashResult.error, baseCtx) };
31846
+ }
31847
+ const packetResult = await relayTxAndWaitPacket({
31848
+ srcTxHash: created.tx,
31849
+ data: created.relayData,
31850
+ chainKey: params.srcChainKey,
31851
+ relayerApiEndpoint: this.config.relay.relayerApiEndpoint,
31852
+ // Remaining shared budget: ≈ full `timeout` on the flag-off path minus the `verifyTxHash` wait,
31853
+ // or the reserve `submitTx` left on the backend path (`pollBackendSubmitTx` holds back up to a
31854
+ // third, capped at 20s). The floor matters because `relayTxAndWaitPacket` SUBMITS the tx to the
31855
+ // relay before `timeout` bounds anything: a budget exhausted by a slow source-chain confirmation
31856
+ // (Stacks polls for up to its full 120s `maxTimeoutMs`) would otherwise strand an already-landed
31857
+ // deposit unrelayed. Re-relay is idempotent, so always spending the floor is safe.
31858
+ timeout: Math.max(deadline - Date.now(), RELAY_FALLBACK_FLOOR_MS)
31859
+ });
31860
+ if (!packetResult.ok) {
31861
+ return {
31862
+ ok: false,
31863
+ error: mapRelayFailure(packetResult.error, {
31864
+ feature: "bridge",
31865
+ action: "bridge",
31866
+ srcChainKey: baseCtx.srcChainKey,
31867
+ dstChainKey: baseCtx.dstChainKey
31868
+ })
31869
+ };
31870
+ }
31871
+ return {
31872
+ ok: true,
31873
+ value: { srcChainTxHash: created.tx, dstChainTxHash: packetResult.value.dst_tx_hash }
31874
+ };
31875
+ }
31876
+ /**
31877
+ * Backend bridge path (opt-in via `bridgeOptions.useBackendSubmitTx`): hand the broadcast
31878
+ * spoke-deposit tx to the bridge API (`POST /bridge/submit-tx`) with the FULL `relayData`
31879
+ * envelope; the backend relays server-side. Polls `getSubmitTxStatus` until `executed`, then
31880
+ * returns the same {@link TxHashPair} the client-side path returns (`result.dstIntentTxHash` →
31881
+ * destination tx hash; bridge has no solver `intent_hash`).
31882
+ *
31883
+ * Never throws — returns `{ ok: false }` on any non-success (submit `!ok`, terminal `failed` /
31884
+ * abandoned, or poll timeout) so `bridge()` falls back to {@link fallbackBridgeSteps}. Falling back
31885
+ * is safe: re-relaying an already-relayed bridge tx is idempotent — the relay dedups and returns the
31886
+ * existing `executed` packet. Polling stops at `deadline - reserve` so the fallback keeps a
31887
+ * guaranteed slice of the shared `bridge` budget.
31888
+ */
31889
+ async submitTx(_params, created, deadline) {
31890
+ const { params } = _params;
31891
+ const srcChainKey = params.srcChainKey;
31892
+ const baseCtx = { srcChainKey, dstChainKey: params.dstChainKey };
31893
+ const { tx: spokeTxHash, relayData } = created;
31894
+ const submitTxFailed = (cause) => ({
31895
+ ok: false,
31896
+ error: executionFailed("bridge", cause, { ...baseCtx, action: "bridge" })
31897
+ });
31898
+ try {
31899
+ const submitted = await this.backendApi.bridge.submitTx({
31900
+ txHash: spokeTxHash,
31901
+ srcChainKey,
31902
+ walletAddress: params.srcAddress,
31903
+ // Send the FULL { address, payload } envelope — bridge has no intent.creator for the backend
31904
+ // to rebuild the relay address, so dropping it would break split-tx-chain relay.
31905
+ relayData
31906
+ });
31907
+ if (!submitted.ok) return submitTxFailed(submitted.error);
31908
+ const polled = await pollBackendSubmitTx({
31909
+ deadline,
31910
+ // Bridge terminal success is `executed` (hub-settled) — not the swaps `solved`.
31911
+ terminalStatus: "executed",
31912
+ getStatus: (override) => this.backendApi.bridge.getSubmitTxStatus({ txHash: spokeTxHash, srcChainKey }, override),
31913
+ onExecuted: (result) => result?.dstIntentTxHash ? { srcChainTxHash: spokeTxHash, dstChainTxHash: result.dstIntentTxHash } : void 0,
31914
+ // Bound each status request by the poll cutoff, never above the service default — so a stalled
31915
+ // request can neither eat the fallback's reserve nor consume the window in one attempt.
31916
+ requestTimeoutMs: this.backendApi.bridge.getTimeout()
31917
+ });
31918
+ return polled.ok ? { ok: true, value: polled.value } : submitTxFailed(polled.cause);
31919
+ } catch (error) {
31920
+ return { ok: false, error: unknownFailed("bridge", error, { ...baseCtx, action: "bridge" }) };
31921
+ }
31922
+ }
31099
31923
  /**
31100
31924
  * Submits the spoke-side deposit transaction that initiates a bridge transfer,
31101
31925
  * without waiting for the cross-chain relay to complete.
@@ -31119,9 +31943,15 @@ var BridgeService = class {
31119
31943
  * contains the hub wallet address and encoded hub execution payload needed for relay.
31120
31944
  */
31121
31945
  async createBridgeIntent(_params) {
31122
- const { params, skipSimulation } = _params;
31946
+ const { params, skipSimulation, extras } = _params;
31947
+ const partnerFee = extras?.partnerFee ?? this.config.bridgePartnerFee;
31123
31948
  const baseCtx = { srcChainKey: params.srcChainKey, dstChainKey: params.dstChainKey };
31124
31949
  try {
31950
+ bridgeInvariant(
31951
+ isUndefinedOrValidWalletProviderForChainKey(params.srcChainKey, _params.walletProvider),
31952
+ `Invalid wallet provider for chain key: ${params.srcChainKey}`,
31953
+ baseCtx
31954
+ );
31125
31955
  bridgeInvariant(params.amount > 0n, "Amount must be greater than 0", { ...baseCtx, field: "amount" });
31126
31956
  const srcToken = this.resolveBridgeEndpointToken(params.srcChainKey, params.srcToken);
31127
31957
  const dstToken = this.resolveBridgeEndpointToken(params.dstChainKey, params.dstToken);
@@ -31133,25 +31963,62 @@ var BridgeService = class {
31133
31963
  ...baseCtx,
31134
31964
  field: "dstToken"
31135
31965
  });
31136
- const personalAddress = params.srcAddress;
31137
- let walletAddress = personalAddress;
31138
- if (isBitcoinChainKeyType(params.srcChainKey) && _params.raw === false) {
31966
+ bridgeInvariant(
31967
+ this.config.isValidSpokeChainKey(params.srcChainKey),
31968
+ `Invalid spoke chain (srcChainKey): ${params.srcChainKey}`,
31969
+ { ...baseCtx, field: "srcChainKey" }
31970
+ );
31971
+ bridgeInvariant(
31972
+ this.config.isValidSpokeChainKey(params.dstChainKey),
31973
+ `Invalid spoke chain (dstChainKey): ${params.dstChainKey}`,
31974
+ { ...baseCtx, field: "dstChainKey" }
31975
+ );
31976
+ if (isNativeBitcoinTransfer(this.config, params.srcChainKey, srcToken)) {
31139
31977
  bridgeInvariant(
31140
- isBitcoinWalletProviderType(_params.walletProvider),
31141
- `Invalid wallet provider for chain key: ${params.srcChainKey}. Expected bitcoin wallet provider.`,
31142
- { ...baseCtx, field: "walletProvider" }
31978
+ params.amount >= BITCOIN_DUST_SATS,
31979
+ `Invalid amount (${params.amount}): below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
31980
+ { ...baseCtx, field: "amount" }
31143
31981
  );
31144
- walletAddress = await this.spoke.bitcoin.getEffectiveWalletAddress(personalAddress);
31145
- if (this.spoke.bitcoin.walletMode === "TRADING") {
31146
- await this.spoke.bitcoin.radfi.ensureRadfiAccessToken(_params.walletProvider);
31982
+ }
31983
+ if (isNativeBitcoinTransfer(this.config, params.dstChainKey, dstToken)) {
31984
+ const { delivered } = this.computeBridgeAmounts(params.amount, srcToken, dstToken, partnerFee);
31985
+ bridgeInvariant(
31986
+ delivered >= BITCOIN_DUST_SATS,
31987
+ `Post-fee BTC delivery (${delivered}) is below the Bitcoin dust limit of ${BITCOIN_DUST_SATS} sats`,
31988
+ { ...baseCtx, field: "amount" }
31989
+ );
31990
+ }
31991
+ if (isStacksChainKeyType(params.srcChainKey) && _params.raw === true) {
31992
+ bridgeInvariant(
31993
+ extras?.srcPublicKey !== void 0,
31994
+ "srcPublicKey is required for Stacks createBridgeIntent (raw) \u2014 the source tx is built unsigned and needs the signer public key",
31995
+ { ...baseCtx, field: "srcPublicKey" }
31996
+ );
31997
+ }
31998
+ const personalAddress = params.srcAddress;
31999
+ let walletAddress = personalAddress;
32000
+ if (isBitcoinChainKeyType(params.srcChainKey)) {
32001
+ if (_params.raw === false) {
32002
+ bridgeInvariant(
32003
+ isBitcoinWalletProviderType(_params.walletProvider),
32004
+ `Invalid wallet provider for chain key: ${params.srcChainKey}. Expected bitcoin wallet provider.`,
32005
+ { ...baseCtx, field: "walletProvider" }
32006
+ );
32007
+ if (this.spoke.bitcoin.walletMode === "TRADING") {
32008
+ await this.spoke.bitcoin.radfi.ensureRadfiAccessToken(_params.walletProvider);
32009
+ }
31147
32010
  }
32011
+ walletAddress = await this.spoke.bitcoin.getEffectiveWalletAddress(personalAddress);
31148
32012
  }
31149
32013
  const hubWallet = await this.hubProvider.getUserHubWalletAddress(walletAddress, params.srcChainKey);
31150
32014
  const effectiveSkipSimulation = skipSimulation || isBitcoinChainKeyType(params.srcChainKey) && this.spoke.bitcoin.walletMode === "USER";
31151
- const data = this.buildBridgeData(params, srcToken, dstToken, this.config.bridgePartnerFee);
32015
+ const data = this.buildBridgeData(params, srcToken, dstToken, partnerFee);
31152
32016
  const coreParams = {
31153
32017
  srcChainKey: params.srcChainKey,
31154
32018
  srcAddress: walletAddress,
32019
+ srcPublicKey: extras?.srcPublicKey,
32020
+ // Bitcoin Bound token; BitcoinSpokeService.deposit falls back to the RadfiProvider instance token when undefined.
32021
+ accessToken: extras?.bound?.accessToken,
31155
32022
  to: hubWallet,
31156
32023
  token: params.srcToken,
31157
32024
  amount: params.amount,
@@ -31206,6 +32073,26 @@ var BridgeService = class {
31206
32073
  if (spokeToken) return spokeToken;
31207
32074
  return isHubChainKeyType(chainKey) ? this.config.getXTokenFromHubAsset(token) : void 0;
31208
32075
  }
32076
+ /**
32077
+ * Post-fee amounts for a bridge, in the units each hub step operates in. Single source for the fee +
32078
+ * vault-decimal pipeline, so {@link buildBridgeData}'s encoded hub calls and the BTC-destination dust
32079
+ * guard in {@link createBridgeIntent} can never disagree about what actually gets delivered.
32080
+ *
32081
+ * A spoke endpoint's amount is translated INTO 18-dp vault units on the way in (skipped when the
32082
+ * endpoint already IS the vault asset), the partner fee is deducted there — so a fixed
32083
+ * `PartnerFee.amount` is wei-denominated, never spoke-denominated — and the remainder is translated
32084
+ * back OUT into the destination endpoint's own units.
32085
+ *
32086
+ * @returns `feeAmount` and `withdrawAmount` in 18-dp vault units (what the hub fee transfer and vault
32087
+ * withdrawal use), and `delivered` in the destination endpoint's units (what the recipient receives).
32088
+ */
32089
+ computeBridgeAmounts(amount, srcToken, dstToken, partnerFee) {
32090
+ const translatedAmount = this.config.isSodaVaultHubAsset(srcToken.hubAsset) ? amount : EvmVaultTokenService.translateIncomingDecimals(srcToken.decimals, amount);
32091
+ const feeAmount = calculateFeeAmount(translatedAmount, partnerFee);
32092
+ const withdrawAmount = translatedAmount - feeAmount;
32093
+ const delivered = this.config.isSodaVaultHubAsset(dstToken.hubAsset) ? withdrawAmount : EvmVaultTokenService.translateOutgoingDecimals(dstToken.decimals, withdrawAmount);
32094
+ return { feeAmount, withdrawAmount, delivered };
32095
+ }
31209
32096
  /**
31210
32097
  * Encodes the hub-side execution payload for a bridge operation.
31211
32098
  *
@@ -31229,23 +32116,23 @@ var BridgeService = class {
31229
32116
  */
31230
32117
  buildBridgeData(params, srcToken, dstToken, partnerFee) {
31231
32118
  const calls = [];
31232
- let translatedAmount = params.amount;
31233
- let srcVault = params.srcToken;
32119
+ const { feeAmount, withdrawAmount, delivered } = this.computeBridgeAmounts(
32120
+ params.amount,
32121
+ srcToken,
32122
+ dstToken,
32123
+ partnerFee
32124
+ );
32125
+ let srcVault = srcToken.hubAsset;
31234
32126
  if (!this.config.isSodaVaultHubAsset(srcToken.hubAsset)) {
31235
32127
  calls.push(Erc20Service.encodeApprove(srcToken.hubAsset, srcToken.vault, params.amount));
31236
32128
  calls.push(EvmVaultTokenService.encodeDeposit(srcToken.vault, srcToken.hubAsset, params.amount));
31237
- translatedAmount = EvmVaultTokenService.translateIncomingDecimals(srcToken.decimals, params.amount);
31238
32129
  srcVault = srcToken.vault;
31239
32130
  }
31240
- const feeAmount = calculateFeeAmount(translatedAmount, partnerFee);
31241
32131
  if (partnerFee && feeAmount > 0n) {
31242
32132
  calls.push(Erc20Service.encodeTransfer(srcVault, partnerFee.address, feeAmount));
31243
32133
  }
31244
- const withdrawAmount = translatedAmount - feeAmount;
31245
- let translatedWithdrawAmount = withdrawAmount;
31246
32134
  if (!this.config.isSodaVaultHubAsset(dstToken.hubAsset)) {
31247
32135
  calls.push(EvmVaultTokenService.encodeWithdraw(dstToken.vault, dstToken.hubAsset, withdrawAmount));
31248
- translatedWithdrawAmount = EvmVaultTokenService.translateOutgoingDecimals(dstToken.decimals, withdrawAmount);
31249
32136
  }
31250
32137
  const encodedRecipientAddress = encodeAddress(params.dstChainKey, params.recipient);
31251
32138
  if (isHubChainKey(params.dstChainKey)) {
@@ -31256,11 +32143,11 @@ var BridgeService = class {
31256
32143
  data: viem.encodeFunctionData({
31257
32144
  abi: wrappedSonicAbi,
31258
32145
  functionName: "withdrawTo",
31259
- args: [encodedRecipientAddress, translatedWithdrawAmount]
32146
+ args: [encodedRecipientAddress, delivered]
31260
32147
  })
31261
32148
  });
31262
32149
  } else {
31263
- calls.push(Erc20Service.encodeTransfer(dstToken.hubAsset, encodedRecipientAddress, translatedWithdrawAmount));
32150
+ calls.push(Erc20Service.encodeTransfer(dstToken.hubAsset, encodedRecipientAddress, delivered));
31264
32151
  }
31265
32152
  } else {
31266
32153
  bridgeInvariant(dstToken, `Unsupported hub chain (${params.dstChainKey}) token: ${params.dstToken}`, {
@@ -31271,7 +32158,7 @@ var BridgeService = class {
31271
32158
  EvmAssetManagerService.encodeTransfer(
31272
32159
  dstToken.hubAsset,
31273
32160
  encodedRecipientAddress,
31274
- translatedWithdrawAmount,
32161
+ delivered,
31275
32162
  this.hubProvider.chainConfig.addresses.assetManager
31276
32163
  )
31277
32164
  );
@@ -39490,7 +40377,7 @@ var LeverageYieldService = class {
39490
40377
  }
39491
40378
  /** Looks up a vault by its `name` field. Returns `undefined` when not registered. */
39492
40379
  getVault(name) {
39493
- return this.listVaults().find((v6) => v6.name === name);
40380
+ return this.listVaults().find((v9) => v9.name === name);
39494
40381
  }
39495
40382
  /**
39496
40383
  * Looks up a registered vault by its on-chain proxy address (case-insensitive).
@@ -39498,7 +40385,7 @@ var LeverageYieldService = class {
39498
40385
  */
39499
40386
  getVaultByAddress(address) {
39500
40387
  const normalized = address.toLowerCase();
39501
- return this.listVaults().find((v6) => v6.vault.toLowerCase() === normalized);
40388
+ return this.listVaults().find((v9) => v9.vault.toLowerCase() === normalized);
39502
40389
  }
39503
40390
  /**
39504
40391
  * Resolves the intent `deadline`: returns the caller-supplied value verbatim, otherwise
@@ -39999,15 +40886,22 @@ var LeverageYieldService = class {
39999
40886
  spender: params.vault
40000
40887
  };
40001
40888
  if (params.raw) {
40002
- const tx2 = await Erc20Service.approve({ ...baseApprove, raw: true });
40003
- return { ok: true, value: tx2 };
40004
- }
40005
- const tx = await Erc20Service.approve({
40006
- ...baseApprove,
40889
+ const tx = await Erc20Service.approve({ ...baseApprove, raw: true });
40890
+ return { ok: true, value: tx };
40891
+ }
40892
+ const result = await this.spoke.approve({
40893
+ srcChainKey: this.hubProvider.chainConfig.chain.key,
40894
+ token: baseApprove.token,
40895
+ amount: baseApprove.amount,
40896
+ owner: from,
40897
+ spender: baseApprove.spender,
40007
40898
  raw: false,
40008
40899
  walletProvider: params.walletProvider
40009
40900
  });
40010
- return { ok: true, value: tx };
40901
+ if (!result.ok) {
40902
+ return { ok: false, error: approveFailed("leverageYield", result.error, baseCtx) };
40903
+ }
40904
+ return { ok: true, value: result.value };
40011
40905
  } catch (error) {
40012
40906
  if (isLeverageYieldApproveError(error)) return { ok: false, error };
40013
40907
  return { ok: false, error: approveFailed("leverageYield", error, baseCtx) };
@@ -40305,12 +41199,12 @@ function toDomainCode(value) {
40305
41199
  }
40306
41200
  function readErrorBody(body) {
40307
41201
  if (typeof body !== "object" || body === null) return {};
40308
- const record = body;
40309
- const retryAfterSeconds = typeof record.retryAfterSeconds === "number" && Number.isFinite(record.retryAfterSeconds) && record.retryAfterSeconds > 0 ? record.retryAfterSeconds : void 0;
40310
- const sponsorSequence = typeof record.sponsorSequence === "string" && /^\d+$/.test(record.sponsorSequence) ? record.sponsorSequence : void 0;
41202
+ const record3 = body;
41203
+ const retryAfterSeconds = typeof record3.retryAfterSeconds === "number" && Number.isFinite(record3.retryAfterSeconds) && record3.retryAfterSeconds > 0 ? record3.retryAfterSeconds : void 0;
41204
+ const sponsorSequence = typeof record3.sponsorSequence === "string" && /^\d+$/.test(record3.sponsorSequence) ? record3.sponsorSequence : void 0;
40311
41205
  return {
40312
- message: typeof record.message === "string" ? record.message : void 0,
40313
- code: toDomainCode(record.error),
41206
+ message: typeof record3.message === "string" ? record3.message : void 0,
41207
+ code: toDomainCode(record3.error),
40314
41208
  retryAfterSeconds,
40315
41209
  sponsorSequence
40316
41210
  };
@@ -40876,7 +41770,9 @@ var Sodax = class {
40876
41770
  const logger = resolveLogger(options?.logger);
40877
41771
  const analytics = resolveAnalytics(options?.analytics);
40878
41772
  const fee = options?.fee;
41773
+ const radfiSigner = options?.radfi?.signRequest;
40879
41774
  const useBackendSubmitTx = options?.swapsOptions?.useBackendSubmitTx ?? false;
41775
+ const bridgeUseBackendSubmitTx = options?.bridgeOptions?.useBackendSubmitTx ?? false;
40880
41776
  this.instanceConfig = options ? mergeSodaxConfig(sodaxConfig, options) : sodaxConfig;
40881
41777
  this.backendApi = new BackendApiService(this.instanceConfig.api, logger);
40882
41778
  this.api = this.backendApi;
@@ -40886,7 +41782,8 @@ var Sodax = class {
40886
41782
  userConfig: options,
40887
41783
  logger,
40888
41784
  analytics,
40889
- fee
41785
+ fee,
41786
+ radfiSigner
40890
41787
  });
40891
41788
  this.hubProvider = new EvmHubProvider({ config: this.config });
40892
41789
  this.spoke = new SpokeService({ config: this.config, hubProvider: this.hubProvider });
@@ -40912,7 +41809,13 @@ var Sodax = class {
40912
41809
  config: this.config,
40913
41810
  spoke: this.spoke
40914
41811
  });
40915
- this.bridge = new BridgeService({ hubProvider: this.hubProvider, config: this.config, spoke: this.spoke });
41812
+ this.bridge = new BridgeService({
41813
+ hubProvider: this.hubProvider,
41814
+ config: this.config,
41815
+ spoke: this.spoke,
41816
+ backendApi: this.backendApi,
41817
+ useBackendSubmitTx: bridgeUseBackendSubmitTx
41818
+ });
40916
41819
  this.staking = new StakingService({ hubProvider: this.hubProvider, config: this.config, spoke: this.spoke });
40917
41820
  this.partners = new PartnerService({
40918
41821
  hubProvider: this.hubProvider,
@@ -40984,6 +41887,7 @@ exports.APPROVE_CODES = APPROVE_CODES;
40984
41887
  exports.AssetService = AssetService;
40985
41888
  exports.BITCOIN_CHAIN_KEYS = BITCOIN_CHAIN_KEYS;
40986
41889
  exports.BITCOIN_CHAIN_KEYS_SET = BITCOIN_CHAIN_KEYS_SET;
41890
+ exports.BITCOIN_DUST_SATS = BITCOIN_DUST_SATS;
40987
41891
  exports.BTC_WALLET_ADDRESS_TYPES = BTC_WALLET_ADDRESS_TYPES;
40988
41892
  exports.BackendApiService = BackendApiService;
40989
41893
  exports.BackendHttpError = BackendHttpError;
@@ -40992,6 +41896,7 @@ exports.BigIntToHex = BigIntToHex;
40992
41896
  exports.BigNumberZeroDecimal = BigNumberZeroDecimal;
40993
41897
  exports.BitcoinSpokeService = BitcoinSpokeService;
40994
41898
  exports.BnUSDMigrationService = BnUSDMigrationService;
41899
+ exports.BridgeApiService = BridgeApiService;
40995
41900
  exports.BridgeService = BridgeService;
40996
41901
  exports.CHAIN_KEYS = CHAIN_KEYS;
40997
41902
  exports.CHAIN_LOGO_BASE_URL = CHAIN_LOGO_BASE_URL;
@@ -41075,6 +41980,7 @@ exports.ProtocolIntentsAbi = ProtocolIntentsAbi;
41075
41980
  exports.RAY = RAY;
41076
41981
  exports.RAY_DECIMALS = RAY_DECIMALS;
41077
41982
  exports.RELAY_ERROR_CODES = RELAY_ERROR_CODES;
41983
+ exports.RELAY_FALLBACK_FLOOR_MS = RELAY_FALLBACK_FLOOR_MS;
41078
41984
  exports.RadfiApiError = RadfiApiError;
41079
41985
  exports.RadfiProvider = RadfiProvider;
41080
41986
  exports.RecoveryService = RecoveryService;
@@ -41279,6 +42185,8 @@ exports.isMoneyMarketCreateIntentError = isMoneyMarketCreateIntentError;
41279
42185
  exports.isMoneyMarketError = isMoneyMarketError;
41280
42186
  exports.isMoneyMarketGasEstimationError = isMoneyMarketGasEstimationError;
41281
42187
  exports.isMoneyMarketOrchestrationError = isMoneyMarketOrchestrationError;
42188
+ exports.isNativeBitcoinToken = isNativeBitcoinToken;
42189
+ exports.isNativeBitcoinTransfer = isNativeBitcoinTransfer;
41282
42190
  exports.isNativeToken = isNativeToken;
41283
42191
  exports.isNearChainKey = isNearChainKey;
41284
42192
  exports.isNearChainKeyType = isNearChainKeyType;
@@ -41414,6 +42322,7 @@ exports.swapExactInSingleParamsAbi = swapExactInSingleParamsAbi;
41414
42322
  exports.swapInvariant = swapInvariant;
41415
42323
  exports.swapSupportedTokens = swapSupportedTokens;
41416
42324
  exports.swapsConfig = swapsConfig;
42325
+ exports.toCreateBridgeIntentParamsV2 = toCreateBridgeIntentParamsV2;
41417
42326
  exports.tokenLogo = tokenLogo;
41418
42327
  exports.tokenLogoSlug = tokenLogoSlug;
41419
42328
  exports.uiPoolDataAbi = uiPoolDataAbi;