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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +31 -0
  4. package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +24 -0
  5. package/skills/sodax-dapp-kit/integration/knowledge/features/bridge.md +5 -0
  6. package/skills/sodax-dapp-kit/integration/knowledge/features/dex.md +5 -0
  7. package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +5 -0
  8. package/skills/sodax-dapp-kit/integration/knowledge/features/migration.md +5 -0
  9. package/skills/sodax-dapp-kit/integration/knowledge/features/money-market.md +5 -0
  10. package/skills/sodax-dapp-kit/integration/knowledge/features/staking.md +5 -0
  11. package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +5 -0
  12. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +19 -1
  13. package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +18 -0
  14. package/skills/sodax-sdk/SKILL.md +2 -1
  15. package/skills/sodax-sdk/bridge-api/SKILL.md +64 -0
  16. package/skills/sodax-sdk/integration/knowledge/architecture.md +19 -0
  17. package/skills/sodax-sdk/integration/knowledge/chain-specifics.md +18 -0
  18. package/skills/sodax-sdk/integration/knowledge/features/README.md +2 -0
  19. package/skills/sodax-sdk/integration/knowledge/features/backend-api.md +5 -0
  20. package/skills/sodax-sdk/integration/knowledge/features/bridge-api.md +141 -0
  21. package/skills/sodax-sdk/integration/knowledge/features/bridge.md +56 -4
  22. package/skills/sodax-sdk/integration/knowledge/features/dex.md +6 -0
  23. package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +6 -0
  24. package/skills/sodax-sdk/integration/knowledge/features/migration.md +6 -0
  25. package/skills/sodax-sdk/integration/knowledge/features/money-market.md +6 -0
  26. package/skills/sodax-sdk/integration/knowledge/features/sponsoring.md +2 -0
  27. package/skills/sodax-sdk/integration/knowledge/features/staking.md +6 -0
  28. package/skills/sodax-sdk/integration/knowledge/features/swap.md +6 -0
  29. package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +23 -0
  30. package/skills/sodax-sdk/sponsoring/SKILL.md +2 -2
package/README.md CHANGED
@@ -49,4 +49,4 @@ LLM training data drifts: snippets from chat often use stale method names, resha
49
49
 
50
50
  ## Feedback
51
51
 
52
- If your agent generates wrong code despite reading the docs, that's a doc bug — please open an issue on the [Sodax SDKs repo](https://github.com/icon-project/sodax-sdks/issues) with the prompt and the incorrect output. The per-skill `knowledge/` subtrees are structurally CI-guarded (frontmatter, link resolution); prose claims benefit from real-world feedback.
52
+ If your agent generates wrong code despite reading the docs, that's a doc bug — please open an issue on the [SODAX SDKs repo](https://github.com/icon-project/sodax-sdks/issues) with the prompt and the incorrect output. The per-skill `knowledge/` subtrees are structurally CI-guarded (frontmatter, link resolution); prose claims benefit from real-world feedback.
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "2.1.0-rc.1",
7
+ "version": "2.1.0-rc.3",
8
8
  "license": "MIT",
9
9
  "description": "AI-agent skills and knowledge for consumers of @sodax/* SDKs (Claude Code, Codex, Cursor, …)",
