@sodax/skills 2.0.0-rc.9 → 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 (163) hide show
  1. package/.claude-plugin/plugin.json +1 -9
  2. package/AGENTS.md +119 -14
  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/money-market.md +6 -1
  28. package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +1 -1
  29. package/skills/sodax-dapp-kit/integration/knowledge/quickstart.md +2 -2
  30. package/skills/sodax-dapp-kit/integration/knowledge/recipes/README.md +1 -0
  31. package/skills/sodax-dapp-kit/integration/knowledge/recipes/backend-queries.md +23 -8
  32. package/skills/sodax-dapp-kit/integration/knowledge/recipes/bitcoin.md +8 -8
  33. package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +168 -0
  34. package/skills/sodax-dapp-kit/integration/knowledge/recipes/migration.md +1 -1
  35. package/skills/sodax-dapp-kit/integration/knowledge/recipes/setup.md +4 -4
  36. package/skills/sodax-dapp-kit/integration/knowledge/recipes/swap.md +1 -1
  37. package/skills/sodax-dapp-kit/integration/knowledge/recipes/wallet-connectivity.md +3 -0
  38. package/skills/sodax-dapp-kit/integration/knowledge/reference/glossary.md +1 -1
  39. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +67 -6
  40. package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +49 -0
  41. package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +54 -0
  42. package/skills/sodax-dapp-kit/migration/SKILL.md +64 -0
  43. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/breaking-changes/hook-signatures.md +1 -1
  44. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/breaking-changes/sdk-leakage.md +2 -2
  45. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/checklist.md +1 -1
  46. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/README.md +1 -1
  47. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/auxiliary-services.md +19 -10
  48. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/bitcoin.md +2 -2
  49. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/bridge.md +1 -1
  50. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/dex.md +1 -1
  51. package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/reference/renamed-hooks.md +3 -3
  52. package/skills/sodax-dapp-kit/money-market/SKILL.md +61 -0
  53. package/skills/sodax-dapp-kit/staking/SKILL.md +60 -0
  54. package/skills/sodax-dapp-kit/swap/SKILL.md +64 -0
  55. package/skills/sodax-sdk/SKILL.md +11 -6
  56. package/skills/sodax-sdk/backend-api/SKILL.md +21 -15
  57. package/skills/sodax-sdk/bridge/SKILL.md +4 -0
  58. package/skills/sodax-sdk/dex/SKILL.md +5 -1
  59. package/skills/sodax-sdk/integration/knowledge/README.md +1 -1
  60. package/skills/sodax-sdk/integration/knowledge/ai-rules.md +1 -1
  61. package/skills/sodax-sdk/integration/knowledge/architecture.md +24 -21
  62. package/skills/sodax-sdk/integration/knowledge/chain-specifics.md +57 -10
  63. package/skills/sodax-sdk/integration/knowledge/features/README.md +2 -1
  64. package/skills/sodax-sdk/integration/knowledge/features/backend-api.md +27 -16
  65. package/skills/sodax-sdk/integration/knowledge/features/bridge.md +15 -14
  66. package/skills/sodax-sdk/integration/knowledge/features/dex.md +7 -7
  67. package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +175 -0
  68. package/skills/sodax-sdk/integration/knowledge/features/migration.md +73 -28
  69. package/skills/sodax-sdk/integration/knowledge/features/money-market.md +20 -25
  70. package/skills/sodax-sdk/integration/knowledge/features/partner.md +27 -4
  71. package/skills/sodax-sdk/integration/knowledge/features/recovery.md +5 -4
  72. package/skills/sodax-sdk/integration/knowledge/features/staking.md +2 -2
  73. package/skills/sodax-sdk/integration/knowledge/features/swap.md +42 -24
  74. package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +171 -0
  75. package/skills/sodax-sdk/integration/knowledge/quickstart.md +1 -1
  76. package/skills/sodax-sdk/integration/knowledge/recipes/README.md +1 -0
  77. package/skills/sodax-sdk/integration/knowledge/recipes/backend-server-init.md +3 -3
  78. package/skills/sodax-sdk/integration/knowledge/recipes/gas-estimation.md +8 -4
  79. package/skills/sodax-sdk/integration/knowledge/recipes/initialize-sodax.md +34 -2
  80. package/skills/sodax-sdk/integration/knowledge/recipes/logging.md +102 -0
  81. package/skills/sodax-sdk/integration/knowledge/recipes/raw-tx-flow.md +28 -4
  82. package/skills/sodax-sdk/integration/knowledge/recipes/result-and-errors.md +1 -1
  83. package/skills/sodax-sdk/integration/knowledge/recipes/testing.md +7 -11
  84. package/skills/sodax-sdk/integration/knowledge/reference/README.md +1 -1
  85. package/skills/sodax-sdk/integration/knowledge/reference/chain-keys.md +40 -4
  86. package/skills/sodax-sdk/integration/knowledge/reference/error-codes.md +32 -9
  87. package/skills/sodax-sdk/integration/knowledge/reference/glossary.md +2 -2
  88. package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +37 -4
  89. package/skills/sodax-sdk/leverage-yield/SKILL.md +50 -0
  90. package/skills/sodax-sdk/migration/SKILL.md +5 -1
  91. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/README.md +1 -1
  92. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/ai-rules.md +1 -1
  93. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/architecture.md +2 -2
  94. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/result-and-errors.md +3 -3
  95. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/type-system.md +6 -5
  96. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/checklist.md +1 -1
  97. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/backend-api.md +23 -23
  98. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/bridge.md +5 -5
  99. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/dex.md +2 -4
  100. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/migration.md +29 -27
  101. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/money-market.md +2 -2
  102. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/partner.md +10 -5
  103. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/recovery.md +2 -2
  104. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/staking.md +2 -2
  105. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/features/swap.md +22 -18
  106. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/reference/sodax-config.md +18 -16
  107. package/skills/sodax-sdk/money-market/SKILL.md +7 -3
  108. package/skills/sodax-sdk/partner/SKILL.md +4 -0
  109. package/skills/sodax-sdk/recovery/SKILL.md +5 -1
  110. package/skills/sodax-sdk/staking/SKILL.md +4 -0
  111. package/skills/sodax-sdk/swap/SKILL.md +8 -3
  112. package/skills/sodax-sdk/swaps-api/SKILL.md +62 -0
  113. package/skills/sodax-wallet-sdk-core/SKILL.md +7 -3
  114. package/skills/sodax-wallet-sdk-core/bitcoin/SKILL.md +54 -0
  115. package/skills/sodax-wallet-sdk-core/evm/SKILL.md +54 -0
  116. package/skills/sodax-wallet-sdk-core/icon/SKILL.md +54 -0
  117. package/skills/sodax-wallet-sdk-core/injective/SKILL.md +54 -0
  118. package/skills/sodax-wallet-sdk-core/integration/knowledge/README.md +1 -1
  119. package/skills/sodax-wallet-sdk-core/integration/knowledge/ai-rules.md +2 -2
  120. package/skills/sodax-wallet-sdk-core/integration/knowledge/architecture.md +5 -5
  121. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/bitcoin.md +2 -2
  122. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +2 -2
  123. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/icon.md +5 -5
  124. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/injective.md +4 -2
  125. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/near.md +1 -1
  126. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/solana.md +2 -2
  127. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/stacks.md +2 -2
  128. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/stellar.md +2 -2
  129. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/sui.md +1 -1
  130. package/skills/sodax-wallet-sdk-core/integration/knowledge/quickstart.md +1 -1
  131. package/skills/sodax-wallet-sdk-core/integration/knowledge/recipes/setup-private-key.md +2 -2
  132. package/skills/sodax-wallet-sdk-core/integration/knowledge/recipes/sign-and-broadcast.md +1 -0
  133. package/skills/sodax-wallet-sdk-core/integration/knowledge/recipes/testing.md +1 -1
  134. package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/chain-support.md +3 -2
  135. package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/interfaces.md +7 -5
  136. package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/provider-classes.md +2 -2
  137. package/skills/sodax-wallet-sdk-core/migration-v1-to-v2/knowledge/README.md +1 -1
  138. package/skills/sodax-wallet-sdk-core/near/SKILL.md +54 -0
  139. package/skills/sodax-wallet-sdk-core/solana/SKILL.md +54 -0
  140. package/skills/sodax-wallet-sdk-core/stacks/SKILL.md +53 -0
  141. package/skills/sodax-wallet-sdk-core/stellar/SKILL.md +54 -0
  142. package/skills/sodax-wallet-sdk-core/sui/SKILL.md +53 -0
  143. package/skills/sodax-wallet-sdk-react/SKILL.md +5 -3
  144. package/skills/sodax-wallet-sdk-react/bridge-to-sdk/SKILL.md +56 -0
  145. package/skills/sodax-wallet-sdk-react/connect/SKILL.md +59 -0
  146. package/skills/sodax-wallet-sdk-react/integration/knowledge/architecture.md +3 -3
  147. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/chain-detection.md +1 -1
  148. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/connect-button.md +1 -1
  149. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/sign-message.md +10 -10
  150. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/switch-chain.md +1 -1
  151. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/api-surface.md +4 -4
  152. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/chain-support.md +4 -4
  153. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/connectors.md +1 -1
  154. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/hooks.md +5 -4
  155. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/wallet-brands.md +1 -1
  156. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/ai-rules.md +1 -1
  157. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/recipes/multi-chain-modal.md +57 -31
  158. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/recipes/ssr-setup.md +24 -19
  159. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/reference/config.md +1 -1
  160. package/skills/sodax-wallet-sdk-react/sign-message/SKILL.md +51 -0
  161. package/skills/sodax-wallet-sdk-react/switch-chain/SKILL.md +51 -0
  162. package/skills/sodax-wallet-sdk-react/wallet-modal/SKILL.md +54 -0
  163. package/skills/sodax-wallet-sdk-react/walletconnect/SKILL.md +52 -0
