@sodax/sdk 2.0.0-rc.3 → 2.0.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +8 -60
  2. package/dist/index.cjs +62 -74
  3. package/dist/index.d.cts +22 -110
  4. package/dist/index.d.ts +22 -110
  5. package/dist/index.mjs +39 -49
  6. package/package.json +23 -24
  7. package/ai-exported/AGENTS.md +0 -99
  8. package/ai-exported/integration/README.md +0 -41
  9. package/ai-exported/integration/ai-rules.md +0 -75
  10. package/ai-exported/integration/architecture.md +0 -533
  11. package/ai-exported/integration/chain-specifics.md +0 -189
  12. package/ai-exported/integration/features/README.md +0 -19
  13. package/ai-exported/integration/features/auxiliary-services.md +0 -189
  14. package/ai-exported/integration/features/bridge.md +0 -136
  15. package/ai-exported/integration/features/dex.md +0 -182
  16. package/ai-exported/integration/features/icx-bnusd-baln.md +0 -181
  17. package/ai-exported/integration/features/money-market.md +0 -198
  18. package/ai-exported/integration/features/staking.md +0 -166
  19. package/ai-exported/integration/features/swap.md +0 -207
  20. package/ai-exported/integration/quickstart.md +0 -213
  21. package/ai-exported/integration/recipes/README.md +0 -21
  22. package/ai-exported/integration/recipes/backend-server-init.md +0 -69
  23. package/ai-exported/integration/recipes/chain-key-narrowing.md +0 -65
  24. package/ai-exported/integration/recipes/gas-estimation.md +0 -33
  25. package/ai-exported/integration/recipes/initialize-sodax.md +0 -78
  26. package/ai-exported/integration/recipes/raw-tx-flow.md +0 -71
  27. package/ai-exported/integration/recipes/result-and-errors.md +0 -104
  28. package/ai-exported/integration/recipes/signed-tx-flow.md +0 -46
  29. package/ai-exported/integration/recipes/testing.md +0 -101
  30. package/ai-exported/integration/reference/README.md +0 -18
  31. package/ai-exported/integration/reference/chain-keys.md +0 -67
  32. package/ai-exported/integration/reference/error-codes.md +0 -165
  33. package/ai-exported/integration/reference/glossary.md +0 -32
  34. package/ai-exported/integration/reference/public-api.md +0 -138
  35. package/ai-exported/integration/reference/wallet-providers.md +0 -62
  36. package/ai-exported/migration/README.md +0 -58
  37. package/ai-exported/migration/ai-rules.md +0 -80
  38. package/ai-exported/migration/breaking-changes/architecture.md +0 -344
  39. package/ai-exported/migration/breaking-changes/result-and-errors.md +0 -363
  40. package/ai-exported/migration/breaking-changes/type-system.md +0 -341
  41. package/ai-exported/migration/checklist.md +0 -67
  42. package/ai-exported/migration/features/README.md +0 -35
  43. package/ai-exported/migration/features/auxiliary-services.md +0 -156
  44. package/ai-exported/migration/features/bridge.md +0 -128
  45. package/ai-exported/migration/features/dex.md +0 -143
  46. package/ai-exported/migration/features/icx-bnusd-baln.md +0 -151
  47. package/ai-exported/migration/features/money-market.md +0 -214
  48. package/ai-exported/migration/features/staking.md +0 -138
  49. package/ai-exported/migration/features/swap.md +0 -198
  50. package/ai-exported/migration/recipes.md +0 -350
  51. package/ai-exported/migration/reference/README.md +0 -18
  52. package/ai-exported/migration/reference/deleted-exports.md +0 -127
  53. package/ai-exported/migration/reference/error-code-crosswalk.md +0 -104
  54. package/ai-exported/migration/reference/return-shapes.md +0 -49
  55. package/ai-exported/migration/reference/sodax-config.md +0 -145
  56. package/dist/index.cjs.map +0 -1
  57. package/dist/index.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,18 +1,17 @@
1
- import { getAbiItem, defineChain, isAddress, toHex, hexToBytes, encodeAbiParameters, parseAbiParameters, encodeFunctionData, erc20Abi as erc20Abi$1, createPublicClient, http, bytesToHex, keccak256, fromHex, encodePacked, parseEventLogs, decodeAbiParameters, maxUint160, maxUint48 } from 'viem';
1
+ import { getAbiItem, isAddress, toHex, hexToBytes, encodeAbiParameters, parseAbiParameters, defineChain, encodeFunctionData, erc20Abi as erc20Abi$1, createPublicClient, http, bytesToHex, keccak256, fromHex, encodePacked, parseEventLogs, decodeAbiParameters, maxUint160, maxUint48 } from 'viem';
2
2
  import { bcs } from '@mysten/sui/bcs';
3
3
  import { PublicKey, Connection, VersionedTransaction, SystemProgram, ComputeBudgetProgram, TransactionMessage, TransactionInstruction } from '@solana/web3.js';
4
4
  import { rpc, Address, xdr, Account, Horizon, Contract, TransactionBuilder, nativeToScVal, TimeoutInfinite, scValToBigInt, Operation, Asset, FeeBumpTransaction } from '@stellar/stellar-sdk';
5
- import { serializeCV, Cl, deserializeCV, cvToString, fetchFeeEstimateTransaction, fetchCallReadOnlyFunction, parseContractId, PostConditionMode, noneCV, someCV, uintCV, validateStacksAddress, makeUnsignedContractCall, serializePayloadBytes } from '@stacks/transactions';
5
+ import { serializeCV, Cl, deserializeCV, cvToString, createNetwork, fetchFeeEstimateTransaction, fetchCallReadOnlyFunction, parseContractId, PostConditionMode, noneCV, someCV, uintCV, validateStacksAddress, makeUnsignedContractCall, serializePayloadBytes } from '@sodax/libs/stacks/core';
6
6
  import { kaia, redbellyMainnet, mainnet, lightlinkPhoenix, polygon, bsc, optimism, base, arbitrum, avalanche, sonic } from 'viem/chains';
7
7
  import * as rlp from 'rlp';
8
- import { createNetwork } from '@stacks/network';
9
- import * as bitcoin from 'bitcoinjs-lib';
8
+ import { initEccLib, networks, Transaction, Psbt, payments, opcodes, script } from 'bitcoinjs-lib';
10
9
  import * as ecc from '@bitcoinerlab/secp256k1';
11
10
  import { CLPositionManagerAbi, encodeCLPositionManagerMintCalldata, encodeCLPositionManagerIncreaseLiquidityCalldata, encodeCLPositionManagerDecreaseLiquidityCalldata, getPoolId, CLPoolManagerAbi, decodePoolKey } from '@pancakeswap/infinity-sdk';
12
- import { Transaction } from '@mysten/sui/transactions';
11
+ import { Transaction as Transaction$1 } from '@mysten/sui/transactions';
13
12
  import { SuiClient } from '@mysten/sui/client';
14
13
  import { TOKEN_PROGRAM_ID, getAssociatedTokenAddress } from '@solana/spl-token';
15
- import * as anchor from '@coral-xyz/anchor';
14
+ import { AnchorProvider, Program } from '@coral-xyz/anchor';
16
15
  import BN from 'bn.js';
