@sodax/skills 2.0.0-rc.8 → 2.0.0

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 (168) hide show
  1. package/.claude-plugin/plugin.json +1 -0
  2. package/AGENTS.md +123 -13
  3. package/README.md +5 -2
  4. package/package.json +1 -1
  5. package/skills/sodax-build/SKILL.md +90 -0
  6. package/skills/sodax-build/knowledge/README.md +35 -0
  7. package/skills/sodax-build/knowledge/brief-template.md +41 -0
  8. package/skills/sodax-build/knowledge/chains-and-assets.md +26 -0
  9. package/skills/sodax-build/knowledge/example-sessions.md +84 -0
  10. package/skills/sodax-build/knowledge/feature-catalog.md +51 -0
  11. package/skills/sodax-build/knowledge/glossary.md +35 -0
  12. package/skills/sodax-build/knowledge/handoff.md +60 -0
  13. package/skills/sodax-build/knowledge/interview-guide.md +66 -0
  14. package/skills/sodax-build/knowledge/monetization.md +37 -0
  15. package/skills/sodax-build/knowledge/use-case-gallery.md +32 -0
  16. package/skills/sodax-dapp-kit/SKILL.md +6 -2
  17. package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +65 -0
  18. package/skills/sodax-dapp-kit/bitcoin/SKILL.md +57 -0
  19. package/skills/sodax-dapp-kit/bridge/SKILL.md +59 -0
  20. package/skills/sodax-dapp-kit/dex/SKILL.md +60 -0
  21. package/skills/sodax-dapp-kit/integration/knowledge/README.md +1 -1
  22. package/skills/sodax-dapp-kit/integration/knowledge/features/README.md +3 -2
  23. package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +71 -11
  24. package/skills/sodax-dapp-kit/integration/knowledge/features/bitcoin.md +10 -6
  25. package/skills/sodax-dapp-kit/integration/knowledge/features/dex.md +2 -2
  26. package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +112 -0
  27. package/skills/sodax-dapp-kit/integration/knowledge/features/migration.md +1 -1
  28. package/skills/sodax-dapp-kit/integration/knowledge/features/money-market.md +6 -1
  29. package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +1 -1
  30. package/skills/sodax-dapp-kit/integration/knowledge/quickstart.md +2 -2
  31. package/skills/sodax-dapp-kit/integration/knowledge/recipes/README.md +1 -0
  32. package/skills/sodax-dapp-kit/integration/knowledge/recipes/backend-queries.md +23 -8
  33. package/skills/sodax-dapp-kit/integration/knowledge/recipes/bitcoin.md +8 -8
  34. package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +168 -0
  35. package/skills/sodax-dapp-kit/integration/knowledge/recipes/migration.md +1 -1
  36. package/skills/sodax-dapp-kit/integration/knowledge/recipes/setup.md +4 -4
  37. package/skills/sodax-dapp-kit/integration/knowledge/recipes/swap.md +1 -1
  38. package/skills/sodax-dapp-kit/integration/knowledge/recipes/wallet-connectivity.md +3 -0
  39. package/skills/sodax-dapp-kit/integration/knowledge/reference/glossary.md +1 -1
  40. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +67 -6
  41. package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +49 -0
  42. package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +54 -0
  43. package/skills/sodax-dapp-kit/migration/SKILL.md +64 -0
  44. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/breaking-changes/hook-signatures.md +1 -1
  45. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/breaking-changes/sdk-leakage.md +2 -2
  46. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/checklist.md +1 -1
  47. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/README.md +1 -1
  48. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/auxiliary-services.md +19 -10
  49. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/bitcoin.md +2 -2
  50. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/bridge.md +1 -1
  51. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/dex.md +1 -1
  52. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/migration.md +1 -1
  53. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/reference/renamed-hooks.md +3 -3
  54. package/skills/sodax-dapp-kit/money-market/SKILL.md +61 -0
  55. package/skills/sodax-dapp-kit/staking/SKILL.md +60 -0
  56. package/skills/sodax-dapp-kit/swap/SKILL.md +64 -0
  57. package/skills/sodax-sdk/SKILL.md +54 -50
  58. package/skills/sodax-sdk/backend-api/SKILL.md +58 -0
  59. package/skills/sodax-sdk/bridge/SKILL.md +53 -0
  60. package/skills/sodax-sdk/dex/SKILL.md +54 -0
  61. package/skills/sodax-sdk/integration/knowledge/README.md +5 -3
  62. package/skills/sodax-sdk/integration/knowledge/ai-rules.md +1 -1
  63. package/skills/sodax-sdk/integration/knowledge/architecture.md +26 -39
  64. package/skills/sodax-sdk/integration/knowledge/chain-specifics.md +57 -10
  65. package/skills/sodax-sdk/integration/knowledge/features/README.md +6 -3
  66. package/skills/sodax-sdk/integration/knowledge/features/backend-api.md +92 -0
  67. package/skills/sodax-sdk/integration/knowledge/features/bridge.md +48 -11
  68. package/skills/sodax-sdk/integration/knowledge/features/dex.md +7 -7
  69. package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +175 -0
  70. package/skills/sodax-sdk/integration/knowledge/features/{icx-bnusd-baln.md → migration.md} +75 -30
  71. package/skills/sodax-sdk/integration/knowledge/features/money-market.md +20 -25
  72. package/skills/sodax-sdk/integration/knowledge/features/partner.md +86 -0
  73. package/skills/sodax-sdk/integration/knowledge/features/recovery.md +51 -0
  74. package/skills/sodax-sdk/integration/knowledge/features/staking.md +8 -3
  75. package/skills/sodax-sdk/integration/knowledge/features/swap.md +106 -22
  76. package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +171 -0
  77. package/skills/sodax-sdk/integration/knowledge/quickstart.md +1 -1
  78. package/skills/sodax-sdk/integration/knowledge/recipes/README.md +1 -0
  79. package/skills/sodax-sdk/integration/knowledge/recipes/backend-server-init.md +3 -3
  80. package/skills/sodax-sdk/integration/knowledge/recipes/gas-estimation.md +8 -4
  81. package/skills/sodax-sdk/integration/knowledge/recipes/initialize-sodax.md +34 -2
  82. package/skills/sodax-sdk/integration/knowledge/recipes/logging.md +102 -0
  83. package/skills/sodax-sdk/integration/knowledge/recipes/raw-tx-flow.md +28 -4
  84. package/skills/sodax-sdk/integration/knowledge/recipes/result-and-errors.md +1 -1
  85. package/skills/sodax-sdk/integration/knowledge/recipes/testing.md +7 -11
  86. package/skills/sodax-sdk/integration/knowledge/reference/README.md +1 -1
  87. package/skills/sodax-sdk/integration/knowledge/reference/chain-keys.md +40 -4
  88. package/skills/sodax-sdk/integration/knowledge/reference/error-codes.md +32 -9
  89. package/skills/sodax-sdk/integration/knowledge/reference/glossary.md +2 -2
  90. package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +37 -4
  91. package/skills/sodax-sdk/leverage-yield/SKILL.md +50 -0
  92. package/skills/sodax-sdk/migration/SKILL.md +69 -0
  93. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/README.md +1 -1
  94. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/ai-rules.md +6 -10
  95. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/architecture.md +2 -2
  96. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/result-and-errors.md +3 -3
  97. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/type-system.md +6 -5
  98. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/checklist.md +2 -2
  99. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/README.md +4 -2
  100. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/backend-api.md +92 -0
  101. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/bridge.md +5 -5
  102. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/dex.md +2 -4
  103. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/{icx-bnusd-baln.md → migration.md} +31 -29
  104. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/money-market.md +2 -2
  105. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/partner.md +64 -0
  106. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/recovery.md +35 -0
  107. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/staking.md +8 -3
  108. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/swap.md +22 -18
  109. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/reference/sodax-config.md +19 -17
  110. package/skills/sodax-sdk/money-market/SKILL.md +56 -0
  111. package/skills/sodax-sdk/partner/SKILL.md +55 -0
  112. package/skills/sodax-sdk/recovery/SKILL.md +53 -0
  113. package/skills/sodax-sdk/staking/SKILL.md +53 -0
  114. package/skills/sodax-sdk/swap/SKILL.md +72 -0
  115. package/skills/sodax-sdk/swaps-api/SKILL.md +62 -0
  116. package/skills/sodax-wallet-sdk-core/SKILL.md +7 -3
  117. package/skills/sodax-wallet-sdk-core/bitcoin/SKILL.md +54 -0
  118. package/skills/sodax-wallet-sdk-core/evm/SKILL.md +54 -0
  119. package/skills/sodax-wallet-sdk-core/icon/SKILL.md +54 -0
  120. package/skills/sodax-wallet-sdk-core/injective/SKILL.md +54 -0
  121. package/skills/sodax-wallet-sdk-core/integration/knowledge/README.md +1 -1
  122. package/skills/sodax-wallet-sdk-core/integration/knowledge/ai-rules.md +2 -2
  123. package/skills/sodax-wallet-sdk-core/integration/knowledge/architecture.md +5 -5
  124. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/bitcoin.md +2 -2
  125. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +2 -2
  126. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/icon.md +5 -5
  127. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/injective.md +4 -2
  128. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/near.md +1 -1
  129. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/solana.md +2 -2
  130. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/stacks.md +2 -2
  131. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/stellar.md +2 -2
  132. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/sui.md +1 -1
  133. package/skills/sodax-wallet-sdk-core/integration/knowledge/quickstart.md +1 -1
  134. package/skills/sodax-wallet-sdk-core/integration/knowledge/recipes/setup-private-key.md +2 -2
  135. package/skills/sodax-wallet-sdk-core/integration/knowledge/recipes/sign-and-broadcast.md +1 -0
  136. package/skills/sodax-wallet-sdk-core/integration/knowledge/recipes/testing.md +1 -1
  137. package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/chain-support.md +3 -2
  138. package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/interfaces.md +7 -5
  139. package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/provider-classes.md +2 -2
  140. package/skills/sodax-wallet-sdk-core/migration-v1-to-v2/knowledge/README.md +1 -1
  141. package/skills/sodax-wallet-sdk-core/near/SKILL.md +54 -0
  142. package/skills/sodax-wallet-sdk-core/solana/SKILL.md +54 -0
  143. package/skills/sodax-wallet-sdk-core/stacks/SKILL.md +53 -0
  144. package/skills/sodax-wallet-sdk-core/stellar/SKILL.md +54 -0
  145. package/skills/sodax-wallet-sdk-core/sui/SKILL.md +53 -0
  146. package/skills/sodax-wallet-sdk-react/SKILL.md +5 -3
  147. package/skills/sodax-wallet-sdk-react/bridge-to-sdk/SKILL.md +56 -0
  148. package/skills/sodax-wallet-sdk-react/connect/SKILL.md +59 -0
  149. package/skills/sodax-wallet-sdk-react/integration/knowledge/architecture.md +3 -3
  150. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/chain-detection.md +1 -1
  151. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/connect-button.md +1 -1
  152. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/sign-message.md +10 -10
  153. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/switch-chain.md +1 -1
  154. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/api-surface.md +4 -4
  155. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/chain-support.md +4 -4
  156. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/connectors.md +1 -1
  157. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/hooks.md +5 -4
  158. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/wallet-brands.md +1 -1
  159. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/ai-rules.md +1 -1
  160. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/recipes/multi-chain-modal.md +57 -31
  161. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/recipes/ssr-setup.md +24 -19
  162. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/reference/config.md +1 -1
  163. package/skills/sodax-wallet-sdk-react/sign-message/SKILL.md +51 -0
  164. package/skills/sodax-wallet-sdk-react/switch-chain/SKILL.md +51 -0
  165. package/skills/sodax-wallet-sdk-react/wallet-modal/SKILL.md +54 -0
  166. package/skills/sodax-wallet-sdk-react/walletconnect/SKILL.md +52 -0
  167. package/skills/sodax-sdk/integration/knowledge/features/auxiliary-services.md +0 -189
  168. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/auxiliary-services.md +0 -156