10
10
  "keywords": [
@@ -198,6 +198,37 @@ After translating, the public hook signature is `SafeUseMutationResult<T, Error,
198
198
 
199
199
  The dual API means consumers never have to choose between React Query's error model and `Result<T>` ergonomics — both are exposed by the same hook.
200
200
 
201
+ ## Approve hooks can prompt the wallet twice
202
+
203
+ Every `use*Approve` hook is unchanged and still resolves to a single transaction hash. But a few
204
+ ERC-20s of the 2017 TetherToken lineage — Ethereum USDT is the only one in the SODAX token list today
205
+ — reject an allowance change from one non-zero value to another. When the connected wallet already
206
+ holds a stale allowance on such a token, the SDK sends `approve(0)` first, waits for it to be mined,
207
+ and only then sends the real approval. The user therefore signs **twice**, and the hash the hook
208
+ resolves with is the **last** transaction's.
209
+
210
+ Nothing about the hook contract changes and there is no flag to set. What matters for UI:
211
+
212
+ - An `isPending` that renders a single "Approving…" now spans two wallet prompts. Say so in the copy,
213
+ or the second prompt reads as a bug.
214
+ - Anything estimating gas or counting transactions from "one approve = one transaction" is wrong on
215
+ that branch.
216
+ - If the second signature is rejected after the reset landed, the allowance is now zero, so the next
217
+ attempt is a single transaction — retrying is always safe.
218
+
219
+ On the unsigned (swaps-API) path, prefer **`useSwapsApiApproveAndBroadcast`**: it asks the API for
220
+ the transactions, then signs, broadcasts, and waits for each, resolving with
221
+ `{ approveTxHash, resetTxHash? }` only once the final approval has landed. A transaction that mines
222
+ but reverts rejects the mutation naming that step, so the approve is never sent over a reset that
223
+ did not take. It also invalidates `['swapsApi','allowance']` itself, because confirmation now
224
+ happens inside the hook.
225
+
226
+ `useSwapsApiApprove` still exists and returns the API's `{ tx, resetTx? }` verbatim — use it only
227
+ when you need to own signing. If you do, broadcast `resetTx` **first and wait for it to succeed**;
228
+ the approve is not a valid state transition until the reset has landed, so sending both together
229
+ spends the user's gas on a certain revert. Waiting is not enough on its own — check the receipt's
230
+ status, because a mined-and-reverted reset leaves the allowance exactly where it was.
231
+
201
232
  ## queryKey / mutationKey conventions (mandatory)
202
233
 
203
234
  Every `queryKey` and `mutationKey` follows the same structural rule. Enforced by `_mutationContract.test.ts` for mutation keys; reviewer-enforced for query keys.
@@ -94,6 +94,30 @@ const { data: status } = useSwapsApiSubmitTxStatus({ params: { txHash, srcChainK
94
94
 
95
95
  > The full `useSwapsApi*` hook list (with polling + types) is in [hooks-index.md](../reference/hooks-index.md); key shapes in [querykey-conventions.md](../reference/querykey-conventions.md). For non-React callers, `sodax.api.swaps` is documented in the `sodax-sdk` skill (integration mode).
96
96
 
97
+ ### Bridge API (`sodax.api.bridge`)
98
+
99
+ Typed React Query wrappers over the backend **Bridge API v2** — `useBridgeApi*` hooks over `sodax.api.bridge.*` (tokens, allowance, approve, create-bridge-intent, submit-tx + status, plus the fee / bridgeable-amount / bridgeable discovery quotes). They are the HTTP-API parallel of the on-chain `bridge/` hooks (`useBridge`/`useBridgeAllowance`/…, which drive `sodax.bridge`). Mirrors the swaps family minus the solver/intent surface; reads take `{ params, queryOptions }`, the three actions (`approve`, `createBridgeIntent`, `submitTx`) are mutations taking `{ mutationOptions }`.
100
+
101
+ ```ts
102
+ // @ai-snippets-skip
103
+ useBridgeApiTokens({ params, queryOptions }); // query → sodax.api.bridge.getTokens
104
+ useBridgeApiCreateBridgeIntent({ mutationOptions }); // mutation → sodax.api.bridge.createBridgeIntent
105
+ useBridgeApiSubmitTxStatus({ params, queryOptions }); // query → sodax.api.bridge.getSubmitTxStatus
106
+ ```
107
+
108
+ Two deltas vs the swaps hooks: the allowance/approve/create body is the **wire DTO** `CreateBridgeIntentParamsV2` (`inputToken`/`inputAmount`/`dstAddress`, not the SDK-domain names), and `useBridgeApiSubmitTx`'s `request` is a `BridgeSubmitTxRequestV2` whose `relayData` is the **FULL `{ address, payload }` object** (no `intent` field):
109
+
110
+ ```ts
111
+ // @ai-snippets-skip
112
+ const { mutateAsync: submitBridgeTx } = useBridgeApiSubmitTx();
113
+ // request: BridgeSubmitTxRequestV2 — { txHash, srcChainKey, walletAddress, relayData } (full envelope)
114
+ await submitBridgeTx({ request, apiConfig: { baseURL: 'https://...' } });
115
+ ```
116
+
117
+ `useBridgeApiSubmitTxStatus` polls (1s) and returns `BridgeSubmitTxStatusResponseV2 | undefined`, running only when **both** `txHash` and `srcChainKey` are supplied; terminal states are `executed` / `failed` (no `posting_execution`). The fee / bridgeable-amount / bridgeable quotes are computable client-side (config + vault math) — prefer the on-chain `useGetBridgeableAmount` / `sodax.bridge.*` for a no-round-trip read; `useBridgeApiFee` / `useBridgeApiBridgeableAmount` / `useBridgeApiIsBridgeable` mirror the backend endpoints for HTTP parity.
118
+
119
+ > Full list in [hooks-index.md](../reference/hooks-index.md); key shapes in [querykey-conventions.md](../reference/querykey-conventions.md). For non-React callers, `sodax.api.bridge` is documented in the `sodax-sdk` skill (integration mode).
120
+
97
121
  ## Shared utilities
98
122
 
99
123
  Cross-cutting hooks used by other features.
@@ -19,6 +19,11 @@ useGetBridgeableAmount({ params: { from: XToken, to: XToken }, queryOptions });
19
19
  useGetBridgeableTokens({ params: { from: SpokeChainKey, to: SpokeChainKey, token: string }, queryOptions });
20
20
  ```
21
21
 
22
+ `use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
23
+ transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
24
+ the user signs twice and the hash is the **last** one's. An `isPending`-driven "Approving…" should say
25
+ so. See "Approve hooks can prompt the wallet twice" in [`architecture.md`](../architecture.md).
26
+
22
27
  ## Mutation params
23
28
 
24
29
  ```ts
@@ -35,6 +35,11 @@ useCreateSupplyLiquidityParams({ poolData, poolKey, minPrice, maxPrice, liquidit
35
35
  useCreateDecreaseLiquidityParams({ /* see source for fields */ });
36
36
  ```
37
37
 
38
+ `use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
39
+ transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
40
+ the user signs twice and the hash is the **last** one's. An `isPending`-driven "Approving…" should say
41
+ so. See "Approve hooks can prompt the wallet twice" in [`architecture.md`](../architecture.md).
42
+
38
43
  ## SDK param types (passed via `mutate({ params, walletProvider })`)
39
44
 
40
45
  Each dex mutation hook's TVars is `{ params: <SDKParamsType>, walletProvider, timeout? }`. The SDK param types below are what goes INSIDE `params` — they are not the TVars themselves.
@@ -22,6 +22,11 @@ useLeverageYieldShareBalances({ params, queryOptions }); // per-chain share bala
22
22
 
23
23
  `deposit` / `withdraw` are **builders** — they assemble a `LeverageYieldSwapPayload`, they do NOT broadcast. Spread the built payload into `useLeverageYieldVaultSwap`'s `mutate`, adding the `walletProvider`. There is no dedicated leverage-yield approve hook: the swap-style deposit approves the spoke-side asset manager, so reuse `useSwapApprove` / `useSwapAllowance` (see Approval pattern).
24
24
 
25
+ `use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
26
+ transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
27
+ the user signs twice and the hash is the **last** one's. An `isPending`-driven "Approving…" should say
28
+ so. See "Approve hooks can prompt the wallet twice" in [`architecture.md`](../architecture.md).
29
+
25
30
  ## Mutation TVars
26
31
 
27
32
  ```ts
@@ -20,6 +20,11 @@ useMigrationApprove({ mutationOptions });
20
20
  useMigrationAllowance({ params: { params: <inner>, action: 'migrate' | 'revert' }, queryOptions });
21
21
  ```
22
22
 
23
+ `use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
24
+ transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
25
+ the user signs twice and the hash is the **last** one's. An `isPending`-driven "Approving…" should say
26
+ so. See "Approve hooks can prompt the wallet twice" in [`architecture.md`](../architecture.md).
27
+
23
28
  ## Mutation params
24
29
 
25
30
  ```ts
@@ -66,6 +66,11 @@ type UseATokensBalancesParams = ReadHookParams<Map<Address, bigint>, {
66
66
 
67
67
  > **Bitcoin `userAddress`**: always pass the **personal** address (the user's wallet address), not the Bound Exchange trading address. The read hooks (`useATokensBalances`, `useUserReservesData`, `useUserFormattedSummary`, `useGetUserHubWalletAddress`) automatically resolve to the trading-wallet-derived hub wallet when a Bound Exchange session is active — this is a local lookup with no network call and no throw on an unauthenticated session. See [`features/bitcoin.md`](bitcoin.md) for Bound Exchange session setup.
68
68
 
69
+ `use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
70
+ transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
71
+ the user signs twice and the hash is the **last** one's. An `isPending`-driven "Approving…" should say
72
+ so. See "Approve hooks can prompt the wallet twice" in [`architecture.md`](../architecture.md).
73
+
69
74
  ## Mutation params
70
75
 
71
76
  All four user mutations share the same TVars shape (only the `action` literal differs):
@@ -35,6 +35,11 @@ useInstantUnstakeRatio({ params, queryOptions });
35
35
  useConvertedAssets({ params, queryOptions });
36
36
  ```
37
37
 
38
+ `use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
39
+ transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
40
+ the user signs twice and the hash is the **last** one's. An `isPending`-driven "Approving…" should say
41
+ so. See "Approve hooks can prompt the wallet twice" in [`architecture.md`](../architecture.md).
42
+
38
43
  ## Mutation TVars
39
44
 
40
45
  ```ts
@@ -24,6 +24,11 @@ useCancelLimitOrder({ mutationOptions }); // TVars are FLAT: { srcChai
24
24
 
25
25
  (In actual code, you import each hook directly: `import { useSwap, useSwapAllowance, ... } from '@sodax/dapp-kit'`.)
26
26
 
27
+ `use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
28
+ transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
29
+ the user signs twice and the hash is the **last** one's. An `isPending`-driven "Approving…" should say
30
+ so. See "Approve hooks can prompt the wallet twice" in [`architecture.md`](../architecture.md).
31
+
27
32
  ## Mutation params
28
33
 
29
34
  ```ts
@@ -197,13 +197,31 @@ Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`),
197
197
 
198
198
  | Hook | Type |
199
199
  |---|---|
200
- | `useSwapsApiApprove` | Mutation; builds unsigned approval tx |
200
+ | `useSwapsApiApprove` | Mutation; builds unsigned approval tx(s) — `{ tx, resetTx? }`, caller signs |
201
+ | `useSwapsApiApproveAndBroadcast` | Mutation; builds **and** signs/broadcasts/waits — preferred; `{ approveTxHash, resetTxHash? }` |
201
202
  | `useSwapsApiCreateIntent` | Mutation; builds `{ tx, intent, relayData }` |
202
203
  | `useSwapsApiSubmitIntent` | Mutation; submits broadcast intent to the relay |
203
204
  | `useSwapsApiCancelIntent` | Mutation; builds unsigned cancel tx |
204
205
  | `useSwapsApiCreateLimitOrder` | Mutation; builds limit-order intent tx |
205
206
  | `useSwapsApiSubmitTx` | Mutation; `request: SubmitTxRequestV2` |
206
207
 
208
+ ## Bridge API (`sodax.api.bridge`)
209
+
210
+ Typed React Query wrappers over the backend Bridge API v2 (`sodax.api.bridge.*`). Distinct from the on-chain `bridge/` hooks (`useBridge`/`useBridgeAllowance`/…), which drive `sodax.bridge` (the `BridgeService`). Smaller than the swaps family (no intent/solver surface). The fee / bridgeable-amount / bridgeable quotes are computable client-side (prefer the on-chain `useGetBridgeableAmount` / `sodax.bridge.*` — no round-trip), but are also mirrored here as HTTP hooks for parity.
211
+
212
+ | Hook | Type / Polling |
213
+ |---|---|
214
+ | `useBridgeApiTokens` | Query; all supported bridge tokens by chain |
215
+ | `useBridgeApiTokensByChain` | Query; supported bridge tokens for one `chainKey` |
216
+ | `useBridgeApiAllowance` | Query; `{ valid }` allowance check (wire-named body) |
217
+ | `useBridgeApiFee` | Query; `{ fee }` partner fee for an amount (per-request `partnerFee` override or configured default) |
218
+ | `useBridgeApiBridgeableAmount` | Query; `{ limit }` deposit capacity / withdrawal liquidity for a pair |
219
+ | `useBridgeApiIsBridgeable` | Query; `{ bridgeable }` whether a (from, to) pair is bridgeable |
220
+ | `useBridgeApiSubmitTxStatus` | Query (1s); requires `txHash` + `srcChainKey`; polls until `executed` / `failed` |
221
+ | `useBridgeApiApprove` | Mutation; builds unsigned approval tx |
222
+ | `useBridgeApiCreateBridgeIntent` | Mutation; builds `{ tx, relayData }` (no intent) |
223
+ | `useBridgeApiSubmitTx` | Mutation; `request: BridgeSubmitTxRequestV2` (FULL relayData envelope) |
224
+
207
225
  ## Partner
208
226
 
209
227
  | Hook | Type | Purpose |
@@ -176,12 +176,30 @@ Typed wrappers over `sodax.api.swaps.*` (one per Swaps API v2 endpoint), all key
176
176
  | `['swapsApi', 'solverFee', amount]` | `useSwapsApiSolverFee` |
177
177
  | `['swapsApi', 'submitTx', 'status', txHash, srcChainKey]` | `useSwapsApiSubmitTxStatus` — both identifiers required |
178
178
  | `['swapsApi', 'approve']` | `useSwapsApiApprove` mutation |
179
+ | `['swapsApi', 'approveAndBroadcast']` | `useSwapsApiApproveAndBroadcast` mutation |
179
180
  | `['swapsApi', 'createIntent']` | `useSwapsApiCreateIntent` mutation |
180
181
  | `['swapsApi', 'submitIntent']` | `useSwapsApiSubmitIntent` mutation |
181
182
  | `['swapsApi', 'cancelIntent']` | `useSwapsApiCancelIntent` mutation |
182
183
  | `['swapsApi', 'createLimitOrder']` | `useSwapsApiCreateLimitOrder` mutation |
183
184
  | `['swapsApi', 'submitTx']` | `useSwapsApiSubmitTx` mutation |
184
185
 
186
+ ### Bridge API (`sodax.api.bridge`)
187
+
188
+ Typed wrappers over `sodax.api.bridge.*` (one per Bridge API v2 endpoint), all keyed `['bridgeApi', action, ...]`.
189
+
190
+ | Key | Hook |
191
+ |---|---|
192
+ | `['bridgeApi', 'tokens']` | `useBridgeApiTokens` |
193
+ | `['bridgeApi', 'tokens', chainKey]` | `useBridgeApiTokensByChain` |
194
+ | `['bridgeApi', 'allowance', …]` | `useBridgeApiAllowance` |
195
+ | `['bridgeApi', 'fee', inputAmount, partnerFee]` | `useBridgeApiFee` |
196
+ | `['bridgeApi', 'bridgeableAmount', srcChainKey, dstChainKey, inputToken, outputToken]` | `useBridgeApiBridgeableAmount` |
197
+ | `['bridgeApi', 'bridgeable', srcChainKey, dstChainKey, inputToken, outputToken]` | `useBridgeApiIsBridgeable` |
198
+ | `['bridgeApi', 'submitTx', 'status', txHash, srcChainKey]` | `useBridgeApiSubmitTxStatus` — both identifiers required |
199
+ | `['bridgeApi', 'approve']` | `useBridgeApiApprove` mutation |
200
+ | `['bridgeApi', 'createBridgeIntent']` | `useBridgeApiCreateBridgeIntent` mutation |
201
+ | `['bridgeApi', 'submitTx']` | `useBridgeApiSubmitTx` mutation |
202
+
185
203
  ### Leverage Yield
186
204
 
187
205
  | Key | Hook |
@@ -36,6 +36,7 @@ If the user has already picked a single feature, load the matching granular skil
36
36
  | Sponsored Stellar account activation | [`./sponsoring/SKILL.md`](./sponsoring/SKILL.md) | "activate a Stellar account", "user has no XLM", "sponsor base reserve", "sodax.sponsoring" |
37
37
  | Backend HTTP client (intents, orderbook, MM reads) | [`./backend-api/SKILL.md`](./backend-api/SKILL.md) | "getIntentByHash", "Sodax backend API", "orderbook", "custom IConfigApiV1" |
38
38
  | Swaps API v2 client (quote, create-intent, submit-tx, fees) | [`./swaps-api/SKILL.md`](./swaps-api/SKILL.md) | "sodax.api.swaps", "swap quote from backend", "submit swap tx", "swaps API v2" |
39
+ | Bridge API v2 client (allowance/approve, create-intent, submit-tx, tokens, fee/bridgeable discovery) | [`./bridge-api/SKILL.md`](./bridge-api/SKILL.md) | "sodax.api.bridge", "createBridgeIntent via backend", "submit bridge tx", "bridge API v2" |
39
40
 
40
41
  Load this broad skill (keep reading below) when:
41
42
 
@@ -77,7 +78,7 @@ Follow in order. Skipping `ai-rules.md` is the most common cause of agents rever
77
78
 
78
79
  1. Read [`integration/knowledge/ai-rules.md`](./integration/knowledge/ai-rules.md) — DO / DO NOT / workflow / stop conditions.
79
80
  2. Read [`integration/knowledge/quickstart.md`](./integration/knowledge/quickstart.md) — install, initialize, first-run troubleshooting.
80
- 3. For your feature, read [`integration/knowledge/features/`](./integration/knowledge/features/) — `swap.md`, `money-market.md`, `staking.md`, `bridge.md`, `dex.md`, `migration.md`, `partner.md`, `recovery.md`, `sponsoring.md`, `backend-api.md`, `swaps-api.md`.
81
+ 3. For your feature, read [`integration/knowledge/features/`](./integration/knowledge/features/) — `swap.md`, `money-market.md`, `staking.md`, `bridge.md`, `dex.md`, `migration.md`, `partner.md`, `recovery.md`, `sponsoring.md`, `backend-api.md`, `swaps-api.md`, `bridge-api.md`.
81
82
  4. For specific patterns (init, raw vs signed, chain narrowing, gas, testing, errors, logging), read [`integration/knowledge/recipes/`](./integration/knowledge/recipes/).
82
83
  5. Lookups (chain keys, error codes, public API surface, wallet provider types, glossary) → [`integration/knowledge/reference/`](./integration/knowledge/reference/).
83
84
  6. Non-EVM quirks (Stellar trustline, BTC PSBT, Solana PDA, ICON, NEAR) → [`integration/knowledge/chain-specifics.md`](./integration/knowledge/chain-specifics.md).
@@ -0,0 +1,64 @@
1
+ ---
2
+ name: sodax-sdk-bridge-api
3
+ description: 'Granular skill for the @sodax/sdk v2 Bridge API client — `sodax.api.bridge` (class BridgeApiService), a typed HTTP client for the backend Bridge API v2 (`/bridge/*`: tokens, allowance/approve, create-bridge-intent, submit-tx + status, fee/bridgeable-amount/bridgeable discovery). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the bridge backend directly (e.g. "sodax.api.bridge", "createBridgeIntent via the backend API", "submit bridge tx", "poll bridge submit-tx status", "bridge API v2", "point bridge at a custom endpoint", "bridgeOptions.useBackendSubmitTx"). For the higher-level end-to-end bridge orchestrator use the `bridge` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
4
+ ---
5
+
6
+ # Bridge API (Core SDK granular skill)
7
+
8
+ Granular skill for `sodax.api.bridge` (class `BridgeApiService`) — the typed HTTP client for the backend
9
+ **Bridge API v2** (`/bridge/*`). `sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the bridge
10
+ client. One method per endpoint; every method returns `Promise<Result<T>>` (never throws) and
11
+ validates the response. Errors carry `feature: 'backend'`, `context.api: 'bridge'`, `context.endpoint`.
12
+
13
+ > Lower-level than `sodax.bridge`: this is the raw backend HTTP surface. For the end-to-end
14
+ > deposit→relay bridge orchestrator, use the [`bridge`](../bridge/SKILL.md) skill. The Bridge API mirrors
15
+ > the [`swaps-api`](../swaps-api/SKILL.md) client minus the solver/intent surface.
16
+
17
+ ## Step 1 — Clarify with user before coding
18
+
19
+ 1. **Which endpoint(s)?** Tokens · allowance/approve/create-bridge-intent · submit-tx/status · fee/bridgeable-amount/bridgeable discovery.
20
+ 2. **Orchestrator or raw API?** If the user just wants "do a bridge", prefer `sodax.bridge` (the `bridge`
21
+ skill). Use `sodax.api.bridge` when they need a single backend call or are building their own flow.
22
+ 3. **Backend availability.** The `/bridge/*` routes are the newest backend surface; confirm the target host
23
+ actually serves them (the on-chain `sodax.bridge` flow needs no backend).
24
+
25
+ ## Integration workflow
26
+
27
+ 1. [`../integration/knowledge/ai-rules.md`](../integration/knowledge/ai-rules.md) — DO / DO NOT (read first).
28
+ 2. [`../integration/knowledge/features/bridge-api.md`](../integration/knowledge/features/bridge-api.md) — the full client: signatures, deltas vs swaps (no intent, FULL relayData envelope, 5-state tolerant status), common call shapes (create-intent, submit-tx + status), the read-only fee/bridgeable-amount/bridgeable discovery quotes, per-call overrides, `bridgeOptions.useBackendSubmitTx`.
29
+ 3. For the end-to-end bridge flow that wraps these calls → [`../integration/knowledge/features/bridge.md`](../integration/knowledge/features/bridge.md); for the sibling swaps client → [`../integration/knowledge/features/swaps-api.md`](../integration/knowledge/features/swaps-api.md); for the read client (`sodax.backendApi`) → [`../integration/knowledge/features/backend-api.md`](../integration/knowledge/features/backend-api.md).
30
+ 4. Errors are `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` → [`../integration/knowledge/recipes/result-and-errors.md`](../integration/knowledge/recipes/result-and-errors.md) and [`../integration/knowledge/reference/error-codes.md`](../integration/knowledge/reference/error-codes.md).
31
+
32
+ ### Bridge-API-specific anti-patterns
33
+
34
+ - **`try/catch` for failures.** Every method returns `Result<T>` — branch on `result.ok`. `catch` won't fire for HTTP/timeout/validation failures.
35
+ - **Passing `relayData.payload` to `submitTx`.** Unlike the swaps client, bridge `submitTx.relayData` is the FULL `{ address, payload }` object — pass `relayData` as-is (bridge has no `intent.creator` for the backend to rebuild the relay address).
36
+ - **Expecting an `intent` / `intent_hash`.** `createBridgeIntent` returns `{ tx, relayData }` only; submit-tx status terminal success is `status === 'executed' && result.dstIntentTxHash` (no solver `intent_hash`, no `'posting_execution'` state).
37
+ - **Calling `getSubmitTxStatus` with only `txHash`.** Both `txHash` AND `srcChainKey` are required.
38
+ - **Using SDK-domain param names in the body.** The wire DTO uses swaps naming (`inputToken`/`outputToken`/`inputAmount`/`srcAddress`/`dstAddress`); map SDK-domain `srcToken`/`dstToken`/`amount`/`recipient` via `toCreateBridgeIntentParamsV2`.
39
+ - **Round-tripping the discovery quotes when a local read suffices.** `getFee` / `getBridgeableAmount` / `isBridgeable` are computable client-side — prefer `sodax.bridge.getFee` / `getBridgeableAmount` / `isBridgeable` (no network hop). Their backend endpoints exist (mirrored on this client) mainly for non-SDK HTTP callers / parity; the token *list*, by contrast, is only backend-served.
40
+ - **Confusing `sodax.api.bridge` with `sodax.bridge`.** The former is the backend HTTP client; the latter is the on-chain vault orchestrator.
41
+
42
+ ## Migration workflow (on-chain → API)
43
+
44
+ There is **no v1 Bridge API** — the typed `sodax.api.bridge` client is v2-new. The relevant move is from the
45
+ on-chain `sodax.bridge.bridge()` orchestrator to the API client (or to the orchestrator's opt-in backend
46
+ path via `bridgeOptions.useBackendSubmitTx`):
47
+
48
+ 1. [`../integration/knowledge/features/bridge.md`](../integration/knowledge/features/bridge.md) — the on-chain `BridgeService` orchestrator and the `bridgeOptions.useBackendSubmitTx` toggle that routes its spoke-deposit through this API with a client-side fallback.
49
+ 2. For the v1 → v2 reshape of the on-chain bridge itself (chain-key routing, `Result<T>`, error unions) → [`../migration-v1-to-v2/knowledge/features/bridge.md`](../migration-v1-to-v2/knowledge/features/bridge.md).
50
+
51
+ ## Verification
52
+
53
+ 1. `pnpm tsc --noEmit` clean.
54
+ 2. Every `await sodax.api.bridge.<method>(...)` call site has `if (!result.ok)`.
55
+ 3. `submitTx.relayData` is the full `relayData` object (not `relayData.payload`); `getSubmitTxStatus` passes both `txHash` and `srcChainKey`.
56
+ 4. Bodies use the wire DTO names (`inputToken`/`outputToken`/`inputAmount`/`dstAddress`), mapped from SDK-domain params.
57
+
58
+ ## Related granular skills (same family)
59
+
60
+ - [`../bridge/SKILL.md`](../bridge/SKILL.md) — the end-to-end bridge orchestrator (`sodax.bridge`) that wraps these backend calls.
61
+ - [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the sibling swaps HTTP client this mirrors.
62
+ - [`../backend-api/SKILL.md`](../backend-api/SKILL.md) — the `sodax.backendApi` read client (intent / orderbook / money-market reads + config).
63
+
64
+ For multi-feature tasks, load the broad [`sodax-sdk` skill](../SKILL.md).
@@ -88,6 +88,25 @@ The chain key on the request payload (e.g. `srcChainKey: ChainKeys.ETHEREUM_MAIN
88
88
 
89
89
  The chain key is the bridge between the type system and runtime routing.
90
90
 
91
+ ### ERC-20 approval can take two transactions
92
+
93
+ A few ERC-20s of the 2017 TetherToken lineage reject an allowance change from one non-zero value to
94
+ another, so a wallet holding a stale allowance cannot approve at all until the allowance is zeroed.
95
+ Before a signed approval, `SpokeService` simulates the approve and, when it reverts, sends
96
+ `approve(0)` first, waits for it to be mined, then sends the real approval. The user signs twice.
97
+
98
+ Detection is behavioural — the simulated approve either reverts or it does not — never a token list,
99
+ so a token added or upgraded later is handled without a code change. Consumer impact:
100
+
101
+ - **Signed flows (`raw: false`)** are unchanged. Every feature `approve` still resolves to a single
102
+ transaction hash: the hash of the **last** transaction. Show step progress in the UI if you want,
103
+ but nothing breaks if you do not.
104
+ - **Unsigned flows (`raw: true`)** still return exactly one transaction from `approve`, which cannot
105
+ express a two-step plan. Use `sodax.swaps.buildApproveTxs({ params, raw: true })` instead — it
106
+ returns `{ approveTx, resetTx? }`. `resetTx` is present only for a guarded token holding a stale
107
+ allowance — broadcast it and wait for it to be mined first, because `approveTx` is not valid until
108
+ the reset has landed.
109
+
91
110
  ---
92
111
 
93
112
  ## 3. `Sodax` facade and service graph
@@ -102,6 +102,24 @@ const exists = await radfi.checkIfTradingWalletExists(personalAddress);
102
102
 
103
103
  **Server-side / raw flows (no interactive sign-in).** A backend that builds raw Bitcoin intents can't run the BIP322 login, so seed a pre-provisioned Bound token instead of authenticating. `RadfiProvider` honors three injection points: `new Sodax({ ... })` with `radfi.accessToken` (and optional `refreshToken`) in the Bitcoin chain config (the constructor seeds them), `radfi.setRadfiAccessToken(token)` at runtime, or a per-action `extras.bound.accessToken` on `createIntent` (the Bitcoin-gated `bound` slot groups Bound/Radfi inputs). If an authenticated Bound call has neither a token nor a configured `apiKey`, `RadfiProvider` throws a legible `RadfiApiError` (the message names the fix: inject via `setRadfiAccessToken` or `new Sodax({ ... })` with `radfi.accessToken`) instead of sending an empty bearer and getting an opaque 403.
104
104
 
105
+ **Backend request signing.** Separate from the per-user token above: if Bound authenticates your service itself, pass `radfi.signRequest` to `new Sodax({ ... })`. The SDK calls it once per outbound Bound request and merges the returned headers onto it, so the credential stays in your closure and never on the SDK config:
106
+
107
+ ```ts
108
+ import { createHmac } from 'node:crypto';
109
+
110
+ new Sodax({
111
+ radfi: {
112
+ signRequest: () => {
113
+ const ts = `${Date.now()}`;
114
+ const signature = createHmac('sha256', secretKey).update(`${secretWord}_${ts}`).digest('hex');
115
+ return { 'x-api-signature': `${signature}_${ts}` };
116
+ },
117
+ },
118
+ });
119
+ ```
120
+
121
+ It receives `{ method, path }`, may be async, and runs on every request (a timestamped signature must not be cached). Its headers merge last, so do not return `Authorization` — that is the per-user token. Server-side only: never ship a credential in a browser bundle.
122
+
105
123
  Other public methods on `RadfiProvider` you may need: `setRadfiAccessToken`, `refreshAccessToken`, `createTradingWallet`, `createWithdrawTransaction`, `requestRadfiSignature`, `getExpiredUtxos`, `buildRenewUtxoTransaction`, `signAndBroadcastRenewUtxo`, `withdrawToUser`, `signAndBroadcastWithdraw`, `getMaxWithdrawable`. Read `RadfiProvider` source for argument shapes — the API surface is broader than typical chain providers.
106
124
 
107
125
  ### Pitfall
@@ -15,6 +15,8 @@ One file per feature service. Each file documents the v2 API surface, common cal
15
15
  | [`recovery.md`](recovery.md) | `RecoveryService` | Withdraw stuck hub-wallet assets back to a spoke chain. |
16
16
  | [`backend-api.md`](backend-api.md) | `BackendApiService` | HTTP client for backend services: swap-tx submission, intent / orderbook lookups, money-market reads. |
17
17
  | [`sponsoring.md`](sponsoring.md) | `SponsoringService` | Stellar account activation via sponsored reserves. The sponsor pays the base reserve; the user's wallet signs. |
18
+ | [`swaps-api.md`](swaps-api.md) | `SwapsApiService` | Typed HTTP client for the backend Swaps API v2 (`sodax.api.swaps`, `/swaps/*`). Quote, create-intent, submit-tx + status, fees. |
19
+ | [`bridge-api.md`](bridge-api.md) | `BridgeApiService` | Typed HTTP client for the backend Bridge API v2 (`sodax.api.bridge`, `/bridge/*`). Allowance/approve/create-intent, submit-tx + status, tokens. |
18
20
 
19
21
  All feature services are constructed and wired by the `Sodax` facade. You don't instantiate them directly — access them via `sodax.swaps`, `sodax.moneyMarket`, etc. See [`../architecture.md`](../architecture.md) for the service graph.
20
22
 
@@ -59,6 +59,11 @@ if (!submitResult.ok) return;
59
59
 
60
60
  ## Swap-intent request DTO — `bound.accessToken` (Bitcoin TRADING)
61
61
 
62
+ `/swaps/approve` answers `ApproveResponseV2 = { tx, resetTx? }`. `resetTx` appears only when the
63
+ source token rejects a non-zero to non-zero allowance change (Ethereum USDT is the only listed one
64
+ today) **and** the wallet already holds a stale allowance — broadcast it first, wait for it to be
65
+ mined, then broadcast `tx`. Absent for every other token, so a client that ignores it keeps working.
66
+
62
67
  `CreateIntentParamsV2` is the shared wire-level request body behind the typed `/swaps/allowance/check`, `/swaps/approve`, and `/swaps/intents` calls (the `IBackendApiV2` methods the SDK drives internally). It inherits the swap extras — `partnerFee`, `srcPublicKey`, and `bound` — from `SwapExtrasV2`, the JSON-safe mirror of the SDK `SwapExtras` (`QuoteRequestV2` inherits the same trio for its `includeTxData=true` path). For Bitcoin **TRADING**-mode `raw` intents the Bound Exchange (Radfi) token is carried as `bound.accessToken` — passed in the request body instead of an `x-bound-access-token` header so it stays inside the typed DTO. Required only when the source chain is Bitcoin in TRADING mode; ignored otherwise.
63
68
 
64
69
  You rarely build this DTO yourself: `sodax.swaps.createIntent` takes the token via the chain-key-gated `extras.bound.accessToken` slot and maps it onto `CreateIntentParamsV2.bound.accessToken`. See [`swap.md`](swap.md) § `SwapExtras` and [`../chain-specifics.md`](../chain-specifics.md) § "Bitcoin PSBT and Bound Exchange" for the consumer-facing flow and token-injection points.
@@ -0,0 +1,141 @@
1
+ # Bridge API — `BridgeApiService`
2
+
3
+ Typed HTTP client for the backend **Bridge API v2** (`/bridge/*`). Reachable as `sodax.api.bridge`
4
+ (`sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the `BridgeApiService` instance). One method
5
+ per endpoint. 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.bridge`. Service class: `BridgeApiService`. **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: 'bridge'`, and `context.endpoint` (the path); the underlying failure
12
+ is on `error.cause`. Like `sodax.api.swaps`, the bridge **HTTP client** is uniformly `feature: 'backend'`
13
+ (with a per-service `context.api` tag — `'bridge'`).
14
+
15
+ > Lower-level than `sodax.bridge` (the `BridgeService` orchestrator that deposits + relays end-to-end).
16
+ > Use `sodax.api.bridge` for a single backend call, or when building your own flow. The Bridge API is
17
+ > served on the base backend host — its routes are `/bridge/*` sub-paths under the same base URL.
18
+
19
+ ## Methods
20
+
21
+ ```ts
22
+ // Tokens
23
+ sodax.api.bridge.getTokens(config?): Promise<Result<GetBridgeTokensResponseV2>>;
24
+ sodax.api.bridge.getTokensByChain(chainKey, config?): Promise<Result<GetBridgeTokensByChainResponseV2>>;
25
+
26
+ // Allowance · approve · create intent — all three share the CreateBridgeIntentParamsV2 body
27
+ sodax.api.bridge.checkAllowance(body: CreateBridgeIntentParamsV2, config?): Promise<Result<BridgeAllowanceCheckResponseV2>>;
28
+ sodax.api.bridge.approve(body: CreateBridgeIntentParamsV2, config?): Promise<Result<BridgeApproveResponseV2>>;
29
+ sodax.api.bridge.createBridgeIntent(body: CreateBridgeIntentParamsV2, config?): Promise<Result<CreateBridgeIntentResponseV2>>;
30
+
31
+ // Submit-tx state machine
32
+ sodax.api.bridge.submitTx(body: BridgeSubmitTxRequestV2, config?): Promise<Result<BridgeSubmitTxResponseV2>>;
33
+ sodax.api.bridge.getSubmitTxStatus(query: BridgeSubmitTxStatusQueryV2, config?): Promise<Result<BridgeSubmitTxStatusResponseV2>>;
34
+
35
+ // Discovery / quote — read-only (computable client-side via sodax.bridge.*; mirrored here for HTTP parity)
36
+ sodax.api.bridge.getFee(body: BridgeFeeRequestV2, config?): Promise<Result<BridgeFeeResponseV2>>;
37
+ sodax.api.bridge.getBridgeableAmount(body: BridgeQuoteRequestV2, config?): Promise<Result<BridgeableAmountResponseV2>>;
38
+ sodax.api.bridge.isBridgeable(body: BridgeQuoteRequestV2, config?): Promise<Result<BridgeableCheckResponseV2>>;
39
+ ```
40
+
41
+ The optional trailing `config?: RequestOverrideConfig` (`{ baseURL?, timeout?, headers? }`) on every method
42
+ applies per-call overrides that take precedence over the service config (same as the swaps client).
43
+
44
+ ## Deltas vs the Swaps API
45
+
46
+ Bridge is **vault-backed, not solver-based**, so the surface is smaller and a few shapes differ:
47
+
48
+ - **No `intent` struct.** `createBridgeIntent` returns `{ tx, relayData }` (no `intent`); `submitTx` carries
49
+ no `intent` field; there is no quote / deadline / limit-order / cancel / intent-hash / packet surface.
50
+ - **`submitTx.relayData` is the FULL `{ address, payload }` object** (not the `.payload` string the swaps
51
+ client takes). Bridge has no `intent.creator` for the backend to rebuild the relay address, so the client
52
+ must send the whole envelope — dropping the address breaks split-tx-chain relay (Stellar/Solana/Sui/Stacks).
53
+ - **Status lifecycle is 5-state** (`'pending'` → `'relaying'` → `'relayed'` → `'executed'` | `'failed'`) —
54
+ no swaps `'posting_execution'`. Terminal success is `status === 'executed' && result.dstIntentTxHash`
55
+ (no solver `intent_hash`). The status schema is tolerant of unknown states.
56
+ - **Param naming follows the swaps wire convention** (`inputToken`/`outputToken`/`inputAmount`/`srcAddress`/
57
+ `dstAddress`), NOT the SDK-domain `srcToken`/`dstToken`/`amount`/`recipient`. The mapper
58
+ `toCreateBridgeIntentParamsV2(params, extras?)` converts SDK-domain params (and serializes the `bigint`
59
+ amount) to this wire DTO.
60
+ - **Discovery quotes (`getFee` / `getBridgeableAmount` / `isBridgeable`) are computable client-side** — prefer
61
+ `sodax.bridge.getFee(...)` / `getBridgeableAmount(...)` / `isBridgeable({ from, to })` (no round-trip). They
62
+ *also* have backend endpoints (listed above), mirrored on this client for non-SDK HTTP callers / parity.
63
+ The token *list* is backend-served via `getTokens` / `getTokensByChain`.
64
+
65
+ ## Common call shapes
66
+
67
+ ### Allowance · approve · create intent (shared body)
68
+
69
+ ```ts
70
+ const body = {
71
+ srcChainKey, dstChainKey,
72
+ inputToken, // source token address (SDK domain `srcToken`)
73
+ outputToken, // destination token address (SDK domain `dstToken`)
74
+ inputAmount: '1000000', // smallest unit, decimal string (SDK domain `amount`, bigint → string)
75
+ srcAddress, dstAddress, // dstAddress is the SDK domain `recipient`
76
+ };
77
+
78
+ const allowance = await sodax.api.bridge.checkAllowance(body);
79
+ if (allowance.ok && !allowance.value.valid) {
80
+ const approved = await sodax.api.bridge.approve(body); // { tx } — sign + broadcast yourself
81
+ }
82
+
83
+ const created = await sodax.api.bridge.createBridgeIntent(body);
84
+ if (!created.ok) return;
85
+ const { tx, relayData } = created.value; // no `intent`
86
+ ```
87
+
88
+ ### Submit tx + poll status
89
+
90
+ ```ts
91
+ // Sign + broadcast `tx` yourself, then hand the spoke tx hash back with the FULL relayData envelope.
92
+ const submit = await sodax.api.bridge.submitTx({
93
+ txHash, srcChainKey, walletAddress,
94
+ relayData, // the whole { address, payload } object, NOT relayData.payload
95
+ });
96
+ if (!submit.ok) return;
97
+
98
+ // Both txHash AND srcChainKey are required.
99
+ const status = await sodax.api.bridge.getSubmitTxStatus({ txHash, srcChainKey });
100
+ if (status.ok && status.value.data.status === 'executed') {
101
+ status.value.data.result?.dstIntentTxHash; // destination tx hash (no intent_hash)
102
+ }
103
+ // Lifecycle: 'pending' → 'relaying' → 'relayed' → 'executed' | 'failed'.
104
+ ```
105
+
106
+ ## Per-call overrides & custom endpoint
107
+
108
+ Every method accepts a trailing `RequestOverrideConfig` to redirect a single call or attach headers:
109
+
110
+ ```ts
111
+ await sodax.api.bridge.getTokens({ baseURL: 'https://staging.example/v1/be', headers: { 'X-Trace': 'abc' } });
112
+ ```
113
+
114
+ The Bridge API has no dedicated config slice — it always shares the base backend host (`/bridge/*`). To
115
+ move the whole backend (including bridge) to a custom host, use the `CustomApiConfig` `baseApiConfig` slice
116
+ (see [`backend-api.md`](backend-api.md) § "Custom backend").
117
+
118
+ ## Orchestrator integration — `bridgeOptions.useBackendSubmitTx`
119
+
120
+ `new Sodax({ bridgeOptions: { useBackendSubmitTx: true } })` opts the end-to-end `sodax.bridge.bridge()`
121
+ into routing the spoke-deposit through this API (`submit-tx` + status poll) with an automatic fall back to
122
+ the client-side relay on any non-success. **Default OFF.** This is a distinct key from
123
+ `swapsOptions.useBackendSubmitTx`. See [`bridge.md`](bridge.md) and the `CONFIGURE_SDK` doc.
124
+
125
+ ## Error handling
126
+
127
+ ```ts
128
+ const r = await sodax.api.bridge.createBridgeIntent(body);
129
+ if (!r.ok) {
130
+ // r.error: SodaxError<'EXTERNAL_API_ERROR'> — feature: 'backend', context.api: 'bridge',
131
+ // context.endpoint: '/bridge/intents'. The transport / shape-validation failure is on r.error.cause.
132
+ return;
133
+ }
134
+ ```
135
+
136
+ ## Cross-references
137
+
138
+ - `sodax.bridge` (the `BridgeService` orchestrator that deposits + relays end-to-end): [`bridge.md`](bridge.md).
139
+ - `sodax.api.swaps` (the sibling swaps HTTP client this mirrors): [`swaps-api.md`](swaps-api.md).
140
+ - `BackendApiService` (intent / orderbook / money-market reads + config): [`backend-api.md`](backend-api.md).
141
+ - Error model context fields: [`../reference/error-codes.md`](../reference/error-codes.md).
@@ -13,21 +13,29 @@ A bridge call deposits the source token into its vault on the hub, then triggers
13
13
  ## Public methods
14
14
 
15
15
  ```ts
16
- sodax.bridge.bridge<K>(action: BridgeAction<K, false>): Promise<Result<TxHashPair, SodaxError>>;
17
- sodax.bridge.createBridgeIntent<K, Raw>(action): Promise<Result<IntentTxResult<K, Raw>, SodaxError>>;
16
+ sodax.bridge.bridge<K>(action: BridgeParams<K, false>): Promise<Result<TxHashPair, SodaxError>>;
17
+ sodax.bridge.createBridgeIntent<K, Raw>(action: BridgeParams<K, Raw>): Promise<Result<IntentTxResult<K, Raw>, SodaxError>>;
18
18
  sodax.bridge.approve<K, Raw>(args): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
19
19
  sodax.bridge.isAllowanceValid<K, Raw>(args): Promise<Result<boolean, SodaxError>>;
20
20
 
21
21
  sodax.bridge.getBridgeableAmount(from: XToken, to: XToken): Promise<Result<BridgeLimit, SodaxError>>;
22
22
  sodax.bridge.getBridgeableTokens(from: SpokeChainKey, to: SpokeChainKey, token: string): Result<XToken[], SodaxError>;
23
- // Plus the sync helper:
23
+ // Plus the sync helpers:
24
24
  sodax.bridge.isBridgeable({ from: XToken, to: XToken }): boolean;
25
- sodax.bridge.getFee(inputAmount: bigint): bigint;
25
+ // partnerFee defaults to the configured `bridge.partnerFee`; pass one to preview an `extras.partnerFee` override.
26
+ sodax.bridge.getFee(inputAmount: bigint, partnerFee?: PartnerFee): bigint;
26
27
  ```
27
28
 
28
29
  ## Action params shape
29
30
 
30
31
  ```ts
32
+ type BridgeParams<K extends SpokeChainKey, Raw extends boolean> = {
33
+ params: CreateBridgeIntentParams<K>;
34
+ extras?: BridgeExtras<K>;
35
+ skipSimulation?: boolean;
36
+ timeout?: number; // shared budget for relay/poll; defaults to DEFAULT_RELAY_TX_TIMEOUT
37
+ } & WalletProviderSlot<K, Raw>; // raw: true ⇒ no walletProvider; raw: false ⇒ required, chain-narrowed
38
+
31
39
  type CreateBridgeIntentParams<K extends SpokeChainKey> = {
32
40
  srcChainKey: K;
33
41
  srcAddress: string; // source wallet (spoke chain)
@@ -39,6 +47,44 @@ type CreateBridgeIntentParams<K extends SpokeChainKey> = {
39
47
  };
40
48
  ```
41
49
 
50
+ ### extras (per-action overrides)
51
+
52
+ Chain-specific slots are keyed off `K`, so a non-Stacks action can't set `srcPublicKey` and a non-Bitcoin action can't set `bound`:
53
+
54
+ ```ts
55
+ type BridgeExtras<K extends SpokeChainKey> = (GetChainType<K> extends 'STACKS'
56
+ ? { srcPublicKey?: string }
57
+ : { srcPublicKey?: never }) &
58
+ (GetChainType<K> extends 'BITCOIN' ? { bound?: { accessToken?: string } } : { bound?: never }) & {
59
+ partnerFee?: PartnerFee;
60
+ };
61
+ ```
62
+
63
+ | Slot | When | Notes |
64
+ |---|---|---|
65
+ | `partnerFee` | any chain, optional | Takes precedence over the config-level `bridge.partnerFee` for this call. Omit to use the configured fee. |
66
+ | `srcPublicKey` | Stacks source + `raw: true` — **required** | A Stacks address can't yield the signer public key at raw-tx build time. Omitting it fails `VALIDATION_FAILED` (`field: 'srcPublicKey'`). |
67
+ | `bound` | raw Bitcoin TRADING source, optional | Bound Exchange (Radfi) access token; falls back to the `RadfiProvider` instance token. |
68
+
69
+ ```ts
70
+ const result = await sodax.bridge.bridge({
71
+ params: { /* … */ },
72
+ raw: false,
73
+ walletProvider: evmWp,
74
+ extras: { partnerFee: { address: '0xPartner…', percentage: 100 } }, // 100 = 1%
75
+ });
76
+ ```
77
+
78
+ ## Validation rules to respect
79
+
80
+ - **Native BTC dust limit (`BITCOIN_DUST_SATS` = 546 sats).** Native BTC is denominated in satoshis, and outputs below the dust limit are unspendable/rejected by nodes. Bitcoin as **source**: `amount >= 546`. Bitcoin as **destination**: the *post-fee delivered* amount must clear 546 — the partner fee is deducted on the hub in 18-dp vault units, so a percentage fee or a wei-denominated fixed `PartnerFee.amount` can push a nominally valid `amount` under the limit. Both fail `VALIDATION_FAILED` on `field: 'amount'`.
81
+ - **Stacks + `raw: true`** requires `extras.srcPublicKey` (above).
82
+ - Amount must be `> 0n`; both chain keys must be registered spoke chains; both tokens must be supported on their chain and share a vault.
83
+
84
+ ## Routing the spoke deposit through the backend
85
+
86
+ `bridge()` relays client-side by default. `new Sodax({ bridgeOptions: { useBackendSubmitTx: true } })` opts into handing the broadcast deposit to the backend Bridge API instead (`sodax.api.bridge`), which relays server-side and falls back to the client-side relay on any non-success — safe because re-relaying is idempotent. Default is OFF. See [`bridge-api.md`](bridge-api.md).
87
+
42
88
  ## Common call shapes
43
89
 
44
90
  ### Full bridge (recommended for most flows)
@@ -153,6 +199,12 @@ if (result.ok) {
153
199
  | `getBridgeableAmount` | `BridgeLimit = { amount, decimals, type }` |
154
200
  | `getBridgeableTokens` | `XToken[]` |
155
201
 
202
+ `approve` can send **two** transactions on a token that rejects a non-zero to non-zero allowance
203
+ change (Ethereum USDT is the only listed one today): `approve(0)` is mined first, then the real
204
+ approval, so the user signs twice. The returned value is unchanged — one hash, the **last**
205
+ transaction's. Detection simulates the approval, so never gate on a token list. Full note: "ERC-20
206
+ approval can take two transactions" in [`architecture.md`](../architecture.md).
207
+
156
208
  ## Error codes
157
209
 
158
210
  `feature: 'bridge'`. Per-method narrow unions:
@@ -165,6 +165,12 @@ The underlying read does not consult the wallet provider; pass `raw: true` to sa
165
165
 
166
166
  > `getPools()` is **synchronous** in v2 (was `Promise<PoolKey[]>` in v1). v2 reads from cached config — no I/O. `await sodax.dex.clService.getPools()` works (TS allows `await` on non-promise) but `.then(...)` is a runtime error.
167
167
 
168
+ `approve` can send **two** transactions on a token that rejects a non-zero to non-zero allowance
169
+ change (Ethereum USDT is the only listed one today): `approve(0)` is mined first, then the real
170
+ approval, so the user signs twice. The returned value is unchanged — one hash, the **last**
171
+ transaction's. Detection simulates the approval, so never gate on a token list. Full note: "ERC-20
172
+ approval can take two transactions" in [`architecture.md`](../architecture.md).
173
+
168
174
  ## Error codes
169
175
 
170
176
  `feature: 'dex'`. Per-method narrow unions:
@@ -152,6 +152,12 @@ await sodax.leverageYield.notifySolver({ intent_tx_hash: hubIntentTxHash });
152
152
  | `getAsset` | `Address` |
153
153
  | `listVaults` / `getVault` / `getVaultByAddress` | `LeverageYieldVault[]` / `LeverageYieldVault \| undefined` (synchronous) |
154
154
 
155
+ `approve` can send **two** transactions on a token that rejects a non-zero to non-zero allowance
156
+ change (Ethereum USDT is the only listed one today): `approve(0)` is mined first, then the real
157
+ approval, so the user signs twice. The returned value is unchanged — one hash, the **last**
158
+ transaction's. Detection simulates the approval, so never gate on a token list. Full note: "ERC-20
159
+ approval can take two transactions" in [`architecture.md`](../architecture.md).
160
+
155
161
  ## Error codes
156
162
 
157
163
  `feature: 'leverageYield'`. Action discriminator on `context.action`: `'deposit' | 'withdraw' | 'approve' | 'allowanceCheck' | 'vaultSwap'`. Read methods partition on `context.method`.
@@ -205,6 +205,12 @@ try {
205
205
  | `getAvailableAmount` | `bigint` |
206
206
  | `BalnSwapService.claim` etc. | `TxReturnType<K, false>` (raw, not `Result`-wrapped) |
207
207
 
208
+ `approve` can send **two** transactions on a token that rejects a non-zero to non-zero allowance
209
+ change (Ethereum USDT is the only listed one today): `approve(0)` is mined first, then the real
210
+ approval, so the user signs twice. The returned value is unchanged — one hash, the **last**
211
+ transaction's. Detection simulates the approval, so never gate on a token list. Full note: "ERC-20
212
+ approval can take two transactions" in [`architecture.md`](../architecture.md).
213
+
208
214
  ## Error codes
209
215
 
210
216
  `feature: 'migration'`. Per-method narrow unions:
@@ -164,6 +164,12 @@ The `action` field routes to the right token under the hood — relevant for rep
164
164
 
165
165
  > Every cross-chain mutation across the SDK (bridge, staking, dex, migration, MM) returns `TxHashPair = { srcChainTxHash, dstChainTxHash }` — there is no array-form variant in v2.
166
166
 
167
+ `approve` can send **two** transactions on a token that rejects a non-zero to non-zero allowance
168
+ change (Ethereum USDT is the only listed one today): `approve(0)` is mined first, then the real
169
+ approval, so the user signs twice. The returned value is unchanged — one hash, the **last**
170
+ transaction's. Detection simulates the approval, so never gate on a token list. Full note: "ERC-20
171
+ approval can take two transactions" in [`architecture.md`](../architecture.md).
172
+
167
173
  ## Error codes
168
174
 
169
175
  `feature: 'moneyMarket'`. Per-method narrow unions:
@@ -23,6 +23,8 @@ sponsor account can be rotated without a client release.
23
23
  ```ts