17
16
  import * as IconSdkRaw from 'icon-sdk-js';
18
17
  import { ChainGrpcWasmApi, TxGrpcApi, CosmosTxV1Beta1TxPb, toBase64, fromBase64, MsgExecuteContract, createTransactionForAddressAndMsg } from '@injectivelabs/sdk-ts';
@@ -488,7 +487,7 @@ var SodaTokens = {
488
487
  sodaNEAR: {
489
488
  symbol: "sodaNEAR",
490
489
  name: "SODA NEAR",
491
- decimals: 24,
490
+ decimals: 18,
492
491
  address: "0xf4ba497c9b805e4bd88a8a9e6a7b8f74984c3e39",
493
492
  chainKey: ChainKeys.SONIC_MAINNET,
494
493
  hubAsset: "0xf4ba497c9b805e4bd88a8a9e6a7b8f74984c3e39",
@@ -3203,7 +3202,8 @@ var moneyMarketSupportedTokens = {
3203
3202
  spokeChainConfig[ChainKeys.HYPEREVM_MAINNET].supportedTokens.HYPE,
3204
3203
  spokeChainConfig[ChainKeys.HYPEREVM_MAINNET].supportedTokens.bnUSD,
3205
3204
  spokeChainConfig[ChainKeys.HYPEREVM_MAINNET].supportedTokens.SODA,
3206
- spokeChainConfig[ChainKeys.HYPEREVM_MAINNET].supportedTokens.USDT0
3205
+ spokeChainConfig[ChainKeys.HYPEREVM_MAINNET].supportedTokens.USDT0,
3206
+ spokeChainConfig[ChainKeys.HYPEREVM_MAINNET].supportedTokens.USDC
3207
3207
  ],
3208
3208
  [ChainKeys.LIGHTLINK_MAINNET]: [
3209
3209
  spokeChainConfig[ChainKeys.LIGHTLINK_MAINNET].supportedTokens.ETH,
@@ -3487,7 +3487,6 @@ var swapSupportedTokens = {
3487
3487
  spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.USDT,
3488
3488
  spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.wS,
3489
3489
  spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.SODA,
3490
- spokeChainConfig[ChainKeys.SONIC_MAINNET].supportedTokens.bnUSD,
3491
3490
  ...Object.values(SodaTokens)
3492
3491
  ],
3493
3492
  [ChainKeys.AVALANCHE_MAINNET]: [
@@ -3869,7 +3868,7 @@ function isValidWalletProviderForChainKey(chainKey, walletProvider) {
3869
3868
  }
3870
3869
 
3871
3870
  // ../types/dist/index.js
3872
- var CONFIG_VERSION = 201;
3871
+ var CONFIG_VERSION = 203;
3873
3872
  function isEvmSpokeChainConfig(value) {
3874
3873
  return typeof value === "object" && value !== null && value.chain.type === "EVM" && value.chain.key !== HUB_CHAIN_KEY;
3875
3874
  }
@@ -14212,7 +14211,7 @@ var StacksSpokeService = class {
14212
14211
  nonce: 0n
14213
14212
  });
14214
14213
  return {
14215
- payload: `0x${bytesToHex(serializePayloadBytes(tx.payload))}`
14214
+ payload: bytesToHex(serializePayloadBytes(tx.payload))
14216
14215
  };
14217
14216
  }
14218
14217
  const txId = await params.walletProvider.sendTransaction(reqData);
@@ -14255,7 +14254,7 @@ var StacksSpokeService = class {
14255
14254
  nonce: 0n
14256
14255
  });
14257
14256
  return {
14258
- payload: `0x${bytesToHex(serializePayloadBytes(tx.payload))}`
14257
+ payload: bytesToHex(serializePayloadBytes(tx.payload))
14259
14258
  };
14260
14259
  }
14261
14260
  const txId = await params.walletProvider.sendTransaction(reqData);