@@ -7,7 +7,7 @@ Access: `sodax.staking`. Service class: `StakingService`. Feature tag for errors
7
7
  ## How it works
8
8
 
9
9
  - **SODA** (the staked asset) → **xSoda** (ERC4626 vault shares, proportional to current exchange rate).
10
- - **Unstake** has a configurable waiting period with linear penalty (max 1–100%).
10
+ - **Unstake** has a configurable waiting period with a piecewise penalty (max 1–100%): the flat `maxPenalty` applies during the minimum period, then decays linearly to zero by the full unstaking period, and is none after.
11
11
  - **Instant unstake** bypasses the waiting period but pays slippage (via `StakingRouter`).
12
12
  - **Claim** redeems SODA after the unstaking period expires.
13
13
  - **Cancel unstake** restores xSoda from a pending unstake request before claim.
@@ -34,8 +34,12 @@ sodax.staking.getStakeRatio(amount): Promise<Result<[bigint, bigint], SodaxError
34
34
  sodax.staking.getInstantUnstakeRatio(amount): Promise<Result<bigint, SodaxError>>;
35
35
  sodax.staking.getConvertedAssets(amount): Promise<Result<bigint, SodaxError>>;
36
36
 
37
+ // Reads (hub-address — caller already has the hub wallet):
38
+ sodax.staking.getStakingInfo(hubAddress: Address): Promise<Result<StakingInfo, SodaxError>>;
39
+
37
40
  // Reads (cross-chain — derive hub wallet from src chain):