24
24
  // @ai-snippets-skip
25
25
  sodax.sponsoring.isStellarAccountActive({ address }); // Result<boolean>
26
+ sodax.sponsoring.getStellarAccountStatus({ address }); // Result<StellarAccountStatus>
27
+ // { exists, nativeBalanceStroops, availableBalanceStroops, canAffordTrustline, trustlineMinXlmStroops }
26
28
  sodax.sponsoring.getStellarSponsorConfig({ forceRefresh? }); // Result<StellarSponsorConfig>
27
29
  sodax.sponsoring.activateStellarAccount({
28
30
  address, // must be the account walletProvider signs with
@@ -151,6 +151,12 @@ const allowed = await sodax.staking.isAllowanceValid({
151
151
 
152
152
  > All 5 mutation methods return `TxHashPair = { srcChainTxHash, dstChainTxHash }` because the SDK relays spoke→hub internally. When the user is already on the hub, both fields hold the same hash.
153
153
 
154
+ `approve` can send **two** transactions on a token that rejects a non-zero to non-zero allowance
155
+ change (Ethereum USDT is the only listed one today): `approve(0)` is mined first, then the real
156
+ approval, so the user signs twice. The returned value is unchanged — one hash, the **last**
157
+ transaction's. Detection simulates the approval, so never gate on a token list. Full note: "ERC-20
158
+ approval can take two transactions" in [`architecture.md`](../architecture.md).
159
+
154
160
  ## Error codes
155
161
 
156
162
  `feature: 'staking'`. Per-method narrow unions:
@@ -264,6 +264,12 @@ type RelayExtraData = {
264
264
  };
265
265
  ```
266
266
 
267
+ `approve` can send **two** transactions on a token that rejects a non-zero to non-zero allowance
268
+ change (Ethereum USDT is the only listed one today): `approve(0)` is mined first, then the real
269
+ approval, so the user signs twice. The returned value is unchanged — one hash, the **last**
270
+ transaction's. Detection simulates the approval, so never gate on a token list. Full note: "ERC-20
271
+ approval can take two transactions" in [`architecture.md`](../architecture.md).
272
+
267
273
  ## Error codes
268
274
 
269
275
  `feature: 'swap'`. Per-method narrow unions:
@@ -57,6 +57,29 @@ sodax.api.swaps.getSubmitTxStatus(query: SubmitTxStatusQueryV2, config?): Promis
57
57
  The optional trailing `config?: RequestOverrideConfig` (`{ baseURL?, timeout?, headers? }`) on every method
58
58
  applies per-call overrides that take precedence over the service config (see "Per-call overrides" below).
59
59
 
60
+ ## `approve` can return two transactions
61
+
62
+ `ApproveResponseV2` is `{ tx, resetTx? }`. `resetTx` appears only when the source token rejects an
63
+ allowance change from one non-zero value to another (the 2017 TetherToken lineage) **and** the wallet
64
+ already holds a stale allowance — a wallet in that state cannot approve at all until it is zeroed.
65
+
66
+ Broadcast `resetTx` first and wait for it to be mined, then broadcast `tx`. The two cannot be
67
+ batched: the approval is only valid once the reset has landed on-chain.
68
+
69
+ ```ts
70
+ const { tx, resetTx } = approveResponse;
71
+
72
+ if (resetTx) {
73
+ const resetHash = await sendTransaction(resetTx);
74
+ await waitForTransactionReceipt(resetHash);
75
+ }
76
+
77
+ await sendTransaction(tx);
78
+ ```
79
+
80
+ The field is optional and absent for every other token, so ignoring it keeps existing behaviour —
81
+ it just cannot rescue a wallet stuck on a guarded token.
82
+
60
83
  ## Wire shapes — `bigint` vs decimal strings
61
84
 
62
85
  Request bodies that carry an `intent` struct (`cancelIntent`, `getIntentHash`,
@@ -18,8 +18,8 @@ Stellar's sponsorship sandwich requires the *sponsored* account to authorise
18
18
  `endSponsoringFutureReserves`, and only their wallet holds that key — so the client builds and signs,
19
19
  and the backend validates, co-signs as sponsor, and submits.
20
20
 
21
- Three methods, all returning `Result<T>` and never throwing:
22
- `activateStellarAccount`, `isStellarAccountActive`, `getStellarSponsorConfig`.
21
+ Four methods, all returning `Result<T>` and never throwing: `activateStellarAccount`,
22
+ `isStellarAccountActive`, `getStellarAccountStatus`, `getStellarSponsorConfig`.
23
23
 
24
24
  > **Activation makes the account able to RECEIVE, not to SEND.** The sponsor covers the account's own
25
25
  > reserve and `startingBalance` is `0`, so a freshly activated account holds **zero spendable XLM** — it