@@ -13,15 +13,17 @@ 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: SolverIntentQuoteRequest): Promise<Result<SolverIntentQuoteResponse, SolverErrorResponse>>;
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).
25
27
  // Preview the output amount before signing — useful for UX confirmations / bot previews.
26
28
 
27
29
  sodax.swaps.createIntent<K extends SpokeChainKey, Raw extends boolean>(
@@ -38,8 +40,8 @@ sodax.swaps.createLimitOrder<K, Raw>(
38
40
 
39
41
  sodax.swaps.createLimitOrderIntent<K, Raw>(/* same as createIntent shape with limit-order params */): /* same return */;
40
42
 
41
- sodax.swaps.cancelIntent<K, Raw>(/* … */): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
42
- 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 }
43
45
 
44
46
  sodax.swaps.approve<K, Raw>(/* … */): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
45
47
  sodax.swaps.isAllowanceValid<K, Raw>(/* … */): Promise<Result<boolean, SodaxError>>;
@@ -52,32 +54,46 @@ Generic `K extends SpokeChainKey` carries the literal source chain key. `WalletP
52
54
  ```ts
53
55
  type SwapActionParams<K extends SpokeChainKey, Raw extends boolean> = {
54
56
  params: CreateIntentParams<K>;
57
+ extras?: SwapExtras<K>; // per-action overrides (optional)
55
58
  skipSimulation?: boolean;
56
59
  timeout?: number;
57
- fee?: PartnerFee;
58
60
  } & WalletProviderSlot<K, Raw>;
59
61
  ```
60
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
+
61
77
  `CreateIntentParams<K>`:
62
78
 
63
79
  ```ts
64
80
  type CreateIntentParams<K extends SpokeChainKey> = {
65
81
  srcChainKey: K;
66
82
  dstChainKey: SpokeChainKey;
67
- srcAddress: GetAddressType<K>;
83
+ srcAddress: string; // source-chain address (chain-specific format)
68
84
  dstAddress: string; // chain-specific format on the destination side
69
- inputToken: XToken; // must have chainKey === srcChainKey
70
- 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)
71
87
  inputAmount: bigint;
72
88
  minOutputAmount: bigint;
73
89
  deadline: bigint; // unix seconds
74
90
  allowPartialFill: boolean;
75
- solver: `0x${string}`; // solver address; '0x0…0' for default
91
+ solver?: `0x${string}`; // optional solver address; '0x0…0' for default
76
92
  data: `0x${string}`; // arbitrary calldata; '0x' for default
77
93
  };