38
41
  sodax.staking.getStakingInfoFromSpoke(srcAddress, srcChainKey): Promise<Result<StakingInfo, SodaxError>>;
42
+ // internally calls hubProvider.getUserHubWalletAddress(srcAddress, srcChainKey), then delegates to getStakingInfo
39
43
  sodax.staking.getUnstakingInfo(srcAddress, srcChainKey): Promise<Result<UnstakingInfo, SodaxError>>;
40
44
  // value: { userUnstakeSodaRequests: UserUnstakeInfo[]; totalUnstaking: bigint }
41
45
  sodax.staking.getUnstakingInfoWithPenalty(srcAddress, srcChainKey): Promise<Result<UnstakingInfo & { requestsWithPenalty: UnstakeRequestWithPenalty[] }, SodaxError>>;
@@ -136,11 +140,12 @@ const allowed = await sodax.staking.isAllowanceValid({
136
140
  | `create*Intent` | `CreateIntentResult<K, Raw>` |
137
141
  | `approve` | `TxReturnType<K, Raw>` |
138
142
  | `isAllowanceValid` | `boolean` |
139
- | `getStakingConfig` | `{ unstakingPeriod, maxPenalty, minPenalty, /* … */ }` |
143
+ | `getStakingConfig` | `{ unstakingPeriod, minUnstakingPeriod, maxPenalty }` |
140
144
  | `getStakeRatio` | `[xSodaAmount: bigint, previewDepositAmount: bigint]` (estimated xSoda shares + vault's `previewDeposit` preview) |
141
145
  | `getInstantUnstakeRatio` | `bigint` |
142
146
  | `getConvertedAssets` | `bigint` (SODA per xSoda) |
143
- | `getStakingInfoFromSpoke` | `StakingInfo` (xSoda balance, accrued, etc.) |
147
+ | `getStakingInfo` | `StakingInfo` (totals + user's xSoda balance + SODA value). Takes a hub address directly. |
148
+ | `getStakingInfoFromSpoke` | `StakingInfo` (same shape). Takes `(srcAddress, srcChainKey)`; resolves hub wallet internally. |
144
149
  | `getUnstakingInfo` | `UnstakingInfo` (object; carries `userUnstakeSodaRequests` array + aggregate amount) |
145
150
  | `getUnstakingInfoWithPenalty` | `UnstakingInfo & { requestsWithPenalty: UnstakeRequestWithPenalty[] }` (each entry adds `penalty`, `penaltyPercentage`, `claimableAmount`) |
146
151
 
@@ -13,14 +13,19 @@ Access: `sodax.swaps`. Service class: `SwapService`. Feature tag for errors: `'s
13
13
 
14
14
  Two execution paths:
15
15
 
16
- - **`swap`** — full flow in one call. Wraps `createIntent` + relay + `postExecution`. Returns `SwapResponse` on success.
17
- - **`createIntent` + backend submit** — break it apart for custom relay handling. `createIntent` returns `{ tx, intent, relayData }`; submit `relayData.payload` to the backend swap-tx endpoint via `BackendApiService.submitSwapTx`.
16
+ - **`swap`** — full flow in one call. Wraps `createIntent` + relay + `postExecution`. Returns `SwapResponse` on success. Opt into a **backend-driven 2-step** variant (the backend relays + post-executes server-side) with `new Sodax({ swapsOptions: { useBackendSubmitTx: true } })`; on any non-success it falls back to the client-side relay, returning the same `SwapResponse`.
17
+ - **`createIntent` + backend submit** — break it apart for custom relay handling. `createIntent` returns `{ tx, intent, relayData }`; submit `relayData.payload` to the backend swap-tx endpoint via `sodax.api.swaps.submitTx`.
18
18
 
19
19
  ## Public methods
20
20
 
21
21
  ```ts
22
22
  sodax.swaps.swap<K extends SpokeChainKey>(action: SwapActionParams<K, false>): Promise<Result<SwapResponse, SodaxError>>;
23
23
 
24
+ sodax.swaps.getQuote(payload: GetQuoteParams): Promise<Result<SolverIntentQuoteResponse, SolverErrorResponse>>;
25
+ // GetQuoteParams = SolverIntentQuoteRequest & { partnerFee?: PartnerFee } — pass the request as before;
26
+ // optionally add `partnerFee` to override the configured swap fee for this quote (matches extras.partnerFee).
27
+ // Preview the output amount before signing — useful for UX confirmations / bot previews.
28
+
24
29
  sodax.swaps.createIntent<K extends SpokeChainKey, Raw extends boolean>(
25
30
  action: SwapActionParams<K, Raw>,
26
31
  ): Promise<Result<CreateIntentResult<K, Raw>, SodaxError>>;
@@ -35,8 +40,8 @@ sodax.swaps.createLimitOrder<K, Raw>(
35
40
 
36
41
  sodax.swaps.createLimitOrderIntent<K, Raw>(/* same as createIntent shape with limit-order params */): /* same return */;
37
42
 
38
- sodax.swaps.cancelIntent<K, Raw>(/* … */): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
39
- sodax.swaps.cancelLimitOrder<K, Raw>(/* … */): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
43
+ sodax.swaps.cancelIntent<K>(/* … */): Promise<Result<TxHashPair, SodaxError>>; // not generic over Raw (only false)
44
+ sodax.swaps.cancelLimitOrder<K>(/* … */): Promise<Result<TxHashPair, SodaxError>>; // TxHashPair = { srcChainTxHash, dstChainTxHash }
40
45
 
41
46
  sodax.swaps.approve<K, Raw>(/* … */): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
42
47
  sodax.swaps.isAllowanceValid<K, Raw>(/* … */): Promise<Result<boolean, SodaxError>>;
@@ -49,48 +54,94 @@ Generic `K extends SpokeChainKey` carries the literal source chain key. `WalletP
49
54
  ```ts
50
55
  type SwapActionParams<K extends SpokeChainKey, Raw extends boolean> = {
51
56
  params: CreateIntentParams<K>;
57
+ extras?: SwapExtras<K>; // per-action overrides (optional)
52
58
  skipSimulation?: boolean;
53
59
  timeout?: number;
54
- fee?: PartnerFee;
55
60
  } & WalletProviderSlot<K, Raw>;
56
61
  ```
57
62
 
63
+ `extras` and every field on it are optional. `partnerFee` overrides the configured swap fee for this single action (the same override `getQuote` accepts, below); `srcPublicKey` is chain-key-gated — only typeable when `K` is a Stacks chain (`never` elsewhere) and only needed for raw (`raw: true`) Stacks `createIntent`; `bound` is chain-key-gated to Bitcoin and groups the Bound Exchange (Radfi) inputs — its `accessToken` is only needed for raw Bitcoin TRADING-mode `createIntent`, overriding the RadfiProvider's configured token and falling back to that instance token when omitted. (Grouping keeps future Bound inputs — trading mode, refresh token — under one slot rather than spreading a new `extras` field per item.) `LimitOrderActionParams<K, Raw>` carries the same `SwapExtras<K>`.
64
+
65
+ ```ts
66
+ type SwapExtras<K extends SpokeChainKey> = {
67
+ partnerFee?: PartnerFee; // overrides the configured swap fee for this action; falls back to config
68
+ srcPublicKey?: string; // Stacks only (raw createIntent): signer public key. Chain-key-gated — `never` on non-Stacks K.
69
+ bound?: BitcoinBoundExtras; // Bitcoin only: grouped Bound Exchange (Radfi) inputs. Chain-key-gated — `never` on non-Bitcoin K.
70
+ };
71
+
72
+ type BitcoinBoundExtras = {
73
+ accessToken?: string; // raw TRADING createIntent: Bound Exchange token; falls back to the RadfiProvider instance token.
74
+ };
75
+ ```
76
+
58
77
  `CreateIntentParams<K>`:
59
78
 
60
79
  ```ts
61
80
  type CreateIntentParams<K extends SpokeChainKey> = {
62
81
  srcChainKey: K;
63
82
  dstChainKey: SpokeChainKey;
64
- srcAddress: GetAddressType<K>;
83
+ srcAddress: string; // source-chain address (chain-specific format)
65
84
  dstAddress: string; // chain-specific format on the destination side
66
- inputToken: XToken; // must have chainKey === srcChainKey
67
- outputToken: XToken; // must have chainKey === dstChainKey
85
+ inputToken: string; // token ADDRESS on srcChainKey (the XToken's .address)
86
+ outputToken: string; // token ADDRESS on dstChainKey (the XToken's .address)
68
87
  inputAmount: bigint;
69
88
  minOutputAmount: bigint;
70
89
  deadline: bigint; // unix seconds
71
90
  allowPartialFill: boolean;
72
- solver: `0x${string}`; // solver address; '0x0…0' for default
91
+ solver?: `0x${string}`; // optional solver address; '0x0…0' for default
73
92
  data: `0x${string}`; // arbitrary calldata; '0x' for default
74
93
  };
75
94
  ```
76
95
 
77
- `CreateLimitOrderParams<K>` is `Omit<CreateIntentParams<K>, 'deadline'>` (limit orders have a different expiry mechanism).
96
+ `CreateLimitOrderParams<K>` is `Omit<CreateIntentParams<K>, 'deadline'> & { deadline?: bigint }` — it makes `deadline` optional rather than removing it; when omitted the SDK forces it to `0n` internally (limit orders use a different expiry mechanism).
78
97
 
79
98
  ## Common call shapes
80
99
 
100
+ ### Quote before signing (preview / confirmation UX)
101
+
102
+ `getQuote` is a read-only call to the solver — no wallet, no signing. Use it for trading-bot previews, UI confirmations, or to set `minOutputAmount` based on a fresh quote.
103
+
104
+ ```ts
105
+ const quote = await sodax.swaps.getQuote({
106
+ token_src: USDC_ARBITRUM.address,
107
+ token_src_blockchain_id: ChainKeys.ARBITRUM_MAINNET,
108
+ token_dst: XLM.address,
109
+ token_dst_blockchain_id: ChainKeys.STELLAR_MAINNET,
110
+ amount: 1_000_000n, // 1 USDC (6 decimals)
111
+ quote_type: 'exact_input', // currently the only supported type
112
+ });
113
+
114
+ if (!quote.ok) {
115
+ // quote.error: SolverErrorResponse — different shape from SodaxError;
116
+ // see `error.detail.code` and `error.detail.message`.
117
+ return;
118
+ }
119
+
120
+ const { quoted_amount } = quote.value; // bigint output amount in dst-token units
121
+ // Use `quoted_amount` (with a slippage buffer) as `minOutputAmount` on the swap call.
122
+ ```
123
+
124
+ `SolverIntentQuoteRequest` uses snake_case fields and **`token_src`/`token_dst` are token addresses** (strings), not full `XToken` objects. `quote_type` is currently `'exact_input'` only.
125
+
81
126
  ### Signed swap (full flow)
82
127
 
128
+ `inputToken` / `outputToken` on `CreateIntentParams` are token **addresses** (`string`), not `XToken` objects. Look the `XToken` up from config (do **not** hand-construct) and pass its `.address` — the looked-up object also gives you `decimals` for `parseUnits`:
129
+
83
130
  ```ts
131
+ const inputToken = sodax.config.findSupportedTokenBySymbol(ChainKeys.ARBITRUM_MAINNET, 'USDC');
132
+ const outputToken = sodax.config.findSupportedTokenBySymbol(ChainKeys.STELLAR_MAINNET, 'XLM');
133
+ if (!inputToken || !outputToken) throw new Error('Token missing from config — did you call sodax.config.initialize()?');
134
+
84
135
  const result = await sodax.swaps.swap({
85
136
  params: {
86
137
  srcChainKey: ChainKeys.ARBITRUM_MAINNET,
87
138
  dstChainKey: ChainKeys.STELLAR_MAINNET,
88
139
  srcAddress: '0x…',
89
140
  dstAddress: 'G…',
90
- inputToken: USDC_ARBITRUM, // XToken with chainKey === ARBITRUM_MAINNET
91
- outputToken: XLM, // XToken with chainKey === STELLAR_MAINNET
92
- inputAmount: 1_000_000n, // 1 USDC (6 decimals)
93
- minOutputAmount: 500_0000000n, // 50 XLM (7 decimals)
141
+ inputToken: inputToken.address, // token ADDRESS on srcChainKey
142
+ outputToken: outputToken.address, // token ADDRESS on dstChainKey
143
+ inputAmount: parseUnits('1', inputToken.decimals), // 1 USDC
144
+ minOutputAmount: parseUnits('50', outputToken.decimals), // 50 XLM floor
94
145
  deadline: BigInt(Math.floor(Date.now() / 1000) + 300),
95
146
  allowPartialFill: false,
96
147
  solver: '0x0000000000000000000000000000000000000000',
@@ -106,6 +157,37 @@ const { solverExecutionResponse, intent, intentDeliveryInfo } = result.value;
106
157
  // Use `intentDeliveryInfo` for spoke / hub tx hashes; `solverExecutionResponse` for solver-side outcome.
107
158
  ```
108
159
 
160
+ ### Hub as source (Sonic → spoke)
161
+
162
+ `srcChainKey` accepts `ChainKeys.SONIC_MAINNET` too — same `WalletProviderSlot<K, Raw>` shape, same `Result<T>` return. The SDK routes through the user's hub-wallet abstraction instead of a spoke deposit. The token lookup pattern is identical; only the chain key changes:
163
+
164
+ ```ts
165
+ const sodaSonic = sodax.config.findSupportedTokenBySymbol(ChainKeys.SONIC_MAINNET, 'SODA');
166
+ const sodaBase = sodax.config.findSupportedTokenBySymbol(ChainKeys.BASE_MAINNET, 'SODA');
167
+ if (!sodaSonic || !sodaBase) throw new Error('SODA missing from config');
168
+
169
+ const result = await sodax.swaps.swap({
170
+ params: {
171
+ srcChainKey: ChainKeys.SONIC_MAINNET,
172
+ dstChainKey: ChainKeys.BASE_MAINNET,
173
+ srcAddress: (await evmWp.getWalletAddress()) as `0x${string}`,
174
+ dstAddress: recipientOnBase,
175
+ inputToken: sodaSonic.address,
176
+ outputToken: sodaBase.address,
177
+ inputAmount: parseUnits('1', sodaSonic.decimals),
178
+ minOutputAmount: parseUnits('0.99', sodaBase.decimals), // tighten with getQuote() in production
179
+ deadline: BigInt(Math.floor(Date.now() / 1000) + 300),
180
+ allowPartialFill: false,
181
+ solver: '0x0000000000000000000000000000000000000000',
182
+ data: '0x',
183
+ },
184
+ raw: false,
185
+ walletProvider: evmWp,
186
+ });
187
+ ```
188
+
189
+ If both `srcChainKey` and `dstChainKey` are spoke chains that share a vault for the token, prefer [`sodax.bridge.bridge`](bridge.md) — it skips the solver and tends to be cheaper. Use `swap` when no vault pair exists or when a solver-routed price improves the outcome.
190
+
109
191
  ### Create intent only (custom relay)
110
192
 
111
193
  ```ts
@@ -118,22 +200,22 @@ if (!result.ok) return;
118
200
 
119
201
  const { tx: spokeTxHash, intent, relayData } = result.value;
120
202
  // tx is the spoke tx hash (TxReturnType<K, false>) for raw: false
121
- // relayData is { payload: string }; submit relayData.payload to your backend
203
+ // relayData is { address: Hex; payload: Hex }; submit relayData.payload to your backend
122
204
  ```
123
205
 
124
206
  ### Backend submit-tx flow
125
207
 
126
208
  ```ts
127
- const submitResult = await sodax.backendApi.submitSwapTx({
209
+ const submitResult = await sodax.api.swaps.submitTx({
128
210
  txHash: spokeTxHash as string,
129
211
  srcChainKey: ChainKeys.ARBITRUM_MAINNET,
130
212
  walletAddress: '0x…',
131
- intent: /* SwapIntentData built from CreateIntentResult.value.intent */,
213
+ intent, // IntentRequestV2 — CreateIntentResult.value.intent passes through
132
214
  relayData: relayData.payload, // string (not the object)
133
215
  });
134
216
 
135
217
  if (!submitResult.ok) {
136
- // submitResult.error.code: 'EXTERNAL_API_ERROR' with context.api: 'backend'
218
+ // submitResult.error.code: 'EXTERNAL_API_ERROR' with context.api: 'swaps'
137
219
  return;
138
220
  }
139
221
  ```
@@ -169,7 +251,7 @@ await sodax.swaps.cancelIntent({
169
251
  | `createIntent` | `CreateIntentResult<K, Raw>` = `{ tx: TxReturnType<K, Raw>, intent: Intent & FeeAmount, relayData: RelayExtraData }` |
170
252
  | `postExecution` | `SwapResponse` |
171
253
  | `createLimitOrder` / `createLimitOrderIntent` | Same as `createIntent` |
172
- | `cancelIntent` / `cancelLimitOrder` | `TxReturnType<K, Raw>` |
254
+ | `cancelIntent` / `cancelLimitOrder` | `TxHashPair` = `{ srcChainTxHash, dstChainTxHash }` (not generic over `Raw`) |
173
255
  | `approve` | `TxReturnType<K, Raw>` |
174
256
  | `isAllowanceValid` | `boolean` |
175
257
 
@@ -177,7 +259,8 @@ await sodax.swaps.cancelIntent({
177
259
 
178
260
  ```ts
179
261
  type RelayExtraData = {
180
- payload: string; // pass this string to backend submit-tx as `relayData`
262
+ address: Hex; // relay address
263
+ payload: Hex; // pass this to backend submit-tx as `relayData`
181
264
  };
182
265
  ```
183
266
 
@@ -197,11 +280,12 @@ type RelayExtraData = {
197
280
  Solver-specific context on `EXTERNAL_API_ERROR`:
198
281
 
199
282
  - `error.context.api === 'solver'`
200
- - `error.context.solverCode` — the solver's own error code (e.g. `'INSUFFICIENT_LIQUIDITY'`)
201
- - `error.context.solverDetail` — the solver's human-readable message
283
+ - `error.context.solverCode` — the solver's own error code as a **numeric** `SolverIntentErrorCode` enum value (e.g. `-5` = `NO_PRIVATE_LIQUIDITY`, `-999` = `UNKNOWN`), not a string
284
+ - `error.context.solverDetail` — the solver's full detail object `{ code, message }`
202
285
 
203
286
  ## Cross-references
204
287
 
205
288
  - v1 → v2 swap migration: [`features/swap.md`](../../../migration-v1-to-v2/knowledge/features/swap.md).
206
289
  - Error model: [`../architecture.md`](../architecture.md) § 8 and [`../reference/`](../reference/) § 3.
207
290
  - Stellar destinations require a trustline first: [`../chain-specifics.md`](../chain-specifics.md) § "Stellar trustline".
291
+ - NEAR destinations require NEP-141 storage registration first: [`../chain-specifics.md`](../chain-specifics.md) § "Receiving tokens: NEP-141 storage registration".
@@ -0,0 +1,171 @@
1
+ # Swaps API — `SwapsApiService`
2
+
3
+ Typed HTTP client for the backend **Swaps API v2** (`/swaps/*`). Reachable as `sodax.api.swaps`
4
+ (`sodax.api` is an alias for `sodax.backendApi`; `.swaps` is the `SwapsApiService` instance). One method
5
+ per endpoint (21 total). Every method returns `Promise<Result<T>>` — it **never throws** — and every
6
+ response is validated at runtime against a valibot schema, so a backend contract drift surfaces as
7
+ `{ ok: false }` rather than an untyped object.
8
+
9
+ Access: `sodax.api.swaps`. Service class: `SwapsApiService`. **Errors:** every failure (network, timeout,
10
+ non-2xx HTTP, or response-shape mismatch) returns `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with
11
+ `feature: 'backend'`, `context.api: 'swaps'`, and `context.endpoint` (the path). The underlying failure
12
+ is preserved on `error.cause` — a `SwapsApiError` from the `@sodax/swaps-api` client this service wraps
13
+ (read its `code`: `NETWORK_ERROR` | `TIMEOUT_ERROR` | `HTTP_ERROR` | `PARSE_ERROR` | `VALIDATION_ERROR`;
14
+ the same code is mirrored on `error.context.code`, and both `SwapsApiError` and the `SwapsApiErrorCode`
15
+ union are re-exported from `@sodax/sdk`). Idempotent
16
+ reads/polls (and pure-compute POSTs like `getQuote`) retry transient failures; mutating calls do not.
17
+ This differs from the feature services (`sodax.swaps`, etc.), whose errors carry their own `feature`
18
+ (`'swap'`, …) — the swaps **HTTP client** is uniformly `feature: 'backend'`.
19
+
20
+ ## Methods
21
+
22
+ ```ts
23
+ // Tokens
24
+ sodax.api.swaps.getTokens(config?): Promise<Result<GetSwapTokensResponseV2>>;
25
+ sodax.api.swaps.getTokensByChain(chainKey, config?): Promise<Result<GetSwapTokensByChainResponseV2>>;
26
+
27
+ // Quote · deadline
28
+ sodax.api.swaps.getQuote(body: QuoteRequestV2, query?: QuoteQueryV2, config?): Promise<Result<QuoteResponseV2>>;
29
+ sodax.api.swaps.getDeadline(query?: DeadlineQueryV2, config?): Promise<Result<DeadlineResponseV2>>;
30
+
31
+ // Allowance · approve · create intent — all three share the CreateIntentParamsV2 body
32
+ sodax.api.swaps.checkAllowance(body: CreateIntentParamsV2, config?): Promise<Result<AllowanceCheckResponseV2>>;
33
+ sodax.api.swaps.approve(body: CreateIntentParamsV2, config?): Promise<Result<ApproveResponseV2>>;
34
+ sodax.api.swaps.createIntent(body: CreateIntentParamsV2, config?): Promise<Result<CreateIntentResponseV2>>;
35
+
36
+ // Intent lifecycle: submit · status · cancel · hash · packet · extra-data · fill · get
37
+ sodax.api.swaps.submitIntent(body: SubmitIntentRequestV2, config?): Promise<Result<SubmitIntentResponseV2>>;
38
+ sodax.api.swaps.getStatus(body: StatusRequestV2, config?): Promise<Result<StatusResponseV2>>;
39
+ sodax.api.swaps.cancelIntent(body: CancelIntentRequestV2, config?): Promise<Result<CancelIntentResponseV2>>;
40
+ sodax.api.swaps.getIntentHash(body: IntentHashRequestV2, config?): Promise<Result<IntentHashResponseV2>>;
41
+ sodax.api.swaps.getSolvedIntentPacket(body: IntentPacketRequestV2, config?): Promise<Result<IntentPacketResponseV2>>;
42
+ sodax.api.swaps.getIntentSubmitTxExtraData(body: IntentExtraDataRequestV2, config?): Promise<Result<IntentExtraDataResponseV2>>;
43
+ sodax.api.swaps.getFilledIntent(txHash, config?): Promise<Result<IntentStateV2>>;
44
+ sodax.api.swaps.getIntent(txHash, config?): Promise<Result<GetIntentResponseV2>>;
45
+
46
+ // Limit orders · gas · fees
47
+ sodax.api.swaps.createLimitOrderIntent(body: CreateLimitOrderParamsV2, config?): Promise<Result<CreateLimitOrderResponseV2>>;
48
+ sodax.api.swaps.estimateGas(body: GasEstimateRequestV2, config?): Promise<Result<GasEstimateResponseV2>>;
49
+ sodax.api.swaps.getPartnerFee(query: FeeQueryV2, config?): Promise<Result<FeeResponseV2>>;
50
+ sodax.api.swaps.getSolverFee(query: FeeQueryV2, config?): Promise<Result<FeeResponseV2>>;
51
+
52
+ // Submit-tx state machine
53
+ sodax.api.swaps.submitTx(body: SubmitTxRequestV2, config?): Promise<Result<SubmitTxResponseV2>>;
54
+ sodax.api.swaps.getSubmitTxStatus(query: SubmitTxStatusQueryV2, config?): Promise<Result<SubmitTxStatusResponseV2>>;
55
+ ```
56
+
57
+ The optional trailing `config?: RequestOverrideConfig` (`{ baseURL?, timeout?, headers? }`) on every method
58
+ applies per-call overrides that take precedence over the service config (see "Per-call overrides" below).
59
+
60
+ ## Wire shapes — `bigint` vs decimal strings
61
+
62
+ Request bodies that carry an `intent` struct (`cancelIntent`, `getIntentHash`,
63
+ `getIntentSubmitTxExtraData`, `submitTx`) take `IntentRequestV2`, whose numeric fields
64
+ (`intentId`, `inputAmount`, `minOutputAmount`, `deadline`, `srcChain`, `dstChain`) are **`bigint`**; the
65
+ client serializes them to decimal strings on the wire. Server-returned intents (`IntentResponseV2`) come
66
+ back with those fields as decimal **`string`** (outbound JSON can't carry bigint). The `amount` /
67
+ `inputAmount` fields on the quote / create-intent request bodies are already decimal **strings**.
68
+
69
+ ## Common call shapes
70
+
71
+ ### Quote
72
+
73
+ ```ts
74
+ const quote = await sodax.api.swaps.getQuote({
75
+ tokenSrc, tokenSrcChainKey, tokenDst, tokenDstChainKey,
76
+ amount: '1000000', // smallest unit, decimal string
77
+ quoteType: 'exact_input',
78
+ });
79
+ if (!quote.ok) return;
80
+ quote.value.quotedAmount; // decimal string
81
+ // Pass query `{ includeTxData: true }` (and srcAddress/dstAddress on the body) to also get `txData`.
82
+ ```
83
+
84
+ ### Create intent
85
+
86
+ ```ts
87
+ const created = await sodax.api.swaps.createIntent({
88
+ srcChainKey, dstChainKey, inputToken, outputToken,
89
+ inputAmount: '1000000',
90
+ minOutputAmount: '990000',
91
+ deadline: '0', // "0" → no expiry (limit-order semantics)
92
+ allowPartialFill: false,
93
+ srcAddress, dstAddress,
94
+ });
95
+ if (!created.ok) return;
96
+ const { tx, intent, relayData } = created.value;
97
+ ```
98
+
99
+ ### Submit tx + poll status
100
+
101
+ ```ts
102
+ // `intent` here is the IntentRequestV2 (bigint fields) you hold from createIntent.
103
+ const submit = await sodax.api.swaps.submitTx({
104
+ txHash, srcChainKey, walletAddress, intent,
105
+ relayData: relayData.payload, // string — the payload, not the RelayExtraData object
106
+ });
107
+ if (!submit.ok) return;
108
+
109
+ // Both txHash AND srcChainKey are required by the status endpoint.
110
+ const status = await sodax.api.swaps.getSubmitTxStatus({ txHash, srcChainKey });
111
+ if (status.ok && status.value.data.status === 'solved') { /* settled */ }
112
+ // Lifecycle: 'pending' → 'relaying' → 'relayed' → 'posting_execution' → 'posted_execution' → 'solved' | 'failed'.
113
+ ```
114
+
115
+ ## Status fields — three distinct `status` values (don't conflate)
116
+
117
+ | Call | Field | Type | Values |
118
+ |---|---|---|---|
119
+ | `getStatus` | `StatusResponseV2.status` | **number** (`SwapIntentStatusCodeV2`) | `-1` NOT_FOUND · `1` NOT_STARTED_YET · `2` STARTED_NOT_FINISHED · `3` SOLVED (terminal) · `4` FAILED (terminal). `fillTxHash` is set only when `status === 3`. |
120
+ | `submitTx` | `SubmitTxResponseV2.data.status` | string | `'inserted'` (new) or `'duplicate'` (already submitted — submit-tx is idempotent on `(txHash, srcChainKey)`). |
121
+ | `getSubmitTxStatus` | `SubmitTxStatusResponseV2.data.status` | string | `'pending'` / `'relaying'` / `'relayed'` / `'posting_execution'` / `'posted_execution'` / `'solved'` / `'failed'` (`'solved'` / `'failed'` terminal). |
122
+
123
+ `getStatus` reports the **solver** intent status as a numeric code (`3` = `SOLVED`); the two submit-tx calls report **string** statuses (submission result vs relay-processing lifecycle, whose success terminal is the string `'solved'`). They are unrelated — don't treat one as the other; note the numeric solver `SOLVED` (`3`) is distinct from the submit-tx string `'solved'`.
124
+
125
+ ## Per-call overrides
126
+
127
+ Every method accepts a trailing `RequestOverrideConfig` to redirect a single call to a different host or
128
+ attach request-specific headers (auth, tracing), overriding the service config:
129
+
130
+ ```ts
131
+ await sodax.api.swaps.getTokens({ baseURL: 'https://staging.example/v1/be', headers: { 'X-Trace': 'abc' } });
132
+ ```
133
+
134
+ ## Custom endpoint for the swaps API
135
+
136
+ By default the swaps endpoints are `/swaps/*` sub-paths under the same base URL as `sodax.backendApi`.
137
+ To point the swaps API at its own host (separate from the base backend API), construct `Sodax` with the
138
+ **`CustomApiConfig`** variant of `ApiConfig` (`{ baseApiConfig?, swapsApiConfig? }`) instead of the flat
139
+ `BaseApiConfig`:
140
+
141
+ ```ts
142
+ const sodax = new Sodax({
143
+ api: {
144
+ baseApiConfig: { baseURL: 'https://api.example/v1/be' },
145
+ swapsApiConfig: { baseURL: 'https://swaps.example/v1' },
146
+ },
147
+ });
148
+ ```
149
+
150
+ The swaps slice layers over the base slice over the defaults (per field), so a cross-cutting header on
151
+ `baseApiConfig` (auth/tracing) still reaches swaps calls unless `swapsApiConfig` overrides that key. A flat
152
+ `BaseApiConfig` (the common case) is shared by both clients. See
153
+ [`backend-api.md`](backend-api.md) § "Custom backend" and [`../architecture.md`](../architecture.md).
154
+
155
+ ## Error handling
156
+
157
+ ```ts
158
+ const r = await sodax.api.swaps.getQuote(body);
159
+ if (!r.ok) {
160
+ // r.error: SodaxError<'EXTERNAL_API_ERROR'> — feature: 'backend', context.api: 'swaps',
161
+ // context.endpoint: '/swaps/quote'. The transport failure (HTTP_REQUEST_FAILED / REQUEST_TIMEOUT /
162
+ // a shape-validation issue) is on r.error.cause.
163
+ return;
164
+ }
165
+ ```
166
+
167
+ ## Cross-references
168
+
169
+ - `sodax.swaps` (the `SwapService` orchestrator that creates/executes intents end-to-end): [`swap.md`](swap.md). The swaps **API client** here is the lower-level HTTP surface; the orchestrator is the higher-level flow.
170
+ - `BackendApiService` (the sibling client for intent/orderbook/money-market reads): [`backend-api.md`](backend-api.md).
171
+ - Error model context fields: [`../reference/error-codes.md`](../reference/error-codes.md).
@@ -63,7 +63,7 @@ await sodax.config.initialize(); // load fresh config from backend; falls back
63
63
  // sodax.config, sodax.backendApi, sodax.hubProvider, sodax.spoke
64
64
  ```
65
65
 
66
- `new Sodax()` accepts an optional `DeepPartial<SodaxConfig>` for custom RPC endpoints, solver / backend URLs, etc. — see [`recipes/`](recipes/) § "Initialize Sodax". `initialize()` is idempotent.
66
+ `new Sodax()` accepts an optional `SodaxOptions` for custom RPC endpoints, solver / backend URLs, etc. — see [`recipes/`](recipes/) § "Initialize Sodax". `initialize()` is idempotent.
67
67
 
68
68
  ## 6. Reads without a wallet
69
69
 
@@ -6,6 +6,7 @@ Copy-pasteable patterns for the most common Core SDK consumer tasks. Each file i
6
6
  |---|---|
7
7
  | [`initialize-sodax.md`](initialize-sodax.md) | App startup. `new Sodax()` + `await sodax.config.initialize()`, with and without config override. |
8
8
  | [`result-and-errors.md`](result-and-errors.md) | Branching on `result.ok`, switching on `(error.feature, error.code)`, `isSodaxError` over `instanceof`, sub-Result propagation, logger integration. |
9
+ | [`logging.md`](logging.md) | Select a `SodaxLogger` (`'console'` / `'silent'` / custom sink) at construction; forward SDK diagnostics to Sentry / Pino / Datadog. |
9
10
  | [`signed-tx-flow.md`](signed-tx-flow.md) | `raw: false` + chain-narrowed `walletProvider`. Returns tx hash (or `TxHashPair` for cross-chain mutations). |
10
11
  | [`raw-tx-flow.md`](raw-tx-flow.md) | `raw: true`. Builds an unsigned chain-specific payload; you sign elsewhere. |
11
12
  | [`chain-key-narrowing.md`](chain-key-narrowing.md) | Cast-at-boundary pattern; runtime `chainType` discriminant. |
@@ -11,9 +11,9 @@ declare const evmWallet: IEvmWalletProvider;
11
11
  // class you can construct with `{ privateKey, rpcUrl }`.
12
12
 
13
13
  const sodax = new Sodax({
14
- rpcConfig: {
15
- [ChainKeys.ARBITRUM_MAINNET]: process.env.ARBITRUM_RPC_URL!,
16
- [ChainKeys.SONIC_MAINNET]: process.env.SONIC_RPC_URL!,
14
+ chains: {
15
+ [ChainKeys.ARBITRUM_MAINNET]: { rpcUrl: process.env.ARBITRUM_RPC_URL! },
16
+ [ChainKeys.SONIC_MAINNET]: { rpcUrl: process.env.SONIC_RPC_URL! },
17
17
  // …
18
18
  },
19
19
  });
@@ -3,9 +3,13 @@
3
3
  Pre-flight gas estimation for raw-tx flows. Most signed flows include gas estimation internally; you only need this when building unsigned payloads.
4
4
 
5
5
  ```ts
6
- const result = await sodax.swaps.estimateGas({
7
- params: { /* same as createIntent params */ },
8
- });
6
+ // 1. Build the unsigned tx via a raw: true flow (same params you'd pass to a signed createIntent).
7
+ const built = await sodax.swaps.createIntent({ params, raw: true });
8
+ if (!built.ok) return;
9
+ const { tx } = built.value; // TxReturnType<C, true> — the unsigned tx object
10
+
11
+ // 2. Estimate gas for that tx on its chain. estimateGas takes { tx, chainKey } — no `params` wrapper.
12
+ const result = await sodax.swaps.estimateGas({ tx, chainKey: params.srcChainKey });
9
13
 
10
14
  if (!result.ok) {
11
15
  // result.error: SodaxError<'VALIDATION_FAILED' | 'GAS_ESTIMATION_FAILED' | 'UNKNOWN'>
@@ -15,7 +19,7 @@ if (!result.ok) {
15
19
  return;
16
20
  }
17
21
 
18
- const { gasLimit, gasPrice } = result.value;
22
+ const gasEstimate = result.value; // bigint (EVM); chain-family-specific for non-EVM
19
23
  ```
20
24
 
21
25
  `estimateGas` returns chain-family-specific shapes — EVM gas params, Solana compute units, etc. See per-feature docs in [`../features/`](../features/) for specifics.
@@ -15,9 +15,11 @@ const result = sodax.config.isValidSpokeChainKey(ChainKeys.ARBITRUM_MAINNET);
15
15
  ### With config override
16
16
 
17
17
  ```ts
18
- import { Sodax, ChainKeys, type SodaxConfig, type DeepPartial } from '@sodax/sdk';
18
+ import { Sodax, ChainKeys, type SodaxOptions } from '@sodax/sdk';
19
19
 
20
- const config: DeepPartial<SodaxConfig> = {
20
+ // `SodaxOptions` = `DeepPartial<SodaxDefaultConfig>` (the data override) plus the client-side options:
21
+ // `logger`, the global `fee`, and `swapsOptions` (e.g. `{ useBackendSubmitTx: true }` — opt swap() into the backend 2-step flow).
22
+ const config: SodaxOptions = {
21
23
  // Per-chain overrides — merged with packaged defaults at the field level.
22
24
  chains: {
23
25
  [ChainKeys.SONIC_MAINNET]: { rpcUrl: process.env.SONIC_RPC_URL },
@@ -31,12 +33,41 @@ const config: DeepPartial<SodaxConfig> = {
31
33
  solver: {
32
34
  solverApiEndpoint: 'https://my-solver.example.com',
33
35
  },
36
+ // SDK log sink: 'console' (default) | 'silent' | a custom SodaxLogger. See logging.md.
37
+ logger: 'silent',
34
38
  };
35
39
 
36
40
  const sodax = new Sodax(config);
37
41
  await sodax.config.initialize();
38
42
  ```
39
43
 
44
+ ### Hub RPC failover (multiple endpoints)
45
+
46
+ The Sonic hub is read through two clients — the hub provider (wallet-address lookups, contract reads) and the Sonic spoke service (hub-chain allowance checks, gas estimation, intent creation). Each accepts an ordered `rpcUrls` list, wrapped internally in a viem `fallback()` transport that advances to the next endpoint on 5xx/52x/transport errors. The single `rpcUrl` stays the default; `rpcUrls` is opt-in and, when set and non-empty, takes precedence (first entry is primary). Optional `rpcOptions` tunes the fallback (`rank` / `retryCount` / `retryDelay`).
47
+
48
+ ```ts
49
+ import { Sodax, ChainKeys, type SodaxOptions } from '@sodax/sdk';
50
+
51
+ const SONIC_RPCS = ['https://rpc.soniclabs.com', 'https://sonic-backup.example.com'];
52
+
53
+ const config: SodaxOptions = {
54
+ // Hub provider failover.
55
+ hub: {
56
+ rpcUrls: SONIC_RPCS,
57
+ rpcOptions: { retryCount: 3 }, // optional viem fallback() tuning
58
+ },
59
+ // Sonic spoke failover — same physical chain, separate client/knob.
60
+ chains: {
61
+ [ChainKeys.SONIC_MAINNET]: { rpcUrls: SONIC_RPCS },
62
+ },
63
+ };
64
+
65
+ const sodax = new Sodax(config);
66
+ await sodax.config.initialize();
67
+ ```
68
+
69
+ > Both knobs target the same physical chain (Sonic) but back distinct clients, so set **both** for end-to-end hub resilience — `hub.rpcUrls` covers the hub provider and `chains.[SONIC_MAINNET].rpcUrls` covers the swap/intent path. Omit them to keep the single-endpoint default (fully backward compatible). The endpoint list is read once at `new Sodax(...)` time.
70
+
40
71
  ### Lazy initialization
41
72
 
42
73
  `config.initialize()` is idempotent — calling it twice is a no-op. The first call fetches; subsequent calls return cached data. Treat it as "make sure config is loaded before any feature method".
@@ -74,5 +105,6 @@ export const SUPPORTED_TOKENS_PER_CHAIN = sodaxConfig.swaps.supportedTokens;
74
105
  ## Cross-references
75
106
 
76
107
  - [`README.md`](README.md) — recipe index.
108
+ - [`logging.md`](logging.md) — the `logger` constructor option in depth (presets + custom sinks).
77
109
  - [`../architecture.md`](../architecture.md) — concepts behind these patterns.
78
110
  - [`../reference/`](../reference/) — chain keys, error codes, public API surface.