@@ -14338,7 +14337,7 @@ var RadfiProvider = class {
14338
14337
  if (!publicKey) {
14339
14338
  throw new Error("Failed to retrieve public key from wallet. Please unlock your wallet and try again.");
14340
14339
  }
14341
- const message = `Login to Radfi via Sodax: ${Date.now()}`;
14340
+ const message = `${Date.now()}`;
14342
14341
  const addressType = detectBitcoinAddressType(address);
14343
14342
  const signature = addressType === "P2WPKH" || addressType === "P2TR" ? await walletProvider.signBip322Message(message) : await walletProvider.signEcdsaMessage(message);
14344
14343
  const result = await this.authenticate({ message, signature, address, publicKey });
@@ -14670,7 +14669,7 @@ function normalizePsbtToBase64(signedPsbt) {
14670
14669
  }
14671
14670
 
14672
14671
  // src/shared/services/spoke/BitcoinSpokeService.ts
14673
- bitcoin.initEccLib(ecc);
14672
+ initEccLib(ecc);
14674
14673
  var BITCOIN_DEFAULT_FEE_RATE = 3;
14675
14674
  var DUST_THRESHOLD = 546;
14676
14675
  var BitcoinSpokeService = class {
@@ -14690,7 +14689,7 @@ var BitcoinSpokeService = class {
14690
14689
  this.maxTimeoutMs = chainConfig.pollingConfig.maxTimeoutMs;
14691
14690
  }
14692
14691
  getBtcNetwork(chainId) {
14693
- return this.config.getChainConfig(chainId).network === "MAINNET" ? bitcoin.networks.bitcoin : bitcoin.networks.testnet;
14692
+ return this.config.getChainConfig(chainId).network === "MAINNET" ? networks.bitcoin : networks.testnet;
14694
14693
  }
14695
14694
  async getBalance(tokenAddress, walletAddress) {
14696
14695
  if (!tokenAddress || tokenAddress === "0x" || tokenAddress === "BTC") {
@@ -14702,7 +14701,7 @@ var BitcoinSpokeService = class {
14702
14701
  }
14703
14702
  async fetchScriptPubKey(utxo) {
14704
14703
  const txHex = await this.fetchRawTransaction(utxo.txid);
14705
- const tx = bitcoin.Transaction.fromHex(txHex);
14704
+ const tx = Transaction.fromHex(txHex);
14706
14705
  const out = tx.outs[utxo.vout];
14707
14706
  if (!out) {
14708
14707
  throw new Error(`UTXO not found: ${utxo.txid}:${utxo.vout}`);
@@ -14804,7 +14803,7 @@ var BitcoinSpokeService = class {
14804
14803
  * Build a priority Bitcoin transaction with proper fee calculation
14805
14804
  */
14806
14805
  async buildBitcoinTransaction(utxos, outputs, changeAddress, chainId, walletProvider, feeRate) {
14807
- const psbt = new bitcoin.Psbt({ network: this.getBtcNetwork(chainId) });
14806
+ const psbt = new Psbt({ network: this.getBtcNetwork(chainId) });
14808
14807
  const effectiveFeeRate = feeRate ?? await this.getFeeRateEstimate();
14809
14808
  const walletAddress = await walletProvider.getWalletAddress();
14810
14809
  const addressType = detectBitcoinAddressType(walletAddress);
@@ -14835,7 +14834,7 @@ var BitcoinSpokeService = class {
14835
14834
  throw new Error("Missing public key for P2SH-P2WPKH input");
14836
14835
  }
14837
14836
  const pubKeyHex = await walletProvider.getPublicKey();
14838
- const redeemScript = bitcoin.payments.p2wpkh({
14837
+ const redeemScript = payments.p2wpkh({
14839
14838
  pubkey: Buffer.from(pubKeyHex, "hex"),
14840
14839
  network: this.getBtcNetwork(chainId)
14841
14840
  }).output;
@@ -14992,14 +14991,14 @@ var BitcoinSpokeService = class {
14992
14991
  const psbt = await this.buildBitcoinTransaction(utxos, outputs, walletAddress, srcChainKey, walletProvider);
14993
14992
  const OP_RADFI_SODAX_DATA = 49;
14994
14993
  const payload = Buffer.concat([Buffer.from([OP_RADFI_SODAX_DATA]), Buffer.from(data.slice(2), "hex")]);
14995
- const OP_RETURN = bitcoin.opcodes.OP_RETURN;
14996
- const OP_12 = bitcoin.opcodes.OP_12;
14994
+ const OP_RETURN = opcodes.OP_RETURN;
14995
+ const OP_12 = opcodes.OP_12;
14997
14996
  if (OP_RETURN === void 0 || OP_12 === void 0) {
14998
14997
  throw new Error("bitcoinjs-lib opcodes OP_RETURN or OP_12 are undefined");
14999
14998
  }
15000
- const script2 = bitcoin.script.compile([OP_RETURN, OP_12, payload]);
14999
+ const compiledScript = script.compile([OP_RETURN, OP_12, payload]);
15001
15000
  psbt.addOutput({
15002
- script: script2,
15001
+ script: compiledScript,
15003
15002
  value: 0
15004
15003
  });
15005
15004
  return psbt;
@@ -21601,7 +21600,7 @@ var SonicSpokeService = class {
21601
21600
  }
21602
21601
  /**
21603
21602
  * Deposit tokens to the spoke chain using the Sonic wallet abstraction.
21604
- * @param {SonicSpokeDepositParams<Raw>} params - The parameters for the deposit
21603
+ * @param {DepositParams<SonicChainKey, Raw>} params - The parameters for the deposit
21605
21604
  * @returns {Promise<TxReturnType<SonicChainKey, Raw>>} A promise that resolves to the transaction hash
21606
21605
  */
21607
21606
  async deposit(params) {
@@ -21830,9 +21829,6 @@ var SuiSpokeService = class {
21830
21829
  }
21831
21830
  return coin;
21832
21831
  }
21833
- static getAddressBCSBytes(suiaddress) {
21834
- return toHex(bcs.Address.serialize(suiaddress).toBytes());
21835
- }
21836
21832
  encodeSimulationParams(token, assetManager) {
21837
21833
  const encoder2 = new TextEncoder();
21838
21834
  return {
@@ -21870,7 +21866,7 @@ var SuiSpokeService = class {
21870
21866
  async deposit(params) {
21871
21867
  const { srcAddress: from, srcChainKey, token, to, amount, data = "0x" } = params;
21872
21868
  const isNative = isNativeToken(srcChainKey, token);
21873
- const tx = new Transaction();
21869
+ const tx = new Transaction$1();
21874
21870
  const coin = isNative ? await this.getNativeCoin(tx, amount) : await this.getCoin(tx, token, amount, from);
21875
21871
  const connection = this.splitAddress(this.config.getChainConfig(srcChainKey).addresses.connection);
21876
21872
  const assetManager = this.splitAddress(await this.getAssetManagerAddress(srcChainKey));
@@ -21904,7 +21900,7 @@ var SuiSpokeService = class {
21904
21900
  }
21905
21901
  async sendMessage(params) {
21906
21902
  const { srcAddress: from, srcChainKey, dstChainKey, dstAddress, payload } = params;
21907
- const txb = new Transaction();
21903
+ const txb = new Transaction$1();
21908
21904
  const connection = this.splitAddress(this.config.getChainConfig(srcChainKey).addresses.connection);
21909
21905
  const relayId = getIntentRelayChainId(dstChainKey);
21910
21906
  txb.moveCall({
@@ -21938,7 +21934,7 @@ var SuiSpokeService = class {
21938
21934
  * @returns {Promise<bigint>} The estimated computation cost.
21939
21935
  */
21940
21936
  async estimateGas({ tx }) {
21941
- const txb = Transaction.fromKind(tx.data);
21937
+ const txb = Transaction$1.fromKind(tx.data);
21942
21938
  const result = await this.publicClient.devInspectTransactionBlock({
21943
21939
  sender: tx.from,
21944
21940
  transactionBlock: txb
@@ -21947,13 +21943,12 @@ var SuiSpokeService = class {
21947
21943
  }
21948
21944
  /**
21949
21945
  * Get the balance of the token in the spoke chain.
21950
- * @param {Address} token - The address of the token to get the balance of.
21951
- * @param {SuiSpokeProvider} spokeProvider - The spoke provider.
21946
+ * @param {GetDepositParams<SuiChainKey>} params - The src chain key, src address, and token address.
21952
21947
  * @returns {Promise<bigint>} The balance of the token.
21953
21948
  */
21954
21949
  async getDeposit(params) {
21955
21950
  const assetmanager = this.splitAddress(await this.getAssetManagerAddress(params.srcChainKey));
21956
- const tx = new Transaction();
21951
+ const tx = new Transaction$1();
21957
21952
  const result = await this.viewContract(
21958
21953
  tx,
21959
21954
  assetmanager.packageId,
@@ -21972,7 +21967,7 @@ var SuiSpokeService = class {
21972
21967
  }
21973
21968
  /**
21974
21969
  * Fetch the asset manager config from the spoke chain.
21975
- * @param {SuiBaseSpokeProvider} suiSpokeProvider - The spoke provider.
21970
+ * @param {SuiChainKey} chainId - The Sui chain key.
21976
21971
  * @returns {Promise<string>} The asset manager config.
21977
21972
  */
21978
21973
  async fetchAssetManagerAddress(chainId) {
@@ -21981,7 +21976,7 @@ var SuiSpokeService = class {
21981
21976
  }
21982
21977
  /**
21983
21978
  * Fetch the latest asset manager package id from the spoke chain.
21984
- * @param {SuiBaseSpokeProvider} suiSpokeProvider - The spoke provider.
21979
+ * @param {SuiChainKey} chainId - The Sui chain key.
21985
21980
  * @returns {Promise<string>} The latest asset manager package id.
21986
21981
  */
21987
21982
  async fetchLatestAssetManagerPackageId(chainId) {
@@ -22595,11 +22590,11 @@ async function getProvider(base58PublicKey, rpcUrl) {
22595
22590
  signAllTransactions: () => Promise.reject()
22596
22591
  };
22597
22592
  const connection = new Connection(rpcUrl);
22598
- return new anchor.AnchorProvider(connection, wallet, { commitment: "confirmed" });
22593
+ return new AnchorProvider(connection, wallet, { commitment: "confirmed" });
22599
22594
  }
22600
22595
  async function getAssetManagerIdl(assetManager, provider) {
22601
22596
  try {
22602
- const idl = await anchor.Program.fetchIdl(new PublicKey(assetManager), provider);
22597
+ const idl = await Program.fetchIdl(new PublicKey(assetManager), provider);
22603
22598
  if (!idl) {
22604
22599
  throw new Error("asset manager idl not available");
22605
22600
  }
@@ -22611,7 +22606,7 @@ async function getAssetManagerIdl(assetManager, provider) {
22611
22606
  }
22612
22607
  async function getConnectionIdl(connection, provider) {
22613
22608
  try {
22614
- const idl = await anchor.Program.fetchIdl(new PublicKey(connection), provider);
22609
+ const idl = await Program.fetchIdl(new PublicKey(connection), provider);
22615
22610
  if (!idl) {
22616
22611
  throw new Error("asset manager idl not available");
22617
22612
  }
@@ -22624,12 +22619,12 @@ async function getConnectionIdl(connection, provider) {
22624
22619
  async function getAssetManagerProgram(base58PublicKey, rpcUrl, assetManager) {
22625
22620
  const provider = await getProvider(base58PublicKey, rpcUrl);
22626
22621
  const idl = await getAssetManagerIdl(assetManager, provider);
22627
- return new anchor.Program(idl, provider);
22622
+ return new Program(idl, provider);
22628
22623
  }
22629
22624
  async function getConnectionProgram(base58PublicKey, rpcUrl, connection) {
22630
22625
  const provider = await getProvider(base58PublicKey, rpcUrl);
22631
22626
  const idl = await getConnectionIdl(connection, provider);
22632
- return new anchor.Program(idl, provider);
22627
+ return new Program(idl, provider);
22633
22628
  }
22634
22629
  function getSolanaAddressBytes(address) {
22635
22630
  return `0x${Buffer.from(address.toBytes()).toString("hex")}`;
@@ -22941,7 +22936,7 @@ var IconSpokeService = class {
22941
22936
  }
22942
22937
  /**
22943
22938
  * Deposit tokens to the spoke chain.
22944
- * @param {IconSpokeDepositParams} params - The parameters for the deposit
22939
+ * @param {DepositParams<IconChainKey, R>} params - The parameters for the deposit
22945
22940
  * @param {IconSpokeProviderType} spokeProvider - The provider for the spoke chain
22946
22941
  * @param {EvmHubProvider} hubProvider - The provider for the hub chain
22947
22942
  * @param {boolean} raw - The return type raw or just transaction hash
@@ -28021,7 +28016,7 @@ var MigrationService = class {
28021
28016
  );
28022
28017
  const hubWalletAddress = await this.hubProvider.getUserHubWalletAddress(
28023
28018
  params.srcAddress,
28024
- ChainKeys.SONIC_MAINNET
28019
+ ChainKeys.ICON_MAINNET
28025
28020
  );
28026
28021
  const coreParams = {
28027
28022
  srcChainKey: ChainKeys.ICON_MAINNET,
@@ -29121,11 +29116,7 @@ var BridgeService = class {
29121
29116
  * checking theoretical bridgeability without requiring both chains to be in the active config.
29122
29117
  * @returns `true` if the tokens share the same hub vault; `false` otherwise.
29123
29118
  */
29124
- isBridgeable({
29125
- from,
29126
- to,
29127
- unchecked = false
29128
- }) {
29119
+ isBridgeable({ from, to, unchecked = false }) {
29129
29120
  try {
29130
29121
  if (!unchecked) {
29131
29122
  bridgeInvariant(this.config.isValidSpokeChainKey(from.chainKey), `Invalid spoke chain (${from.chainKey})`, {
@@ -34319,7 +34310,8 @@ var UiPoolDataProviderService = class {
34319
34310
  // The borrow index must also come from the bnUSD debt token.
34320
34311
  // User debt is stored scaled by bnUSD's index, so reading it back requires the same index.
34321
34312
  // Using the vault's index here would inflate the displayed debt amount.
34322
- variableBorrowIndex: bnUSDReserve.variableBorrowIndex
34313
+ variableBorrowIndex: bnUSDReserve.variableBorrowIndex,
34314
+ borrowingEnabled: bnUSDReserve.borrowingEnabled
34323
34315
  };
34324
34316
  return [
34325
34317
  [
@@ -36707,5 +36699,3 @@ var isPartnerError = isCodeMember(PARTNER_CODES);
36707
36699
  */
36708
36700
 
36709
36701
  export { ALLOWANCE_CHECK_CODES, APPROVE_CODES, AssetService, BITCOIN_CHAIN_KEYS, BITCOIN_CHAIN_KEYS_SET, BTC_WALLET_ADDRESS_TYPES, BackendApiService, BalnSwapService, BigIntToHex, BigNumberZeroDecimal, BitcoinSpokeService, BnUSDMigrationService, BridgeService, CHAIN_KEYS, CONFIG_VERSION, CREATE_INTENT_CODES, ChainKeys, ChainTypeArr, ClService, ConfigService, CustomSorobanServer, CustomStellarAccount, DEFAULT_BACKEND_API_ENDPOINT, DEFAULT_BACKEND_API_HEADERS, DEFAULT_BACKEND_API_TIMEOUT, DEFAULT_DEADLINE_OFFSET, DEFAULT_MAX_RETRY, DEFAULT_RELAYER_API_ENDPOINT, DEFAULT_RELAY_TX_TIMEOUT, DEFAULT_RETRY_DELAY_MS, DexService, EVM_CHAIN_ID_TO_KEY, EVM_CHAIN_KEYS, EVM_CHAIN_KEYS_SET, EVM_SPOKE_ONLY_CHAIN_KEYS, EVM_SPOKE_ONLY_CHAIN_KEYS_SET, Erc20Service, Erc4626Service, EvmAssetManagerService, EvmHubProvider, EvmSolverService, EvmSpokeService, EvmVaultTokenService, FEE_PERCENTAGE_SCALE, GAS_ESTIMATION_CODES, HALF_RAY, HALF_WAD, HUB_CHAIN_KEY, HttpRelayError, HubVaultSymbols, ICON_CHAIN_KEYS, ICON_CHAIN_KEYS_SET, ICON_TX_RESULT_WAIT_MAX_RETRY, INJECTIVE_CHAIN_KEYS, INJECTIVE_CHAIN_KEYS_SET, INTENT_CHAIN_IDS, IconSpokeService, IcxMigrationService, Injective20Token, InjectiveSpokeService, IntentCreatedEventAbi, IntentDataType, IntentFilledEventAbi, IntentRelayChainIdToChainKey, IntentsAbi, LOOKUP_CODES, LTV_PRECISION, LendingPoolService, LockupMultiplier, LockupPeriod, MAX_UINT256, MigrationService, MintPositionEventAbi, MoneyMarketDataService, MoneyMarketService, NEAR_CHAIN_KEYS, NEAR_CHAIN_KEYS_SET, NEAR_DEFAULT_GAS, NearSpokeService, PartnerFeeClaimService, PartnerService, Permit2Service, ProtocolIntentsAbi, RAY, RAY_DECIMALS, RELAY_ERROR_CODES, RadfiApiError, RadfiProvider, RecoveryService, RelayChainIdMap, SECONDS_PER_YEAR, SODAX_ERROR_CODES, SODAX_FEATURES, SOLANA_CHAIN_KEYS, SOLANA_CHAIN_KEYS_SET, SONIC_CHAIN_KEYS, SONIC_CHAIN_KEYS_SET, STACKS_CHAIN_KEYS, STACKS_CHAIN_KEYS_SET, STELLAR_CHAIN_KEYS, STELLAR_CHAIN_KEYS_SET, SUI_CHAIN_KEYS, SUI_CHAIN_KEYS_SET, SodaTokens, Sodax, SodaxError, SolanaSpokeService, SolverApiService, SolverIntentErrorCode, SolverIntentStatusCode, SonicSpokeService, SpokeService, StacksSpokeService, StakingLogic, StakingService, StatATokenAddresses, StellarSpokeService, SuiSpokeService, SupportedMigrationTokens, SwapService, USD_DECIMALS, UiPoolDataProviderService, VAULT_TOKEN_DECIMALS, WAD, WAD_RAY_RATIO, WEI_DECIMALS, adjustAmountByFee, allowanceCheckFailed, apiConfig, approveFailed, arbitrumSupportedTokens, assetManagerAbi, avalancheSupportedTokens, balnSwapAbi, baseChainInfo, baseSupportedTokens, binomialApproximatedRayPow, bitcoinSupportedTokens, bnUSDLegacySpokeChainIds, bnUSDLegacyTokens, bridgeConfig, bridgeInvariant, bscSupportedTokens, calculateAllReserveIncentives, calculateAllUserIncentives, calculateAvailableBorrowsMarketReferenceCurrency, calculateCompoundedInterest, calculateCompoundedRate, calculateFeeAmount, calculateHealthFactorFromBalances, calculateHealthFactorFromBalancesBigUnits, calculateLinearInterest, calculatePercentageFeeAmount, clPoolAbi, clPoolManagerAbi, clPositionManagerAbi, clQuoterAbi, clRouterAbi, clTickLensAbi, concentratedLiquidityConfig, connectionAbi, convertTransactionInstructionToRaw, createInvariant, deepMerge, defaultHookAbi, detectBitcoinAddressType, dexConfig, dexInvariant, dexPools, encodeAddress, encodeBtcPayloadToBytes, encodeContractCalls, erc20Abi, erc4626Abi, estimateBitcoinTxSize, ethereumSupportedTokens, executionFailed, formatBasisPoints, formatEModeCategory, formatEModes, formatPercentage, formatReserve, formatReserveUSD, formatReserves, formatReservesAndIncentives, formatUserSummary, formatUserSummaryAndIncentives, gasEstimationFailed, getAllLegacybnUSDTokens, getAndFormatReserveEModes, getAssetManagerIdl, getAssetManagerProgram, getChainKeyFromRelayChainId, getChainType, getCompoundedBalance, getConcentratedLiquidityConfig, getConnectionIdl, getConnectionProgram, getEvmChainKeyByChainId, getEvmViemChain, getIconAddressBytes, getIntentRelayChainId, getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getPacket, getProvider, getRandomBytes, getReserveNormalizedIncome, getReservesEModes, getSolanaAddressBytes, getSolverConfig, getSupportedSolverTokens, getTransactionPackets, getbnUSDToken, hexToBigInt, hexToSolanaAddress, hubConfig, hyper, hyperevmSupportedTokens, iconSupportedTokens, injectiveSupportedTokens, intentCreationFailed, isBalnMigrateParams, isBitcoinChainKey, isBitcoinChainKeyType, isBitcoinWalletProviderType, isBridgeAllowanceCheckError, isBridgeApproveError, isBridgeCreateIntentError, isBridgeError, isBridgeLookupError, isBridgeOrchestrationError, isCodeMember, isDexError, isEvmChainKey, isEvmChainKeyType, isEvmSpokeChainConfig, isEvmSpokeOnlyChainKey, isEvmSpokeOnlyChainKeyType, isEvmWalletProviderType, isFeatureError, isHubChainKey, isHubChainKeyType, isIconAddress, isIconChainKey, isIconChainKeyType, isIcxCreateRevertMigrationParams, isIcxMigrateParams, isInjectiveChainKey, isInjectiveChainKeyType, isJsonRpcPayloadResponse, isLegacybnUSDChainId, isLegacybnUSDToken, isMigrateOrchestrationError, isMigrationAllowanceCheckError, isMigrationApproveError, isMigrationCreateIntentError, isMigrationError, isMigrationLookupError, isMoneyMarketAllowanceCheckError, isMoneyMarketApproveError, isMoneyMarketCreateIntentError, isMoneyMarketError, isMoneyMarketGasEstimationError, isMoneyMarketOrchestrationError, isNativeToken, isNearChainKey, isNearChainKeyType, isNewbnUSDChainId, isNewbnUSDToken, isOptionalBitcoinWalletProviderType, isOptionalEvmWalletProviderType, isOptionalStellarWalletProviderType, isPartnerError, isPartnerFeeAmount, isPartnerFeePercentage, isPostExecutionError, isRawDestinationParams, isRecoveryError, isResponseAddressType, isResponseSigningType, isRevertMigrationOrchestrationError, isSodaxError, isSolanaChainKey, isSolanaChainKeyType, isSolanaNativeToken, isSonicChainKey, isSonicChainKeyType, isSpokeApproveParamsEvmSpoke, isSpokeApproveParamsHub, isSpokeApproveParamsStellar, isSpokeChainKey, isSpokeIsAllowanceValidParamsEvmSpoke, isSpokeIsAllowanceValidParamsHub, isSpokeIsAllowanceValidParamsStellar, isStacksChainKey, isStacksChainKeyType, isStakeOrchestrationError, isStakingAllowanceCheckError, isStakingApproveError, isStakingCreateIntentError, isStakingError, isStakingInfoFetchError, isStakingOrchestrationError, isStellarChainKey, isStellarChainKeyType, isStellarWalletProviderType, isSubmitSwapTxResponse, isSubmitSwapTxStatusResponse, isSuiChainKey, isSuiChainKeyType, isSupportedBitcoinAddressType, isSwapCreateIntentError, isSwapError, isSwapSupportedToken, isUndefinedOrValidWalletProviderForChainKey, isUnifiedBnUSDMigrateParams, isValidWalletProviderForChainKey, kaiaSupportedTokens, lightlinkSupportedTokens, lookupFailed, mapRelayFailure, messageOf, migrationInvariant, mintPositionParamsAbi, mmInvariant, modifyLiquidityParamsAbi, moneyMarketConfig, moneyMarketReserveAssets, moneyMarketSupportedTokens, nativeToUSD, nearSupportedTokens, newbnUSDSpokeChainIds, normalize, normalizeBN, normalizePsbtToBase64, normalizedToUsd, optimismSupportedTokens, pancakeSwapInfinityDefaultHookAbi, pancakeSwapInfinityPoolManagerAbi, pancakeSwapInfinityPositionManagerAbi, parseToStroops, parseTokenArrayFromJson, partnerInvariant, permit2Abi, polygonSupportedTokens, poolAbi, poolKeyAbi, randomUint256, rayDiv, rayMul, rayPow, rayToWad, recoveryInvariant, redbellySupportedTokens, relayConfig, relayTxAndWaitPacket, requestAddress, requestJsonRpc, requestSigning, retry, reverseEncodeAddress, serializeAddressData, sleep, sodaxConfig, sodaxInvariant, solanaSupportedTokens, solverConfig, sonicSupportedTokens, sonicWalletFactoryAbi, spokeAssetManagerAbi, spokeChainConfig, spokeChainKeysSet, stacksSupportedTokens, stakedSodaAbi, stakingInvariant, stakingRouterAbi, stataTokenFactoryAbi, stellarSupportedTokens, submitTransaction, suiSupportedTokens, supportedSpokeChains, supportedTokensByChain, swapExactInSingleParamsAbi, swapInvariant, swapSupportedTokens, swapsConfig, uiPoolDataAbi, universalRouterAbi, unknownFailed, valueToBigNumber, valueToZDBigNumber, variableDebtTokenAbi, vaultTokenAbi, verifyFailed, wadToRay, waitForStacksTransaction, waitForTransactionReceipt, waitUntilIntentExecuted, walletFactoryAbi, wrappedSonicAbi };
36710
- //# sourceMappingURL=index.mjs.map
36711
- //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "2.0.0-rc.3",
7
+ "version": "2.0.0-rc.5",
8
8
  "license": "MIT",
9
9
  "description": "Sodax SDK",
10
10
  "keywords": [
@@ -27,45 +27,46 @@
27
27
  "types": "./dist/index.d.ts",
28
28
  "exports": {
29
29
  ".": {
30
- "types": "./dist/index.d.ts",
31
- "import": "./dist/index.mjs",
32
- "require": "./dist/index.cjs"
33
- }
30
+ "import": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.mjs"
33
+ },
34
+ "require": {
35
+ "types": "./dist/index.d.cts",
36
+ "default": "./dist/index.cjs"
37
+ }
38
+ },
39
+ "./package.json": "./package.json"
34
40
  },
35
41
  "engines": {
36
- "node": ">=20.0.0"
42
+ "node": ">=20.12.0"
37
43
  },
38
44
  "files": [
39
45
  "dist",
40
- "ai-exported"
46
+ "!dist/**/*.map"
41
47
  ],
48
+ "sideEffects": false,
42
49
  "dependencies": {
43
50
  "@bitcoinerlab/secp256k1": "^1.2.0",
44
51
  "@coral-xyz/anchor": "0.30.1",
45
52
  "@injectivelabs/networks": "1.18.14",
46
53
  "@injectivelabs/sdk-ts": "1.18.14",
47
54
  "@mysten/sui": "1.21.2",
48
- "@ordjs/runestone": "^1.6.0",
49
- "@pancakeswap/chains": "^0.7.0",
50
55
  "@pancakeswap/infinity-sdk": "^1.0.0",
51
- "@pancakeswap/permit2-sdk": "^1.1.7",
52
56
  "@pancakeswap/swap-sdk-core": "^1.5.1",
53
57
  "@pancakeswap/v3-sdk": "^3.9.7",
54
58
  "@solana/spl-token": "0.4.9",
55
59
  "@solana/web3.js": "1.98.0",
56
- "@stacks/network": "7.3.1",
57
- "@stacks/transactions": "7.3.1",
58
60
  "@stellar/stellar-sdk": "15.1.0",
59
61
  "bignumber.js": "9.3.1",
60
62
  "bitcoinjs-lib": "^6.1.5",
61
63
  "bn.js": "^5.2.1",
62
- "ecpair": "^2.0.1",
63
64
  "icon-sdk-js": "1.5.3",
64
65
  "near-api-js": "7.2.0",
65
66
  "rlp": "3.0.0",
66
- "runelib": "^1.0.7",
67
67
  "viem": "2.29.2",
68
- "@sodax/types": "2.0.0-rc.3"
68
+ "@sodax/libs": "0.0.1-rc.0",
69
+ "@sodax/types": "2.0.0-rc.5"
69
70
  },
70
71
  "devDependencies": {
71
72
  "@arethetypeswrong/cli": "0.17.4",
@@ -74,11 +75,12 @@
74
75
  "@stryker-mutator/vitest-runner": "9.6.1",
75
76
  "@types/bn.js": "^5.1.6",
76
77
  "@types/node": "22.18.1",
77
- "@vitest/coverage-v8": "2.1.9",
78
+ "@vitest/coverage-v8": "3.2.4",
79
+ "knip": "5.30.5",
78
80
  "madge": "8.0.0",
79
81
  "tsup": "8.5.0",
80
82
  "typescript": "5.5.4",
81
- "vitest": "2.1.9"
83
+ "vitest": "3.2.4"
82
84
  },
83
85
  "scripts": {
84
86
  "build": "tsup",
@@ -86,17 +88,14 @@
86
88
  "test-e2e": "vitest run ./src/e2e-tests",
87
89
  "coverage": "vitest run --coverage",
88
90
  "dev": "tsup --watch",
89
- "ci": "pnpm run pretty && pnpm run build && pnpm run test && pnpm run check:ai-exported && pnpm run check:ai-scope && pnpm run check:ai-links && pnpm run check:ai-imports",
91
+ "ci": "pnpm run pretty && pnpm run build && pnpm run test",
90
92
  "checkTs": "tsc --noEmit",
91
93
  "pretty": "biome format . --write",
92
94
  "lint": "biome lint . --write",
93
- "check-exports": "attw $(pnpm pack) --ignore-rules=cjs-resolves-to-esm",
95
+ "size:check": "node ./scripts/size-check.mjs",
96
+ "check-exports": "attw --pack",
94
97
  "check:circular-deps": "madge --circular --exclude 'types/dist' $(find ./src -name '*.ts')",
95
- "check:ai-exported": "bash ./scripts/check-ai-exported.sh",
96
- "check:ai-scope": "bash ./scripts/check-ai-scope.sh",
97
- "check:ai-links": "bash ./scripts/check-ai-links.sh",
98
- "check:ai-imports": "bash ./scripts/check-ai-imports.sh",
99
- "check:ai": "pnpm run check:ai-exported && pnpm run check:ai-scope && pnpm run check:ai-links && pnpm run check:ai-imports",
98
+ "check:knip": "knip",
100
99
  "local-release": "changeset version && changeset publish",
101
100
  "clean": "rm -rf node_modules && rm -rf dist && rm -rf .turbo"
102
101
  }
@@ -1,99 +0,0 @@
1
- # AGENTS.md — `@sodax/sdk` v2
2
-
3
- > Tool-neutral entry point for any AI coding agent assisting a consumer of `@sodax/sdk`. If you're at `node_modules/@sodax/sdk/ai-exported/AGENTS.md`, you are in the right place — everything you need is reachable from here without leaving the npm tarball.
4
-
5
- ## Project
6
-
7
- `@sodax/sdk` is the official SDK for SODAX, a cross-chain DeFi platform built on a hub-and-spoke architecture (Sonic is the hub; 19 spoke chains across EVM and non-EVM ecosystems). The SDK provides cross-chain swaps (intent-based via solver), lending/borrowing (money market), staking, bridging, concentrated-liquidity DEX, ICX/bnUSD/BALN migration, and partner-fee operations. It is runtime-agnostic and runs in Node.js, browsers, and bundled apps.
8
-
9
- This package is **v2**. v2 was a deep architectural reshape of v1 — chain-key driven routing replaced per-chain provider classes; `Result<T>` replaced throwing methods; `SodaxError<C>` replaced module-specific error unions; `WalletProviderSlot<K, Raw>` replaced ad-hoc wallet/raw branching; `ConfigService` replaced static lookup tables. Code written against v1 will not compile against v2.
10
-
11
- ## When to read what
12
-
13
- ```
14
- Are you writing NEW code against v2? → integration/ai-rules.md, then integration/
15
- Are you porting EXISTING v1 code to v2? → migration/ai-rules.md, then migration/
16
- Just need a chain key / error code / type? → integration/reference/
17
- Need to install + initialize the SDK? → integration/quickstart.md
18
- Hit a non-EVM chain quirk (Stellar, BTC, …)? → integration/chain-specifics.md
19
- ```
20
-
21
- If a consumer's repo has both v1 call sites and a request to extend with new code, do migration first. Stale v1 patterns leak into new code if you skip it.
22
-
23
- **Always start with the `ai-rules.md` for the tree you're working in** — it's the consolidated DO / DO NOT / workflow / stop-conditions guide that prevents the most common v2 traps. Read it once, then dive into the per-feature docs.
24
-
25
- ## Top-level layout
26
-
27
- ```
28
- ai-exported/
29
- ├── AGENTS.md # You are here
30
- ├── integration/ # How to use v2 (new consumers)
31
- │ ├── README.md # Index for this tree
32
- │ ├── ai-rules.md # DO / DO NOT / workflow — read before per-feature docs
33
- │ ├── quickstart.md # Install + initialize + first-run troubleshooting
34
- │ ├── architecture.md # Every v2 design concept (TOC-navigable)
35
- │ ├── features/ # One file per feature service
36
- │ │ ├── README.md
37
- │ │ ├── swap.md
38
- │ │ ├── money-market.md
39
- │ │ ├── staking.md
40
- │ │ ├── bridge.md
41
- │ │ ├── dex.md
42
- │ │ ├── icx-bnusd-baln.md # MigrationService (the SDK module, not the v1→v2 port)
43
- │ │ └── auxiliary-services.md # PartnerService + RecoveryService + BackendApiService
44
- │ ├── recipes/ # One file per pattern — init, result/errors, raw, signed, narrowing, testing, gas, backend-init
45
- │ ├── reference/ # One file per table — chain keys, wallet providers, error codes, public API, glossary
46
- │ └── chain-specifics.md # Non-EVM quirks (Stellar trustline, BTC PSBT, Solana PDA, ICON, NEAR)
47
- └── migration/ # How to port v1 → v2
48
- ├── README.md # Overview + reading order + cross-cutting checklist + v1↔v2 glossary
49
- ├── ai-rules.md # DO / DO NOT / workflow for porting agents
50
- ├── breaking-changes/ # Cross-cutting v1→v2 changes
51
- │ ├── type-system.md # @sodax/types renames + ChainKeys + WalletProviderSlot + RpcConfig + IConfigApi Result
52
- │ ├── architecture.md # *SpokeProvider deletion + ConfigService + relay reshape + invariants
53
- │ └── result-and-errors.md # Throws → Result<T>; module errors → SodaxError<C>; v1↔v2 code crosswalk; return shapes
54
- ├── features/ # Per-feature pure-SDK migration playbooks
55
- │ ├── README.md
56
- │ ├── swap.md, money-market.md, staking.md, bridge.md, dex.md, icx-bnusd-baln.md, auxiliary-services.md
57
- └── recipes.md # Codemods + error-shape adapter + result adapter
58
- ```
59
-
60
- ## v2 in one minute
61
-
62
- 1. **Chain key drives everything.** Pass `srcChainKey: ChainKeys.ETHEREUM_MAINNET` (or any of 20 keys) on the request payload. The SDK routes to the correct per-chain spoke service internally and TypeScript narrows the wallet-provider parameter to the chain-specific interface via `GetWalletProviderType<K>`. There are **no** `*SpokeProvider` classes to construct.
63
- 2. **Every async public method returns `Result<T>`.** Branch on `result.ok`. No throws across service boundaries. Sub-Result forwarding is the default: `if (!sub.ok) return sub`.
64
- 3. **Errors are `SodaxError<C>`.** A single class with a closed 13-code reason vocabulary (`VALIDATION_FAILED`, `RELAY_TIMEOUT`, `EXECUTION_FAILED`, …) plus a `feature` field (`'swap' | 'moneyMarket' | …`). The pair `(feature, code)` is your discriminator. Use `isSodaxError(e)` (not bare `instanceof`).
65
- 4. **Signed vs raw is a discriminated union.** `WalletProviderSlot<K, Raw>` enforces at compile time: `{ raw: false, walletProvider: <chain-narrowed> }` for signing, `{ raw: true }` for unsigned-tx building. Mixing them is a TypeScript error.
66
- 5. **Config is dynamic; overrides only land on `sodax.config`.** Once a `Sodax` instance exists, always read via `sodax.config.*` (e.g. `sodax.config.spokeChainConfig[chainKey]`) — direct imports of `spokeChainConfig` / `sodaxConfig` from `@sodax/types` / `@sodax/sdk` are packaged-default snapshots and silently miss both `await sodax.config.initialize()` updates and `new Sodax(config)` overrides. Full instance-scope-reader table + module-scope rules: [`integration/recipes/initialize-sodax.md`](integration/recipes/initialize-sodax.md) § *Module-scope reads*. Per-symbol status of v1 globals: [`migration/breaking-changes/architecture.md`](migration/breaking-changes/architecture.md) § 2.
67
-
68
- ## Top 5 v1 → v2 traps
69
-
70
- 1. **Reaching for a `*SpokeProvider`.** They're deleted. Pass an object satisfying the chain-specific `I*WalletProvider` interface (e.g. `IEvmWalletProvider`) directly into the SDK call payload. Implementations come from your application — write your own to satisfy the interface, or install `@sodax/wallet-sdk-core` (a separate SODAX package, not bundled into `@sodax/sdk`) for ready-made implementations. The chain key on the payload is what routes — there is no provider class for `@sodax/sdk` consumers to instantiate.
71
- 2. **Forgetting `raw: false`.** Without the discriminator, `walletProvider` is rejected with "Object literal may only specify known properties, and 'walletProvider' does not exist in type". Add `raw: false` for signed flows; `raw: true` for unsigned-tx building.
72
- 3. **Importing from `@sodax/types` directly.** `@sodax/sdk` re-exports the entire `@sodax/types` surface via its barrel. Add `@sodax/sdk` as your only dependency; importing `@sodax/types` separately risks version skew.
73
- 4. **Treating `Result<T>` as throw-on-failure.** v2 mutation methods do **not** throw on SDK-level failure — they resolve `{ ok: false, error }`. A `try { await sodax.<method>(...) } catch` only catches *exceptions* from inside `mutationFn` (e.g. missing `walletProvider`); it will **not** catch `RELAY_TIMEOUT` or `EXECUTION_FAILED`. Branch on `.ok`.
74
- 5. **Reading `xToken.xChainId` or hard-coding `*_MAINNET_CHAIN_ID`.** Renamed: `XToken.chainKey` and `ChainKeys.*`. v1 numeric/string chain-id constants are gone. `ChainKeys.ICON_MAINNET` is `'0x1.icon'` (a string), not the legacy numeric ID — `Number(chainKey)` returns `NaN`.
75
-
76
- See `migration/README.md` for the complete trap list and `migration/breaking-changes/` for full v1↔v2 detail.
77
-
78
- ## Public API contract
79
-
80
- - Import only from the package root: `import { Sodax, ChainKeys, type SpokeChainKey } from '@sodax/sdk'`.
81
- - Do **not** add `@sodax/types` to your dependencies — `@sodax/sdk` re-exports the full types surface (`export * from '@sodax/types'` from the barrel). Importing `@sodax/types` separately is unsupported and may silently version-skew.
82
- - Do **not** deep-import from `dist/...`. Internal paths are not stable across releases. Anything intended for consumer use is exported from the root.
83
- - The published tarball ships `dist/` and `ai-exported/`. Do not rely on any other path being present.
84
-
85
- ## Conventions agents must follow
86
-
87
- - **`Result<T>` discrimination on `.ok`.** Always branch on `result.ok` before reading `.value` or `.error`. Forward sub-Results without re-wrapping (`if (!sub.ok) return sub`).
88
- - **`(feature, code)` for error switching.** Use `isSodaxError(e)`, then `e.feature` and `e.code` for routing logic. Don't string-match on `e.message`.
89
- - **`ChainKeys.*` over hard-coded strings.** Use `ChainKeys.ETHEREUM_MAINNET`, not `'eth'` / `'0xa86a.fuji'`. The set of supported chains evolves per release.
90
- - **No `as unknown as <Type>` double-casts.** v2 type narrowing makes them unnecessary in 99% of cases — chain-key generic flow + `GetWalletProviderType<K>` resolves to the exact interface. If a cast feels needed, look for the chain-key narrowing pattern in `integration/recipes/` first.
91
- - **Conventional commits if generating commits** in the consumer repo (`feat:`, `fix:`, `chore:`). Many SODAX-adjacent repos enforce this via commitlint.
92
- - **Don't generate `try { await sodax.<method>(...) } catch` for SDK-level failures.** That catch never fires for `Result` `!ok`. Branch on `result.ok`.
93
-
94
- ## Pointers
95
-
96
- - `integration/README.md` — start here for any new v2 work.
97
- - `migration/README.md` — start here for any v1 → v2 port.
98
- - `integration/quickstart.md` — install, initialize, first-run troubleshooting.
99
- - `integration/reference/` — chain key table, error code table, public API surface, glossary.
@@ -1,41 +0,0 @@
1
- # Integration — `@sodax/sdk` v2
2
-
3
- This tree documents v2 of the SDK for **new consumers** building against it. If you're porting v1 code, start at [`../migration/README.md`](../migration/README.md) instead.
4
-
5
- ## Files in this tree
6
-
7
- | File | What's in it |
8
- |---|---|
9
- | [`quickstart.md`](quickstart.md) | Install, initialize a `Sodax` instance, and the top init/setup errors and how to fix them. Covers reads (no wallet), raw-tx flows (no wallet), and signed flows (consumer-supplied wallet provider). |
10
- | [`architecture.md`](architecture.md) | Every v2 design concept the SDK rests on, in a single TOC-navigable file: hub-and-spoke model, `SpokeService` router, `Sodax` facade + `ConfigService`, `ChainKeys`, `WalletProviderSlot<K, Raw>`, `Result<T>`, `SodaxError<C>` + 13-code vocabulary, relay layer (`mapRelayFailure`, `relayTxAndWaitPacket`). |
11
- | [`features/swap.md`](features/swap.md) | `SwapService`: intent-based swaps via the solver — `createIntent`, `swap`, `postExecution`, limit orders, `cancelIntent`. |
12
- | [`features/money-market.md`](features/money-market.md) | `MoneyMarketService`: cross-chain lending/borrowing — supply, borrow, withdraw, repay, reserves, allowance. |
13
- | [`features/staking.md`](features/staking.md) | `StakingService`: SODA → xSoda — stake, unstake, instant unstake, claim, cancel; ratio + info reads. |
14
- | [`features/bridge.md`](features/bridge.md) | `BridgeService`: cross-chain token transfer via vault — `bridge`, `createBridgeIntent`, `getBridgeableAmount`, `getBridgeableTokens`. |
15
- | [`features/dex.md`](features/dex.md) | `ClService` (concentrated liquidity) + `AssetService`: position lifecycle (mint/increase/decrease), claim rewards, asset deposit/withdraw. |
16
- | [`features/icx-bnusd-baln.md`](features/icx-bnusd-baln.md) | `MigrationService` (the SDK module): ICX, bnUSD, BALN sub-services + lock management. |
17
- | [`features/auxiliary-services.md`](features/auxiliary-services.md) | `PartnerService` + `RecoveryService` + `BackendApiService` — small APIs grouped together. |
18
- | [`recipes/`](recipes/) | Copy-pasteable patterns: SDK initialization, `Result` + error discrimination, raw-tx flow, signed-tx flow, chain-key narrowing + cast-at-boundary, testing (mocks/stubs), gas estimation, backend-server init. |
19
- | [`reference/`](reference/) | Lookup tables: 20-chain `ChainKeys` table with family + relay id, `I*WalletProvider` interfaces, 13 `SodaxErrorCode` meanings + per-feature narrow unions, public API surface (incl. `@sodax/types` re-export rule), glossary. |
20
- | [`chain-specifics.md`](chain-specifics.md) | Non-EVM quirks — Stellar trustline check/request, Bitcoin PSBT + Radfi auth/session, Solana PDA derivation, ICON Hana wallet + chain-key string, NEAR connector discovery. |
21
-
22
- ## Reading order for a new integrator
23
-
24
- 1. `quickstart.md` — get the SDK installed and a `Sodax` instance running.
25
- 2. `architecture.md` — understand the type system (`ChainKeys`, `Result`, `WalletProviderSlot`, `SodaxError`) before writing call sites.
26
- 3. `recipes/` — pick the patterns you need (signed vs raw, error handling, narrowing).
27
- 4. `features/<x>.md` — read the file for the feature you're integrating.
28
- 5. `chain-specifics.md` — only if you target a non-EVM chain; skip otherwise.
29
- 6. `reference/` — keep open while writing for table lookups.
30
-
31
- ## Cross-references to migration
32
-
33
- If your project also has v1 call sites, port them first using:
34
-
35
- - [`../migration/README.md`](../migration/README.md) — overview, reading order, and cross-cutting checklist.
36
- - [`../migration/breaking-changes/type-system.md`](../migration/breaking-changes/type-system.md) — type renames and shape changes you'll hit on import.
37
- - [`../migration/breaking-changes/architecture.md`](../migration/breaking-changes/architecture.md) — `*SpokeProvider` deletion, `ConfigService` replacing static lookups, relay flow reshape.
38
- - [`../migration/breaking-changes/result-and-errors.md`](../migration/breaking-changes/result-and-errors.md) — throws → `Result<T>` and module errors → `SodaxError<C>`, with the v1↔v2 code crosswalk.
39
- - [`../migration/features/`](../migration/features/) — per-feature playbooks in lockstep with the integration features here.
40
-
41
- The naming rule: **every feature in `integration/features/` has a sibling in `migration/features/` with the same filename.** When you're deep in one, the other is one path-swap away.