78
94
  ```
79
95
 
80
- `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).
81
97
 
82
98
  ## Common call shapes
83
99
 
@@ -109,7 +125,7 @@ const { quoted_amount } = quote.value; // bigint output amount in dst-token un
109
125
 
110
126
  ### Signed swap (full flow)
111
127
 
112
- `inputToken` / `outputToken` are full `XToken` objects (with `chainKey`, `address`, `decimals`, `symbol`). Look them up from config — do **not** hand-construct:
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`:
113
129
 
114
130
  ```ts
115
131
  const inputToken = sodax.config.findSupportedTokenBySymbol(ChainKeys.ARBITRUM_MAINNET, 'USDC');
@@ -122,8 +138,8 @@ const result = await sodax.swaps.swap({
122
138
  dstChainKey: ChainKeys.STELLAR_MAINNET,
123
139
  srcAddress: '0x…',
124
140
  dstAddress: 'G…',
125
- inputToken, // XToken; chainKey === srcChainKey
126
- outputToken, // XToken; chainKey === dstChainKey
141
+ inputToken: inputToken.address, // token ADDRESS on srcChainKey
142
+ outputToken: outputToken.address, // token ADDRESS on dstChainKey
127
143
  inputAmount: parseUnits('1', inputToken.decimals), // 1 USDC
128
144
  minOutputAmount: parseUnits('50', outputToken.decimals), // 50 XLM floor
129
145
  deadline: BigInt(Math.floor(Date.now() / 1000) + 300),
@@ -156,8 +172,8 @@ const result = await sodax.swaps.swap({
156
172
  dstChainKey: ChainKeys.BASE_MAINNET,
157
173
  srcAddress: (await evmWp.getWalletAddress()) as `0x${string}`,
158
174
  dstAddress: recipientOnBase,
159
- inputToken: sodaSonic,
160
- outputToken: sodaBase,
175
+ inputToken: sodaSonic.address,
176
+ outputToken: sodaBase.address,
161
177
  inputAmount: parseUnits('1', sodaSonic.decimals),
162
178
  minOutputAmount: parseUnits('0.99', sodaBase.decimals), // tighten with getQuote() in production
163
179
  deadline: BigInt(Math.floor(Date.now() / 1000) + 300),
@@ -184,22 +200,22 @@ if (!result.ok) return;
184
200
 
185
201
  const { tx: spokeTxHash, intent, relayData } = result.value;
186
202
  // tx is the spoke tx hash (TxReturnType<K, false>) for raw: false
187
- // relayData is { payload: string }; submit relayData.payload to your backend
203
+ // relayData is { address: Hex; payload: Hex }; submit relayData.payload to your backend
188
204
  ```
189
205
 
190
206
  ### Backend submit-tx flow
191
207
 
192
208
  ```ts
193
- const submitResult = await sodax.backendApi.submitSwapTx({
209
+ const submitResult = await sodax.api.swaps.submitTx({
194
210
  txHash: spokeTxHash as string,
195
211
  srcChainKey: ChainKeys.ARBITRUM_MAINNET,
196
212
  walletAddress: '0x…',
197
- intent: /* SwapIntentData built from CreateIntentResult.value.intent */,
213
+ intent, // IntentRequestV2 — CreateIntentResult.value.intent passes through
198
214
  relayData: relayData.payload, // string (not the object)
199
215
  });
200
216
 
201
217
  if (!submitResult.ok) {
202
- // submitResult.error.code: 'EXTERNAL_API_ERROR' with context.api: 'backend'
218
+ // submitResult.error.code: 'EXTERNAL_API_ERROR' with context.api: 'swaps'
203
219
  return;
204
220
  }
205
221
  ```
@@ -235,7 +251,7 @@ await sodax.swaps.cancelIntent({
235
251
  | `createIntent` | `CreateIntentResult<K, Raw>` = `{ tx: TxReturnType<K, Raw>, intent: Intent & FeeAmount, relayData: RelayExtraData }` |
236
252
  | `postExecution` | `SwapResponse` |
237
253
  | `createLimitOrder` / `createLimitOrderIntent` | Same as `createIntent` |
238
- | `cancelIntent` / `cancelLimitOrder` | `TxReturnType<K, Raw>` |
254
+ | `cancelIntent` / `cancelLimitOrder` | `TxHashPair` = `{ srcChainTxHash, dstChainTxHash }` (not generic over `Raw`) |
239
255
  | `approve` | `TxReturnType<K, Raw>` |
240
256
  | `isAllowanceValid` | `boolean` |
241
257
 
@@ -243,7 +259,8 @@ await sodax.swaps.cancelIntent({
243
259
 
244
260
  ```ts
245
261
  type RelayExtraData = {
246
- 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`
247
264
  };
248
265
  ```
249
266
 
@@ -263,11 +280,12 @@ type RelayExtraData = {
263
280
  Solver-specific context on `EXTERNAL_API_ERROR`:
264
281
 
265
282
  - `error.context.api === 'solver'`
266
- - `error.context.solverCode` — the solver's own error code (e.g. `'INSUFFICIENT_LIQUIDITY'`)
267
- - `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 }`
268
285
 
269
286
  ## Cross-references
270
287
 
271
288
  - v1 → v2 swap migration: [`features/swap.md`](../../../migration-v1-to-v2/knowledge/features/swap.md).
272
289
  - Error model: [`../architecture.md`](../architecture.md) § 8 and [`../reference/`](../reference/) § 3.
273
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.
@@ -0,0 +1,102 @@
1
+ # Logging
2
+
3
+ The SDK routes all of its internal diagnostics through a single `SodaxLogger` instead of calling
4
+ `console.*` directly. Pick a preset or forward to a structured sink (Sentry, Pino, Datadog, …) without
5
+ patching globals.
6
+
7
+ ## Select a logger at construction
8
+
9
+ `logger` is a `Sodax` constructor option — a field on `SodaxOptions` (the constructor's parameter
10
+ type), kept off the `SodaxConfig` data contract because it is a client-side sink, not backend-fetched
11
+ config. It accepts a preset name or a custom implementation:
12
+
13
+ ```ts
14
+ import { Sodax } from '@sodax/sdk';
15
+
16
+ new Sodax(); // default — same as { logger: 'console' }
17
+ new Sodax({ logger: 'console' }); // mirror console.* output
18
+ new Sodax({ logger: 'silent' }); // drop all SDK logs
19
+ ```
20
+
21
+ The logger is resolved **once** at construction and held on `ConfigService` outside the swappable
22
+ dynamic config (read it back as `sodax.config.logger`). `await sodax.config.initialize()` fetches fresh
23
+ chain config from the backend but **never** replaces the logger — the backend cannot set or overwrite
24
+ it.
25
+
26
+ > Combine with the other constructor options freely — pass `logger` alongside `chains` / `api` /
27
+ > `solver` overrides in the same object. The constructor splits `logger` off the data override before
28
+ > merging, so it never lands in `sodax.instanceConfig`. See [`initialize-sodax.md`](initialize-sodax.md).
29
+
30
+ ## Custom sink
31
+
32
+ Implement the `SodaxLogger` interface and pass the instance:
33
+
34
+ ```ts
35
+ import { Sodax, type SodaxLogger } from '@sodax/sdk';
36
+
37
+ const sentryLogger: SodaxLogger = {
38
+ debug: (message, data) => Sentry.addBreadcrumb({ level: 'debug', message, data }),
39
+ info: (message, data) => Sentry.addBreadcrumb({ level: 'info', message, data }),
40
+ warn: (message, data) => Sentry.captureMessage(message, { level: 'warning', extra: data }),
41
+ error: (message, error, data) =>
42
+ error !== undefined
43
+ ? Sentry.captureException(error, { extra: { message, ...data } })
44
+ : Sentry.captureMessage(message, { level: 'error', extra: data }),
45
+ };
46
+
47
+ const sodax = new Sodax({ logger: sentryLogger });
48
+ ```
49
+
50
+ ## Interface
51
+
52
+ ```ts
53
+ import type { SodaxLogger, SodaxLoggerOption } from '@sodax/sdk';
54
+
55
+ // SodaxLogger:
56
+ // debug(message: string, data?: Record<string, unknown>): void;
57
+ // info(message: string, data?: Record<string, unknown>): void;
58
+ // warn(message: string, data?: Record<string, unknown>): void;
59
+ // error(message: string, error?: unknown, data?: Record<string, unknown>): void;
60
+ //
61
+ // SodaxLoggerOption = SodaxLogger | 'console' | 'silent';
62
+ ```
63
+
64
+ `error()` takes the thrown value as a separate second argument (before structured `data`) so adapters
65
+ can attach it as the exception — `warn` / `info` / `debug` take only `(message, data?)`. SDK errors are
66
+ `SodaxError` instances; their `toJSON()` is the canonical serialization surface (`JSON.stringify(error)`
67
+ invokes it automatically). For routing a failed `Result<T>`'s `error` into a sink, see the **Logging**
68
+ section of [`result-and-errors.md`](result-and-errors.md).
69
+
70
+ ## Built-in loggers and resolver
71
+
72
+ `consoleLogger`, `silentLogger`, and `resolveLogger(option)` are exported from `@sodax/sdk` for
73
+ composition — e.g. wrapping the console logger to add a prefix, or resolving a preset name yourself:
74
+
75
+ ```ts
76
+ import { consoleLogger, resolveLogger, type SodaxLogger } from '@sodax/sdk';
77
+
78
+ // Wrap the default to add a prefix
79
+ const prefixed: SodaxLogger = {
80
+ debug: (m, d) => consoleLogger.debug(`[sodax] ${m}`, d),
81
+ info: (m, d) => consoleLogger.info(`[sodax] ${m}`, d),
82
+ warn: (m, d) => consoleLogger.warn(`[sodax] ${m}`, d),
83
+ error: (m, e, d) => consoleLogger.error(`[sodax] ${m}`, e, d),
84
+ };
85
+
86
+ // Resolve a preset name to a concrete logger
87
+ const resolved = resolveLogger('silent'); // → silentLogger
88
+ ```
89
+
90
+ ## Coverage
91
+
92
+ All instance feature services (swap, bridge, money market, DEX, staking, partner, recovery, the spoke
93
+ services), `BackendApiService`, and the solver API client route through the configured logger. A small
94
+ number of pure utility / static-helper functions still call `console.*` directly because they have no
95
+ access to the instance logger.
96
+
97
+ ## Cross-references
98
+
99
+ - [`README.md`](README.md) — recipe index.
100
+ - [`initialize-sodax.md`](initialize-sodax.md) — the constructor options object `logger` lives in.
101
+ - [`result-and-errors.md`](result-and-errors.md) — routing a failed `Result<T>` into a logging sink.
102
+ - [`../reference/public-api.md`](../reference/public-api.md) — exported logger symbols.
@@ -18,6 +18,31 @@ const { tx, intent, relayData } = result.value;
18
18
  // - …
19
19
  ```
20
20
 
21
+ ### Chain-specific raw inputs (`extras`)
22
+
23
+ Some chains need a per-action input on the **raw** path, supplied via the chain-key-gated `extras` slot:
24
+
25
+ - **Stacks** (`raw: true`): `extras.srcPublicKey` is **required** — the unsigned source tx is built from the signer public key (a `SP…` address can't yield it). Omitting it fails fast with a `VALIDATION_FAILED` `SodaxError` before any network call.
26
+ - **Bitcoin** TRADING mode (`raw: true`): `extras.bound.accessToken` carries a Bound Exchange token so the PSBT build authenticates (`bound` is the Bitcoin-gated slot that groups Bound/Radfi inputs). It falls back to the RadfiProvider instance token (`new Sodax({ ... })` with `radfi.accessToken`, or `radfi.setRadfiAccessToken(token)`) when omitted; with no token anywhere the call fails with a legible `RadfiApiError`.
27
+
28
+ ```ts
29
+ // Stacks raw intent — srcPublicKey is mandatory:
30
+ await sodax.swaps.createIntent({
31
+ params: { ...params, srcChainKey: ChainKeys.STACKS_MAINNET },
32
+ extras: { srcPublicKey },
33
+ raw: true,
34
+ });
35
+
36
+ // Bitcoin raw intent (TRADING) — bound.accessToken (or a seeded radfi token):
37
+ await sodax.swaps.createIntent({
38
+ params: { ...params, srcChainKey: ChainKeys.BITCOIN_MAINNET },
39
+ extras: { bound: { accessToken } },
40
+ raw: true,
41
+ });
42
+ ```
43
+
44
+ > **Note (Bitcoin):** even on the `raw: true` path, a Bitcoin TRADING intent makes a live Bound Exchange call to resolve the trading-wallet address (`getEffectiveWalletAddress`) before the PSBT is built. The unsigned PSBT is returned for you to sign offline, but the address lookup is **not** offline — Bound must be reachable, and a valid `accessToken` (per-action or seeded) is required for it.
45
+
21
46
  Submit the raw tx via your own signing infrastructure. Once you have the spoke tx hash, you'll typically need to manually call the relay to complete the cross-chain flow:
22
47
 
23
48
  ```ts
@@ -31,10 +56,9 @@ const spokeTxHash = await mySigningInfra.signAndBroadcast(tx);
31
56
  // the relay payload returned by `createIntent`.
32
57
  const relayResult = await relayTxAndWaitPacket({
33
58
  relayerApiEndpoint,
34
- srcChainKey: params.srcChainKey,
35
- dstChainKey: params.dstChainKey,
36
- txHash: spokeTxHash,
37
- payload: relayData.payload,
59
+ chainKey: params.srcChainKey,
60
+ srcTxHash: spokeTxHash,
61
+ data: relayData, // the whole RelayExtraData ({ address, payload }), not just .payload
38
62
  timeout: 60_000,
39
63
  });
40
64
  ```
@@ -31,7 +31,7 @@ const { tx, intent, relayData } = result.value;
31
31
  When you know the method, the narrow code union from its declaration enables an exhaustive switch:
32
32
 
33
33
  ```ts
34
- type CreateSupplyIntentErrorCode = 'VALIDATION_FAILED' | 'INTENT_CREATION_FAILED' | 'UNKNOWN';
34
+ type CreateSupplyIntentErrorCode = 'USER_REJECTED' | 'VALIDATION_FAILED' | 'INTENT_CREATION_FAILED' | 'UNKNOWN';
35
35
 
36
36
  const result = await sodax.moneyMarket.createSupplyIntent({ params, raw: true });
37
37
  if (!result.ok) {