@sodax/skills 2.2.0-rc.8 → 2.3.0-rc.1

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 (63) hide show
  1. package/AGENTS.md +11 -10
  2. package/README.md +5 -5
  3. package/package.json +6 -5
  4. package/skills/sodax-build/SKILL.md +3 -3
  5. package/skills/sodax-build/knowledge/README.md +1 -1
  6. package/skills/sodax-build/knowledge/feature-catalog.md +4 -0
  7. package/skills/sodax-build/knowledge/glossary.md +1 -0
  8. package/skills/sodax-build/knowledge/handoff.md +3 -0
  9. package/skills/sodax-build/knowledge/interview-guide.md +1 -0
  10. package/skills/sodax-dapp-kit/SKILL.md +23 -5
  11. package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +4 -1
  12. package/skills/sodax-dapp-kit/bridge/SKILL.md +1 -1
  13. package/skills/sodax-dapp-kit/integration/knowledge/ai-rules.md +3 -0
  14. package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +18 -4
  15. package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +31 -1
  16. package/skills/sodax-dapp-kit/integration/knowledge/features/bridge.md +8 -0
  17. package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +17 -3
  18. package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +24 -0
  19. package/skills/sodax-dapp-kit/integration/knowledge/recipes/README.md +1 -0
  20. package/skills/sodax-dapp-kit/integration/knowledge/recipes/bridge.md +2 -0
  21. package/skills/sodax-dapp-kit/integration/knowledge/recipes/dex.md +23 -8
  22. package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield-product-anatomy.md +150 -0
  23. package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +122 -38
  24. package/skills/sodax-dapp-kit/integration/knowledge/recipes/swap.md +141 -1
  25. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +14 -3
  26. package/skills/sodax-dapp-kit/integration/knowledge/reference/public-api.md +1 -1
  27. package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +8 -0
  28. package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +27 -10
  29. package/skills/sodax-dapp-kit/swap/SKILL.md +3 -3
  30. package/skills/sodax-sdk/SKILL.md +2 -1
  31. package/skills/sodax-sdk/bridge/SKILL.md +3 -1
  32. package/skills/sodax-sdk/integration/knowledge/ai-rules.md +3 -0
  33. package/skills/sodax-sdk/integration/knowledge/architecture.md +1 -1
  34. package/skills/sodax-sdk/integration/knowledge/features/bridge-api.md +5 -3
  35. package/skills/sodax-sdk/integration/knowledge/features/bridge.md +8 -0
  36. package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +81 -12
  37. package/skills/sodax-sdk/integration/knowledge/features/swap.md +68 -2
  38. package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +56 -2
  39. package/skills/sodax-sdk/integration/knowledge/reference/error-codes.md +27 -1
  40. package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +30 -1
  41. package/skills/sodax-sdk/leverage-yield/SKILL.md +16 -8
  42. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/architecture.md +1 -1
  43. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/reference/sodax-config.md +9 -1
  44. package/skills/sodax-sdk/swap/SKILL.md +3 -1
  45. package/skills/sodax-sdk/swaps-api/SKILL.md +3 -2
  46. package/skills/sodax-wallet-sdk-core/SKILL.md +20 -2
  47. package/skills/sodax-wallet-sdk-core/evm/SKILL.md +2 -1
  48. package/skills/sodax-wallet-sdk-core/integration/knowledge/README.md +1 -1
  49. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +6 -0
  50. package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/interfaces.md +4 -1
  51. package/skills/sodax-wallet-sdk-core/migration-v1-to-v2/knowledge/README.md +1 -1
  52. package/skills/sodax-wallet-sdk-react/SKILL.md +20 -3
  53. package/skills/sodax-wallet-sdk-react/integration/knowledge/README.md +2 -1
  54. package/skills/sodax-wallet-sdk-react/integration/knowledge/ai-rules.md +2 -0
  55. package/skills/sodax-wallet-sdk-react/integration/knowledge/architecture.md +10 -6
  56. package/skills/sodax-wallet-sdk-react/integration/knowledge/examples/05-privy-email-login.tsx +157 -0
  57. package/skills/sodax-wallet-sdk-react/integration/knowledge/examples/README.md +1 -0
  58. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/privy-email-login.md +111 -0
  59. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/api-surface.md +14 -0
  60. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/chain-support.md +1 -1
  61. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/README.md +1 -1
  62. package/skills/sodax-wallet-sdk-react/privy/SKILL.md +53 -0
  63. package/skills/sodax-wallet-sdk-react/wallet-modal/SKILL.md +1 -0
@@ -12,7 +12,11 @@ Cross-chain token swaps via the intent-based solver.
12
12
  | `useSwap` | Mutation | Execute a complete cross-chain swap |
13
13
  | `useSwapAllowance` | Query | Check if token approval is needed |
14
14
  | `useSwapApprove` | Mutation | Approve tokens for the swap contract |
15
- | `useStatus` | Query | Track intent execution status |
15
+ | `useSwapLifecycle` | Composite | The whole swap form as one `state` + `next()`: approval strategy, destination gates, chain switch, swap, status |
16
+ | `useSwapWithApproval` | Mutation | `useSwap` with the approval folded in (one EIP-5792 signature where the wallet can batch) |
17
+ | `useSwapApprovalStrategy` | Query | Which approval path `useSwapWithApproval` takes |
18
+ | `useDetailedStatus` | Query | Track a swap by its source tx, whichever completion path ran (default status read) |
19
+ | `useStatus` | Query | Track the solver's status by hub tx hash |
16
20
  | `useCancelSwap` | Mutation | Cancel an active swap intent |
17
21
  | `useCreateLimitOrder` | Mutation | Create a limit order (no deadline) |
18
22
  | `useCancelLimitOrder` | Mutation | Cancel an active limit order |
@@ -110,6 +114,142 @@ function SwapButton({ intentParams }: { intentParams: CreateIntentParams }) {
110
114
  }
111
115
  ```
112
116
 
117
+ ## Track Status
118
+
119
+ Read status from the **source** tx you already hold after `swap()` — `useDetailedStatus` works whichever completion
120
+ path ran (backend submit-tx or the client-side relay fallback). `summarizeSwapStatus` collapses its two sources into
121
+ one vocabulary:
122
+
123
+ ```tsx
124
+ import { useDetailedStatus } from '@sodax/dapp-kit';
125
+ import { summarizeSwapStatus, type SpokeChainKey } from '@sodax/sdk';
126
+
127
+ function SwapStatus({ srcChainKey, srcTxHash }: { srcChainKey: SpokeChainKey; srcTxHash: string }) {
128
+ const { data } = useDetailedStatus({ params: { srcChainKey, srcTxHash } });
129
+ if (!data?.ok) return <span>Checking status…</span>;
130
+ const { state, fillTxHash } = summarizeSwapStatus(data.value);
131
+ return <span>{state === 'solved' ? `Filled ${fillTxHash ?? ''}` : state}</span>;
132
+ }
133
+ ```
134
+
135
+ Feed it `intentDeliveryInfo.srcChainKey` / `srcTxHash` on success. A `swap()` that fails **after** broadcast
136
+ (verification, relay or postExecution failure) still carries them on `error.context.srcChainKey` /
137
+ `error.context.srcTxHash` — keep polling, since the backend may still complete the swap.
138
+
139
+ ## One Hook for the Whole Form
140
+
141
+ `useSwapLifecycle` composes the approval strategy, the destination gates (Stellar account + trustline, NEAR
142
+ storage), source-chain switching, `useSwapWithApproval` and `useDetailedStatus` into one discriminated `state` and
143
+ one `next()` action. Render from `state.kind`; wire the button to `next()`. Chain switching and app-owned setup
144
+ (e.g. a Bitcoin trading wallet) are passed in — dapp-kit does not depend on the wallet packages.
145
+
146
+ ```tsx
147
+ import { useSwapLifecycle, type CreateIntentParams, type SwapLifecycleState } from '@sodax/dapp-kit';
148
+ import { useEvmSwitchChain, useWalletProvider } from '@sodax/wallet-sdk-react';
149
+
150
+ function buttonLabel(state: SwapLifecycleState): string {
151
+ switch (state.kind) {
152
+ case 'ready':
153
+ if (state.approvalStrategy === 'atomic-batch') return 'Approve & Swap';
154
+ return state.approvalStrategy === 'sequential' ? 'Approve, then Swap' : 'Swap';
155
+ case 'needsChainSwitch':
156
+ return 'Switch network';
157
+ case 'needsSetup':
158
+ if (state.reason === 'stellarActivation') return 'Activate account';
159
+ if (state.reason === 'stellarTrustline') return 'Add trustline';
160
+ if (state.reason === 'stellarCheckFailed') return 'Retry check';
161
+ if (state.reason === 'nearStorage') return 'Register storage';
162
+ if (state.reason === 'nearStorageCheckFailed') return 'Retry check';
163
+ return 'Waiting on setup';
164
+ case 'submitting':
165
+ case 'pending':
166
+ return 'Swapping…';
167
+ case 'unconfirmed':
168
+ return 'Check the batch again';
169
+ case 'settled':
170
+ return 'Swap again';
171
+ case 'failed':
172
+ return 'Try again';
173
+ default:
174
+ return 'Swap';
175
+ }
176
+ }
177
+
178
+ // Nothing to click: waiting, or a prerequisite only the user or the app can resolve.
179
+ function isPassive(state: SwapLifecycleState): boolean {
180
+ if (state.kind === 'needsSetup') return state.reason === 'stellarFunding' || state.reason === 'external';
181
+ return ['idle', 'checking', 'submitting', 'pending'].includes(state.kind);
182
+ }
183
+
184
+ function SwapButton({ intentParams }: { intentParams: CreateIntentParams }) {
185
+ const srcWalletProvider = useWalletProvider({ xChainId: intentParams.srcChainKey });
186
+ const dstWalletProvider = useWalletProvider({ xChainId: intentParams.dstChainKey });
187
+ const { isWrongChain, handleSwitchChain } = useEvmSwitchChain({ xChainId: intentParams.srcChainKey });
188
+
189
+ const { state, error, next, reset, stellar } = useSwapLifecycle({
190
+ intentParams,
191
+ srcWalletProvider,
192
+ dstWalletProvider,
193
+ chainSwitch: { isWrongChain, switchChain: handleSwitchChain },
194
+ });
195
+
196
+ return (
197
+ <>
198
+ <button type="button" onClick={() => void next()} disabled={isPassive(state)}>
199
+ {buttonLabel(state)}
200
+ </button>
201
+ {state.kind === 'needsSetup' && state.reason === 'stellarFunding' && (
202
+ <p>The destination Stellar account needs some XLM before it can add a trustline.</p>
203
+ )}
204
+ {state.kind === 'needsSetup' && state.reason === 'stellarCheckFailed' && <p>{stellar.error?.message}</p>}
205
+ {state.kind === 'pending' && (
206
+ <button type="button" onClick={reset}>
207
+ Stop tracking
208
+ </button>
209
+ )}
210
+ {state.kind === 'unconfirmed' && (
211
+ <p>
212
+ Your wallet sent the swap but it is not confirmed yet. Check the batch again to finish it once it lands.{' '}
213
+ <button type="button" onClick={reset}>
214
+ Start over
215
+ </button>
216
+ </p>
217
+ )}
218
+ {error && state.kind !== 'unconfirmed' && <p>{error.message}</p>}
219
+ </>
220
+ );
221
+ }
222
+ ```
223
+
224
+ `next()` resolves to the action's `Result` (a setup step or the swap); show a failed setup action from there. A failed
225
+ swap lands in `state`:
226
+
227
+ - before anything was sent → `failed`, and `next()` starts over;
228
+ - after the source tx was sent → `pending` with `error` set, because the backend may still complete it. It stays
229
+ `pending` until the status read answers `solved` or `failed`. The read can stop polling without an error (after its
230
+ budget of ambiguous reads), so keep a "stop tracking" `reset()` reachable throughout `pending`; it cancels nothing
231
+ on-chain;
232
+ - an approve + swap batch the wallet accepted but that was not confirmed in time → `unconfirmed`. It may still land,
233
+ so `next()` never sends it again: it waits for that batch (`swapWithApproval` with `resumeBatchId`) and finishes
234
+ the swap once it lands, staying `unconfirmed` while the batch is pending. `reset()` stops tracking it.
235
+
236
+ Those last two hold even when `intentParams` changes (a refreshed quote rebuilds them), so a param edit cannot
237
+ re-enable the swap while the first one may still land. `next()` also ignores a call while the previous one is still
238
+ running, so a double click swaps once. A setup step reads `checking`, not `needsSetup`, while its tx is in flight and
239
+ until the check it invalidated has refreshed, so a second click cannot resend it.
240
+
241
+ A user who declines the smart-account upgrade a `'ready'` wallet asks for lands in `failed` with a `USER_REJECTED`
242
+ whose `context.reason` is `ACCOUNT_UPGRADE_DECLINED`. They refused the upgrade, not the swap: keep an
243
+ `allowAccountUpgrade` flag in your own state, pass it to `useSwapLifecycle`, and offer "swap without upgrading" by
244
+ setting it to `false` and calling `reset()`. The strategy then reads `'sequential'` and the next swap approves
245
+ separately. Whether to remember that choice across sessions is up to the app.
246
+
247
+ `submitting` covers the whole swap call: signing, and on the default backend path settlement too, so label it as
248
+ swapping, not as waiting for the wallet. Build `intentParams` once per confirmation (a rebuilt `deadline` is fine):
249
+ changing any other field starts a new lifecycle once the current swap is done (one that may still land holds until
250
+ `reset()`). `stellarFunding` and
251
+ `external` setup reasons are for the app to resolve; `next()` does nothing for them.
252
+
113
253
  ## Full Example
114
254
 
115
255
  ```tsx
@@ -19,6 +19,9 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
19
19
  | `useSwap` | Mutation | Execute a complete cross-chain swap |
20
20
  | `useSwapAllowance` | Query | Check token approval status |
21
21
  | `useSwapApprove` | Mutation | Approve tokens for the swap contract |
22
+ | `useSwapApprovalStrategy` | Query | Which path `useSwapWithApproval` takes — `'not-required'` / `'atomic-batch'` (one EIP-5792 signature) / `'sequential'`; `allowAccountUpgrade: false` keeps a `'ready'` wallet sequential; no polling |
23
+ | `useSwapLifecycle` | Composite | One swap form: `state` (`idle` … `ready` … `pending` / `unconfirmed` / `settled` / `failed`, discriminated on `kind`) + `next()`; composes the strategy, Stellar/NEAR gates, injected chain switch, `useSwapWithApproval` and `useDetailedStatus`, and returns each as an escape hatch; `allowAccountUpgrade` is passed to both |
24
+ | `useSwapWithApproval` | Mutation | `useSwap` with the approval folded in: one atomic batch on an EIP-5792 wallet, else approve → swap; `data.approvalStrategy` |
22
25
  | `useStatus` | Query | Track intent execution status (polls 3s once `intentTxHash` supplied; stops on `3`/`4` and after 40 consecutive NOT_FOUND fetches; Result-wrapped data) |
23
26
  | `useDetailedStatus` | Query | Track a swap from its source tx (`{ srcChainKey, srcTxHash }`; polls 3s; Result-wrapped; stops on the answering source's terminal state and after 40 consecutive ambiguous reads — solver NOT_FOUND, or a relay with no packet for the tx; outages keep polling). Returns a tagged union — backend submit-tx record or solver answer — narrow on `source`. Unlike `useSwapsApiSubmitTxStatus`, answers for both `swap()` completion paths |
24
27
  | `useCancelSwap` | Mutation | Cancel an active swap intent |
@@ -52,6 +55,8 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
52
55
  | `useBridgeDetailedStatus` | Query | Track a bridge from its source tx (`{ srcChainKey, srcTxHash, apiConfig? }`; polls 3s; Result-wrapped; stops on the answering source's terminal state, on a rejected API key, and after 40 consecutive ambiguous reads — a relay with no packet for the tx; outages keep polling). Returns a tagged union — backend submit-tx record or delivered relay packet — narrow on `source`. Unlike `useBridgeApiSubmitTxStatus`, answers for both `bridge()` completion paths |
53
56
  | `useBridgeAllowance` | Query | Approval check |
54
57
  | `useBridgeApprove` | Mutation | Approve tokens for bridge |
58
+ | `useBridgeWithApproval` | Mutation | Bridge with the approval folded in — one EIP-5792 signature when the wallet can; `TxHashPair` + `approvalStrategy` |
59
+ | `useBridgeApprovalStrategy` | Query | `'not-required' \| 'atomic-batch' \| 'sequential'` for `useBridgeWithApproval`; not polled |
55
60
  | `useGetBridgeableAmount` | Query | Max bridgeable amount between two `XToken`s |
56
61
  | `useGetBridgeableTokens` | Query | Tokens bridgeable to a destination chain |
57
62
 
@@ -101,15 +106,20 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
101
106
 
102
107
  ## Leverage Yield
103
108
 
109
+ No hook lists the vaults: read the registry with `useSodaxContext().sodax.leverageYield.listVaults()` (synchronous; `{ name, vault, asset, borrowToken, lsdSource? }[]`) and pass `vault` to the hooks below. `targetLtvBps` and position `ltv` are basis points; `healthFactor` and `leverageMultiplierWad` are WAD, and the multiplier is the **borrowed** multiple (exposure = 1 + multiplier).
110
+
104
111
  | Hook | Type | Purpose |
105
112
  |---|---|---|
106
113
  | `useLeverageYieldDeposit` | Mutation | Build a deposit payload (any token → `lsoda*` shares) — spread into `useLeverageYieldVaultSwap` |
107
114
  | `useLeverageYieldWithdraw` | Mutation | Build a withdraw payload (`lsoda*` → any token; `hubWalletSwap`) |
115
+ | `useLeverageYieldVaultSwapWithApproval` | Mutation | `useLeverageYieldVaultSwap` with the deposit's approval folded in — one EIP-5792 signature when the wallet can; adds `approvalStrategy` |
116
+ | `useLeverageYieldApprovalStrategy` | Query | `'not-required' \| 'atomic-batch' \| 'sequential'` for `useLeverageYieldVaultSwapWithApproval` (withdraw is always `'not-required'`); not polled |
108
117
  | `useLeverageYieldVaultSwap` | Mutation | Execute a built payload end-to-end; backend submit-tx by default, falling back to the client-side create → verify → relay → notify path. `extras.apiKey` keys the backend leg per action |
109
118
  | `useLeverageYieldDetailedStatus` | Query | Track a vault swap from its source tx (`{ srcChainKey, srcTxHash, apiConfig? }`; polls 3s; Result-wrapped; stops on the answering source's terminal state, on a rejected API key, and after 40 consecutive ambiguous reads — solver NOT_FOUND, or a relay with no packet for the tx; outages keep polling). Returns a tagged union — backend submit-tx record or solver answer — narrow on `source`. Unlike `useLeverageYieldApiSubmitTxStatus`, answers for both `vaultSwap()` completion paths |
119
+ | `useLeverageYieldQuote` | Query | Deposit (vault = `token_dst`) or withdraw (vault = `token_src`) quote with the leverage-yield fee (polls 3s; Result-wrapped). Size `minOutputAmount` from `quoted_amount` minus slippage, never `0n` |
110
120
  | `useLeverageYieldNotifySolver` | Mutation | Manual-flow notify step (after a self-driven `createVaultIntent` + relay) |
111
121
  | `useLeverageYieldEffectiveApr` | Query | AAVE + LSD effective net APR (60s) |
112
- | `useLeverageYieldPosition` | Query | Live position: collateral, debt, LTV, health factor, idle (30s) |
122
+ | `useLeverageYieldPosition` | Query | Live position: collateral, debt, LTV (bps), health factor (WAD), idle (30s) |
113
123
  | `useLeverageYieldTotalAssets` | Query | Vault TVL (18-dp bigint, 60s) |
114
124
  | `useLeverageYieldPreviewRedeem` | Query | Assets for N shares; pass `1e18` for price-per-share (60s) |
115
125
  | `useLeverageYieldShareBalances` | Query | Per-chain `lsoda*` balances via `useQueries` — returns an array (15s) |
@@ -209,6 +219,7 @@ Typed React Query wrappers over the backend Swaps API (`sodax.api.swaps.*`), one
209
219
  |---|---|
210
220
  | `useSwapsApiApprove` | Mutation; builds unsigned approval tx(s) — `{ tx, resetTx? }`, caller signs |
211
221
  | `useSwapsApiApproveAndBroadcast` | Mutation; builds **and** signs/broadcasts/waits — preferred; `{ approveTxHash, resetTxHash? }`; optional `onProgress` per step |
222
+ | `useSwapsApiBroadcastWithApproval` | Mutation; EVM source with a short allowance — approval + `intentTx` in one EIP-5792 batch (one signature), else rejects with a refusal (`fallbackOnRefusal: true` approves, then sends the pre-approval `intentTx`); `{ txHash, approvalStrategy, approval? }`; stops before submit-tx; `onBatchSent` (persist the batch id) |
212
223
  | `useSwapsApiCreateIntent` | Mutation; builds `{ tx, intent, relayData }` |
213
224
  | `useSwapsApiSubmitIntent` | Mutation; submits broadcast intent to the relay |
214
225
  | `useSwapsApiCancelIntent` | Mutation; builds unsigned cancel tx |
@@ -242,7 +253,7 @@ Typed React Query wrappers over the backend Leverage Yield API (`sodax.api.lever
242
253
  | `useLeverageYieldApiVaults` | Query; the deployed-vault registry |
243
254
  | `useLeverageYieldApiVault` | Query; one vault descriptor by lsoda* `name` |
244
255
  | `useLeverageYieldApiAsset` | Query; the vault's underlying hub asset |
245
- | `useLeverageYieldApiPosition` | Query; `{ collateral, debt, ltv, healthFactor, idleAsset }` |
256
+ | `useLeverageYieldApiPosition` | Query; `{ collateral, debt, ltv, healthFactor, idleAsset }` as decimal strings (`ltv` bps, `healthFactor` WAD) |
246
257
  | `useLeverageYieldApiApr` | Query; AAVE-only steady-state APR (RAY strings; can be negative) |
247
258
  | `useLeverageYieldApiEffectiveApr` | Query; combined AAVE + LSD APR — `effectiveNetAprRay` is the headline |
248
259
  | `useLeverageYieldApiLsdApr` | Query; off-chain LSD staking-APR snapshot |
@@ -251,7 +262,7 @@ Typed React Query wrappers over the backend Leverage Yield API (`sodax.api.lever
251
262
  | `useLeverageYieldApiPreviewWithdraw` | Query; ERC-4626 `previewWithdraw` — shares burned for `assets` |
252
263
  | `useLeverageYieldApiPreviewRedeem` | Query; ERC-4626 `previewRedeem` — assets for `shares` |
253
264
  | `useLeverageYieldApiShareBalance` | Query; an owner's lsoda* balance (the HUB wallet, not the EOA) |
254
- | `useLeverageYieldApiMaxWithdraw` | Query; RAW ERC-4626 `maxWithdraw` — NOT dust-trimmed, apply a margin for a MAX withdraw |
265
+ | `useLeverageYieldApiMaxWithdraw` | Query; RAW ERC-4626 `maxWithdraw` in ASSET units, NOT dust-trimmed — never a withdraw's `inputAmount`, which is shares; size a MAX withdraw from `useLeverageYieldApiShareBalance` |
255
266
  | `useLeverageYieldApiDepositQuote` | Query; any token → lsoda* (set `query.includeTxData` for `txData`) |
256
267
  | `useLeverageYieldApiWithdrawQuote` | Query; lsoda* → any token |
257
268
  | `useLeverageYieldApiDeadline` | Query; computed vault-swap deadline |
@@ -101,7 +101,7 @@ README.md
101
101
  LICENSE
102
102
  ```
103
103
 
104
- Don't rely on any other path being present. Consumer-facing AI docs (this knowledge tree) are shipped separately via [`@sodax/skills`](https://github.com/icon-project/sodax-sdks/tree/main/packages/skills).
104
+ Don't rely on any other path being present. Consumer-facing AI docs (this knowledge tree) are shipped separately via [`@sodax/skills`](https://github.com/gosodax/sodax-sdks/tree/main/packages/skills).
105
105
 
106
106
  ## Cross-references
107
107
 
@@ -70,6 +70,7 @@ queryClient.invalidateQueries({ queryKey: ['swap', 'allowance'] }); // wipe all
70
70
  queryKey: ['mm', 'allowance', srcChainKey, token, action]
71
71
  queryKey: ['swap', 'allowance', srcChainKey, srcAddress, inputToken, inputAmount.toString()]
72
72
  queryKey: ['bridge', 'allowance', srcChainKey, srcAddress, srcToken, amount.toString()]
73
+ queryKey: ['bridge', 'approvalStrategy', srcChainKey, srcAddress, srcToken, amount.toString(), allowAccountUpgrade] // useBridgeApprovalStrategy
73
74
  queryKey: ['bridge', 'detailedStatus', srcChainKey, srcTxHash] // useBridgeDetailedStatus — apiConfig excluded
74
75
  queryKey: ['leverageYield', 'detailedStatus', srcChainKey, srcTxHash] // useLeverageYieldDetailedStatus — apiConfig excluded
75
76
  queryKey: ['dex', 'allowance', srcChainKey, asset, amount.toString()]
@@ -93,6 +94,7 @@ mutationKey: ['mm', 'supply']
93
94
  mutationKey: ['staking', 'stake']
94
95
  mutationKey: ['staking', 'approve', 'stake'] // useStakeApprove (action discriminator inside the key)
95
96
  mutationKey: ['bridge'] // useBridge — single segment (no 'execute' suffix)
97
+ mutationKey: ['bridge', 'bridgeWithApproval'] // useBridgeWithApproval
96
98
  mutationKey: ['migrate', 'icxToSoda']
97
99
  mutationKey: ['dex', 'supplyLiquidity']
98
100
  mutationKey: ['shared', 'registerNearStorage'] // useRegisterNearStorage
@@ -109,8 +111,11 @@ Skip if you're writing a feature hook for the first time and want to align with
109
111
  | `['swap', 'quote', { ...payload, amount: payload.amount.toString() }]` | `useQuote` (object segment with bigint stringified) |
110
112
  | `['swap', 'allowance', srcChainKey, srcAddress, inputToken, inputAmount.toString()]` | `useSwapAllowance` |
111
113
  | `['swap', 'status', intentTxHash]` | `useStatus` |
114
+ | `['swap', 'detailedStatus', srcChainKey, srcTxHash]` | `useDetailedStatus` |
115
+ | `['swap', 'approvalStrategy', srcChainKey, srcAddress, inputToken, inputAmount.toString(), allowAccountUpgrade]` | `useSwapApprovalStrategy` |
112
116
  | `['swap']` | `useSwap` mutation key |
113
117
  | `['swap', 'approve']` | `useSwapApprove` |
118
+ | `['swap', 'swapWithApproval']` | `useSwapWithApproval` |
114
119
  | `['swap', 'cancel']` | `useCancelSwap` |
115
120
  | `['swap', 'limitOrder', 'create']` | `useCreateLimitOrder` |
116
121
  | `['swap', 'limitOrder', 'cancel']` | `useCancelLimitOrder` |
@@ -180,6 +185,7 @@ Typed wrappers over `sodax.api.swaps.*` (one per Swaps API endpoint), all keyed
180
185
  | `['swapsApi', 'submitTx', 'status', txHash, srcChainKey]` | `useSwapsApiSubmitTxStatus` — both identifiers required |
181
186
  | `['swapsApi', 'approve']` | `useSwapsApiApprove` mutation |
182
187
  | `['swapsApi', 'approveAndBroadcast']` | `useSwapsApiApproveAndBroadcast` mutation |
188
+ | `['swapsApi', 'broadcastWithApproval']` | `useSwapsApiBroadcastWithApproval` mutation |
183
189
  | `['swapsApi', 'createIntent']` | `useSwapsApiCreateIntent` mutation |
184
190
  | `['swapsApi', 'submitIntent']` | `useSwapsApiSubmitIntent` mutation |
185
191
  | `['swapsApi', 'cancelIntent']` | `useSwapsApiCancelIntent` mutation |
@@ -258,6 +264,8 @@ Typed wrappers over `sodax.api.leverageYield.*` (one per Leverage Yield API endp
258
264
  | `['leverageYield', 'deposit']` | `useLeverageYieldDeposit` mutation |
259
265
  | `['leverageYield', 'withdraw']` | `useLeverageYieldWithdraw` mutation |
260
266
  | `['leverageYield', 'vaultSwap']` | `useLeverageYieldVaultSwap` mutation |
267
+ | `['leverageYield', 'vaultSwapWithApproval']` | `useLeverageYieldVaultSwapWithApproval` mutation |
268
+ | `['leverageYield', 'approvalStrategy', srcChainKey, srcAddress, inputToken, amount, hubWalletSwap, allowAccountUpgrade]` | `useLeverageYieldApprovalStrategy` |
261
269
  | `['leverageYield', 'notifySolver']` | `useLeverageYieldNotifySolver` mutation |
262
270
 
263
271
  ### Bridge / DEX / Migration / Bitcoin / etc.
@@ -16,8 +16,9 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
16
16
  0. **Vault or leverage position?** Ask first — they share the `leverageYield` key namespace and nothing else. A **vault** is one pooled ERC-4626 position at a single target LTV (`useLeverageYield*`). A **leverage position** is the user's own AAVE account, cloned per position (`useLeveragePosition*`, `useOpenLeveragePosition`). `useLeverageYieldPosition` is the **vault's** snapshot — it is not a leverage position. If the answer is positions, jump to Step 1b.
17
17
  1. **Deposit or withdraw?** Deposit = any token → `lsoda*` shares (lands in the hub wallet). Withdraw = `lsoda*` shares → any token on any chain.
18
18
  2. **Build vs execute.** `useLeverageYieldDeposit` / `useLeverageYieldWithdraw` only *build* a `LeverageYieldSwapPayload`; `useLeverageYieldVaultSwap` *executes* it (create → relay → notify solver). You always need both.
19
- 3. **Approval?** Deposit approves the spoke `inputToken` via the swap-domain `useSwapApprove` / `useSwapAllowance` (no leverage-yield-specific approve hook). Withdraw needs no approval (`hubWalletSwap: true`).
20
- 4. **Which reads?** `useLeverageYieldEffectiveApr` (headline APR), `useLeverageYieldPosition` (LTV/health), `useLeverageYieldTotalAssets` (TVL), `useLeverageYieldPreviewRedeem` (price-per-share), `useLeverageYieldShareBalances` (per-chain balances — returns an array).
19
+ 3. **Approval?** `useLeverageYieldVaultSwapWithApproval` folds the deposit's approval in (one EIP-5792 batch when the wallet can), labelled with `useLeverageYieldApprovalStrategy`. The two-step alternative approves the spoke `inputToken` via the swap-domain `useSwapApprove` / `useSwapAllowance`. Withdraw needs no approval (`hubWalletSwap: true`).
20
+ 4. **Which vaults?** No hook — read the registry with `useSodaxContext().sodax.leverageYield.listVaults()` (synchronous, wrap in `useMemo`) and pass each entry's `vault` address to the hooks.
21
+ 5. **Which reads?** `useLeverageYieldEffectiveApr` (headline APR), `useLeverageYieldPosition` (LTV/health), `useLeverageYieldTotalAssets` (TVL), `useLeverageYieldPreviewRedeem` (price-per-share), `useLeverageYieldShareBalances` (per-chain balances — returns an array).
21
22
 
22
23
  ### Step 1b — leverage positions
23
24
 
@@ -32,6 +33,7 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
32
33
  2. [`../integration/knowledge/architecture.md`](../integration/knowledge/architecture.md) — hook shapes, `mutateAsyncSafe`, `unwrapResult`, queryKey conventions.
33
34
  3. [`../integration/knowledge/features/leverage-yield.md`](../integration/knowledge/features/leverage-yield.md) — full hook surface, mutation TVars, read shapes, approval pattern, gotchas.
34
35
  4. [`../integration/knowledge/recipes/leverage-yield.md`](../integration/knowledge/recipes/leverage-yield.md) — full worked examples (deposit, withdraw, stats, share balances).
36
+ - **Building a user-facing vault screen?** Read [`../integration/knowledge/recipes/leverage-yield-product-anatomy.md`](../integration/knowledge/recipes/leverage-yield-product-anatomy.md) first: the journey, the states to handle, display metadata, USD prices, derived values, units, and the planned steps with explorer links. Layout stays your call.
35
37
  5. Call-shape choice → [`../integration/knowledge/recipes/mutation-error-handling.md`](../integration/knowledge/recipes/mutation-error-handling.md).
36
38
 
37
39
  ### Leverage-yield-specific anti-patterns (dapp-kit)
@@ -39,8 +41,12 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
39
41
  - **Calling `useLeverageYieldDeposit` / `useLeverageYieldWithdraw` and expecting a tx.** They are builders — their `data` is a `LeverageYieldSwapPayload`. Spread it into `useLeverageYieldVaultSwap`'s `mutate` with a `walletProvider` to broadcast.
40
42
  - **Treating `useLeverageYieldShareBalances` as a single query.** It returns an **array** (one `useQueries` row per holder). Aggregate with `reduce`; the key segment is singular `shareBalance`.
41
43
  - **Gating withdraw on an allowance check.** Withdraw carries `hubWalletSwap: true` — the hub wallet authorises the share spend via `sendMessage`. Only `deposit` uses `useSwapAllowance` / `useSwapApprove`.
42
- - **Reaching for a `useLeverageYieldApprove` hook.** It doesn't exist — the deposit approves the spoke asset manager, so use the swap-domain hooks.
43
- - **Quoting on the pre-fee amount.** A deposit's per-intent `partnerFee` is deducted from `inputAmount` before the swap — quote on the post-fee amount or `minOutputAmount` is unfillable.
44
+ - **Reaching for a `useLeverageYieldApprove` hook.** It doesn't exist — use `useLeverageYieldVaultSwapWithApproval`, or the swap-domain hooks, since the deposit approves the spoke asset manager.
45
+ - **Sending `minOutputAmount: 0n`.** Always derive it from `useLeverageYieldQuote`'s `quoted_amount` minus a slippage tolerance in basis points, and disable the action until the quote is `ok`. A zero minimum accepts any fill.
46
+ - **Adding a `partnerFee` nobody asked for.** It is optional and opt-in; leave it out unless the integrator gave you their own receiver. Never copy a fee address from a SODAX demo or doc.
47
+ - **Labelling `leverageMultiplierWad` as "Leverage".** It is the borrowed multiple, `targetLTV / (1 − targetLTV)`; exposure is `1 + multiplier`. `targetLtvBps` and `position.ltv` are basis points.
48
+ - **Lowering the vault-read intervals.** The APR read alone is six Sonic `eth_call`s per vault per refresh. Keep the hook defaults on vault cards; only override hooks that poll faster than your app's floor (quotes, status, wallet balances).
49
+ - **Quoting a vault flow with `useQuote`, or with a different fee.** Size `minOutputAmount` with `useLeverageYieldQuote` on the **gross** `inputAmount` — it deducts the effective leverage-yield fee itself, so netting the amount first deducts it twice. Pass it the same `partnerFee` as `useLeverageYieldDeposit` / `useLeverageYieldWithdraw`, or omit it on both. `useQuote` deducts the *swap* fee instead, and whenever the two fees differ the derived `minOutputAmount` can be unfillable.
44
50
 
45
51
  ### Leverage-position anti-patterns (dapp-kit)
46
52
 
@@ -53,22 +59,33 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
53
59
  - **Charging an existing position the configured fee.** Read `feeBps` from `useLeveragePositionInfo`; `getEffectivePositionFee()` is what a NEW position would carry.
54
60
  - **Treating the mutation receipt as completion.** A solver fills a leverage change afterwards — poll `useLeveragePositionPending`.
55
61
 
62
+ ## Acceptance (what the user can do)
63
+
64
+ Check the running app against these, not only `pnpm tsc`. The full list is in the product anatomy's Acceptance section.
65
+
66
+ - Every vault shows its asset, a variable APR (sign kept), TVL in the asset and USD, exposure (`1 + multiplier`) and health.
67
+ - Before signing, the user sees what they receive, the minimum they accept, and the steps they will sign.
68
+ - Each step links to its transaction on the right explorer, and the flow is followed to a terminal status.
69
+ - Shares are shown per network, in the asset and in USD; withdraw is capped at shares and signed from the network that deposited.
70
+ - Rejecting in the wallet returns to the form quietly; every other state has a clear message.
71
+
56
72
  ## Verification
57
73
 
58
74
  1. `pnpm tsc --noEmit` clean.
59
75
  2. Deposit/withdraw build a payload, then `useLeverageYieldVaultSwap` executes it (`{ ...payload, walletProvider }`).
60
76
  3. `useLeverageYieldShareBalances` consumers treat `data` as an array and aggregate.
61
- 4. Withdraw flows do not gate on `useSwapAllowance`.
62
- 5. Mutation flows use `mutateAsyncSafe` and branch on `result.ok`; reads read `data` directly (no `.ok`/`.value`).
63
- 6. Positions: leverage changes use `useSubmitLeveragePositionIntent` (never `useRunLeveragePositionOperation`), `notified` is checked on every open and leverage change, and exits are sized from `useLeveragePositionCollateral` with the fee from `useLeveragePositionInfo`.
64
- 7. Positions: funding is gated on `useLeveragePositionFundingAllowance` + `useApproveLeveragePositionFunding`, and `borrowAmount` / `minCollateralOut` trace back to `sizeLeverageBorrow` + `projectLeverageLeg`.
77
+ 4. Every `minOutputAmount` is derived from a live `useLeverageYieldQuote` minus slippage; no `0n`, no unrequested `partnerFee`.
78
+ 5. Withdraw flows do not gate on `useSwapAllowance`.
79
+ 6. Mutation flows use `mutateAsyncSafe` and branch on `result.ok`; reads read `data` directly (no `.ok`/`.value`), except `useLeverageYieldQuote` and `useLeverageYieldDetailedStatus`, whose `data` is the SDK `Result` (branch on `data?.ok`).
80
+ 7. Positions: leverage changes use `useSubmitLeveragePositionIntent` (never `useRunLeveragePositionOperation`), `notified` is checked on every open and leverage change, and exits are sized from `useLeveragePositionCollateral` with the fee from `useLeveragePositionInfo`.
81
+ 8. Positions: funding is gated on `useLeveragePositionFundingAllowance` + `useApproveLeveragePositionFunding`, and `borrowAmount` / `minCollateralOut` trace back to `sizeLeverageBorrow` + `projectLeverageLeg`.
65
82
 
66
83
  ## Related granular skills (same family)
67
84
 
68
- - [`../swap/SKILL.md`](../swap/SKILL.md) — `useSwapApprove` / `useSwapAllowance` (spoke-side deposit approval) and `useQuote` (size `minOutputAmount`) live here.
85
+ - [`../swap/SKILL.md`](../swap/SKILL.md) — `useSwapApprove` / `useSwapAllowance` (spoke-side deposit approval) live here. Size `minOutputAmount` with `useLeverageYieldQuote`, not the swap skill's `useQuote`.
69
86
  - [`../auxiliary-services/SKILL.md`](../auxiliary-services/SKILL.md) — `useXBalances` / gas-estimation utilities used alongside leverage-yield UI.
70
87
 
71
- For multi-feature tasks, load the broad [`sodax-dapp-kit` skill](../SKILL.md).
88
+ For multi-feature tasks, load the broad [`sodax-dapp-kit` skill](../SKILL.md). The backend REST hooks (`useLeverageYieldApi*`) are a different surface, documented in the Leverage Yield API section of [`../integration/knowledge/features/auxiliary-services.md`](../integration/knowledge/features/auxiliary-services.md) (granular skill: [`../auxiliary-services/SKILL.md`](../auxiliary-services/SKILL.md)).
72
89
 
73
90
  ## Wallet connectivity (different SDK package family)
74
91
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: sodax-dapp-kit-swap
3
- description: 'Granular skill for the @sodax/dapp-kit v2 swap feature only — React Query hooks for intent-based cross-chain swaps via the solver: useSwap, useQuote, useSwapAllowance, useSwapApprove, useStatus, useCreateLimitOrder, useCancelSwap, useCancelLimitOrder. Use when a React dapp has decided the task is a swap (e.g. "useSwap with dapp-kit", "Sodax React swap hook", "limit order hook", "poll swap status", "cancel a Sodax intent in React") and you want to skip loading the broad sodax-dapp-kit skill. Covers BOTH integration (write new v2 hooks) and migration (port v1 swap hooks to v2 — single-object params, mutateAsyncSafe, hook-owned invalidations). Picks via Step 1. Links into the parent sodax-dapp-kit knowledge tree. For backend/Node swaps (no React), use the sodax-sdk skill instead.'
3
+ description: 'Granular skill for the @sodax/dapp-kit v2 swap feature only — React Query hooks for intent-based cross-chain swaps via the solver: useSwapLifecycle, useSwap, useSwapWithApproval, useSwapApprovalStrategy, useQuote, useSwapAllowance, useSwapApprove, useDetailedStatus, useStatus, useCreateLimitOrder, useCancelSwap, useCancelLimitOrder. Use when a React dapp has decided the task is a swap (e.g. "useSwap with dapp-kit", "Sodax React swap hook", "limit order hook", "poll swap status", "cancel a Sodax intent in React") and you want to skip loading the broad sodax-dapp-kit skill. Covers BOTH integration (write new v2 hooks) and migration (port v1 swap hooks to v2 — single-object params, mutateAsyncSafe, hook-owned invalidations). Picks via Step 1. Links into the parent sodax-dapp-kit knowledge tree. For backend/Node swaps (no React), use the sodax-sdk skill instead.'
4
4
  license: MIT
5
5
  metadata:
6
6
  version: '0.0.1'
@@ -16,7 +16,7 @@ Granular skill for the swap hooks of `@sodax/dapp-kit` v2. React-only — backen
16
16
  1. **New code or v1 → v2 port?**
17
17
  - New → § Integration workflow.
18
18
  - Port v1 → § Migration workflow.
19
- 2. **Which hooks?** Quote/preview (`useQuote`), execute (`useSwap`), allowance gate (`useSwapAllowance` + `useSwapApprove`), status polling (`useStatus`), or limit orders (`useCreateLimitOrder` / `useCancelLimitOrder`).
19
+ 2. **Which hooks?** A whole swap form → `useSwapLifecycle` (one `state` + `next()`; the hooks below are its parts and stay available). Otherwise: quote/preview (`useQuote`), execute (`useSwap`, or `useSwapWithApproval` to fold the approval in — one EIP-5792 signature where the wallet can batch; `useSwapApprovalStrategy` labels it; `allowAccountUpgrade: false` keeps a wallet that would ask for a smart-account upgrade on the two-step path), allowance gate (`useSwapAllowance` + `useSwapApprove`), status polling (`useDetailedStatus` from the source tx — the default; `useStatus` only when you hold the hub tx hash), or limit orders (`useCreateLimitOrder` / `useCancelLimitOrder`).
20
20
  3. **Market order or limit order?** Limit orders use `useCreateLimitOrder` (no `deadline`; cancel manually via `useCancelLimitOrder`).
21
21
  4. **Imperative flow or render-driven?** Sequenced flows → `mutateAsyncSafe` (returns `Result<T>`, never rejects). Fire-and-forget → `mutate`.
22
22
 
@@ -33,7 +33,7 @@ Granular skill for the swap hooks of `@sodax/dapp-kit` v2. React-only — backen
33
33
  - **Treating `useSwap` `data` as `Result<T>`.** The hook's `mutationFn` unwraps before resolving — `data` is the success value (`SwapResponse = { intent, intentDeliveryInfo, solverExecutionResponse }`). For SDK `!ok` read `mutation.error` or use `mutateAsyncSafe` for the `Result<T>` shape.
34
34
  - **Passing the SDK request directly under `params` on `useQuote`.** It nests under `params.payload` (a `SolverIntentQuoteRequest`). `useSwapAllowance` nests `payload` + `srcChainKey` + `walletProvider` under `params`.
35
35
  - **Reading `data.status` on `useQuote` / `useStatus` without `data?.ok`.** Both return a `Result<…>` as their `data` — branch on `.ok` first. (`useSwapAllowance` is the opposite — already-unwrapped `boolean`.)
36
- - **`useStatus` key is `intentTxHash`, not `intentHash`.**
36
+ - **`useStatus` key is `intentTxHash`, not `intentHash`.** It needs the **hub** tx; for a status from what `swap()` returns use `useDetailedStatus({ params: { srcChainKey, srcTxHash } })`.
37
37
  - **Flattening `getSupportedSwapTokens()` and keying rows on `address`.** The same token address recurs across chains — use a composite `${address}-${chainKey}` key (`XToken` carries `chainKey`, not `blockchain_id`).
38
38
  - **Reaching for `useSpokeProvider`.** Deleted. Pass `walletProvider` into `mutate(vars)` for `useSwap`/`useSwapApprove`; cancel hooks take it flat.
39
39
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: sodax-sdk
3
- description: 'Integrate SODAX cross-chain DeFi into a backend, Node script, bot, indexer, or non-React app with @sodax/sdk — swaps, lending/borrowing, staking, bridging, concentrated-liquidity DEX, ICX/bnUSD/BALN token migration, partner fees, and stuck-asset recovery across Sonic (hub) + 20 spoke chains. INTEGRATION (write NEW v2 code) — hub-and-spoke architecture across EVM and non-EVM chains; covers intent-based swaps, lending/borrowing (money market), staking, bridging, concentrated-liquidity DEX, token migration, partner fees, and stuck-asset recovery. Use whenever a non-React or backend codebase calls `@sodax/sdk` directly (Node scripts, indexers, bots, server APIs, custom non-React browser flows). Triggers on "use @sodax/sdk", "swap with Sodax", "Sodax bridge", "Sodax money market", "Sodax staking", "cross-chain DeFi", "Sonic hub", any `Sodax` / `ChainKeys` / `Result<T>` / `SodaxError` symbol. For React dapps, prefer `sodax-dapp-kit` instead. MIGRATION (port v1 → v2) — the v2 reshape replaced `*SpokeProvider` classes with chain-key-driven routing, throws with `Result<T>`, module-specific error unions with `SodaxError<C>`, ad-hoc wallet/raw branching with `WalletProviderSlot<K, Raw>`, and static lookup tables with `ConfigService`. Triggers on "migrate Sodax v1", "upgrade @sodax/sdk", "v1 → v2", "useSpokeProvider broken", "Sodax error types changed", v1 fingerprints (`_MAINNET_CHAIN_ID`, `*SpokeProvider`, `xChainId`, `SpokeChainId`, `MoneyMarketError`/`IntentError`/`StakingError`/`BridgeError`/`MigrationError`/`AssetServiceError`/`ConcentratedLiquidityError`/`RelayError`). Load this skill if EITHER applies; the body gates by mode.'
3
+ description: 'Integrate SODAX cross-chain DeFi into a backend, Node script, bot, indexer, or non-React app with @sodax/sdk — intent-based swaps and limit orders, money market lending/borrowing, staking, bridging, concentrated-liquidity DEX, leverage-yield vaults (lsoda* deposit/withdraw, vault APR) and leverage positions, ICX/bnUSD/BALN token migration, partner fees, stuck-asset recovery, Stellar sponsoring, and the typed backend API clients, with Sonic as the hub. INTEGRATION (write NEW v2 code) — use whenever non-React code calls `@sodax/sdk` directly. Triggers on "use @sodax/sdk", "swap with Sodax", "Sodax bridge", "Sodax money market", "Sodax staking", "leverage yield vault", "sodax.leverageYield", "cross-chain DeFi", "Sonic hub", any `Sodax` / `ChainKeys` / `Result<T>` / `SodaxError` symbol. React dapps: prefer `sodax-dapp-kit`. MIGRATION (port v1 → v2) — v2 replaced `*SpokeProvider` classes with chain-key-driven routing, throws with `Result<T>`, module-specific error unions with `SodaxError<C>`, ad-hoc wallet/raw branching with `WalletProviderSlot<K, Raw>`, and static lookup tables with `ConfigService`. Triggers on "migrate Sodax v1", "upgrade @sodax/sdk", "v1 → v2", "useSpokeProvider broken", "Sodax error types changed", v1 fingerprints (`_MAINNET_CHAIN_ID`, `*SpokeProvider`, `xChainId`, `SpokeChainId`, `MoneyMarketError`/`IntentError`/`StakingError`/`BridgeError`/`MigrationError`/`AssetServiceError`/`ConcentratedLiquidityError`/`RelayError`). Load this skill if EITHER applies; the body gates by mode.'
4
4
  license: MIT
5
5
  metadata:
6
6
  version: '0.0.1'
@@ -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 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
+ | Leverage-yield vaults (lsoda* deposit/withdraw, vault APR, `listVaults`) and leverage positions | [`./leverage-yield/SKILL.md`](./leverage-yield/SKILL.md) | "leverage yield vault", "deposit into a vault", "sodax.leverageYield", "open a leverage position" |
39
40
  | Leverage Yield API client (vault reads, APR, deposit/withdraw quote + intents) | [`./leverage-yield-api/SKILL.md`](./leverage-yield-api/SKILL.md) | "sodax.api.leverageYield", "vault APR from backend", "vault position from API", "leverage-yield API v2" |
40
41
  | Bridge API 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" |
41
42
 
@@ -16,7 +16,8 @@ Granular skill for `BridgeService` — `sodax.bridge`. Feature tag: `'bridge'`.
16
16
  1. **New code or v1 → v2 port?**
17
17
  2. **Signed flow (frontend) or unsigned-tx (backend)?**
18
18
  3. **Need a bridgeable-amount precheck?** Vault deposit limits may cap the transfer; `getBridgeableAmount` (or equivalent) read tells you the cap before submitting.
19
- 4. **Source / destination chains** — confirm both are supported spoke chains, and the destination address format matches the chain (vd Stellar address starts with `G`, Solana base58, Bitcoin specific encodings).
19
+ 4. **One signature?** `bridgeWithApproval` folds the approval in (one EIP-5792 batch when the wallet can); `getApprovalStrategy` labels the button first. Plain `bridge()` expects the allowance to be set already.
20
+ 5. **Source / destination chains** — confirm both are supported spoke chains, and the destination address format matches the chain (vd Stellar address starts with `G`, Solana base58, Bitcoin specific encodings).
20
21
 
21
22
  ## Integration workflow
22
23
 
@@ -32,6 +33,7 @@ Granular skill for `BridgeService` — `sodax.bridge`. Feature tag: `'bridge'`.
32
33
 
33
34
  - **Destructuring the return as an array or single hash.** v2 ALWAYS returns `{ srcChainTxHash, dstChainTxHash }` for cross-chain mutations — destructure by name.
34
35
  - **Skipping the bridgeable-amount check.** Submitting an amount over the vault cap returns `EXECUTION_FAILED`; cheaper to check first.
36
+ - **Reporting a bridge as lost, or calling `bridge()` again, on a post-broadcast failure.** `TX_VERIFICATION_FAILED` and the relay codes carry `error.context.srcTxHash` — the deposit is on-chain and may still deliver, so keep polling `getDetailedStatus` with it. A second `bridge()` is a second deposit. After `TX_SUBMIT_FAILED`, if no packet ever shows up, resubmit that same tx to the relay with `submitTransaction`.
35
37
 
36
38
  ## Migration workflow (v1 → v2)
37
39
 
@@ -37,6 +37,9 @@ DO / DO NOT / workflow / stop conditions for AI agents writing `@sodax/sdk` v2 c
37
37
  - **DO NOT** call `getStakeRatio` and treat its return as `Result<bigint>`. It's `Result<[xSodaAmount, previewDepositAmount]>` — a tuple of two bigints.
38
38
  - **DO NOT** assume `BalnSwapService` lock-management methods (`stake`, `unstake`, `claim`, `claimUnstaked`, `cancelUnstake`, `getDetailedUserLocks`) return `Result<T>`. They still throw on error in v2 — known carve-out. Wrap them in `try/catch`.
39
39
  - **DO NOT** call methods that need a wallet provider with `raw: true` — TypeScript rejects `walletProvider` when `raw: true`. Use `raw: false` + `walletProvider`, or stick to read methods.
40
+ - **DO NOT** send a zero or hand-picked minimum output (`minOutputAmount: 0n` or a literal). Derive it from a live quote for that exact input minus a slippage tolerance in basis points, show both to the user before they sign, and disable the action while there is no quote. The SDK does not reject a zero minimum (swaps and bridge only enforce the 546-sat dust floor on a BTC payout); a zero minimum accepts any fill.
41
+ - **DO NOT** add a `partnerFee` the integrator did not ask for. It is optional; omit it by default, and never copy a fee receiver address from a SODAX demo, doc, or example.
42
+ - **DO NOT** pass `skipSimulation: true` in user-facing flows. The simulation replays the hub-side execution and catches an intent that would revert there before the user signs it.
40
43
 
41
44
  ## Stop conditions (defer to user)
42
45
 
@@ -474,7 +474,7 @@ Use these in cross-bundle code (apps with mixed ESM/CJS resolution, monorepos wi
474
474
  Cross-chain coordination is exposed as two top-level functions (re-exported from `@sodax/sdk`'s barrel):
475
475
 
476
476
  - `submitTransaction(payload, apiUrl)` — TWO positional args: `payload: IntentRelayRequest<'submit'>` and `apiUrl: HttpUrl` (not an options object). POSTs the spoke transaction to the relay submit endpoint and resolves the relay's first-stage acknowledgement.
477
- - `relayTxAndWaitPacket({ srcTxHash, data, chainKey, relayerApiEndpoint, timeout, pollTxHash? })` — `RelayAndWaitParams`: `data` is the whole `RelayExtraData` / `OnDemandRelayData` object and `chainKey` is the source `SpokeChainKey`. Runs `submitTransaction` and then polls until the destination packet reaches `executed`.
477
+ - `relayTxAndWaitPacket({ srcTxHash, data?, chainKey, relayerApiEndpoint, timeout, pollTxHash? })` — `RelayAndWaitParams`: `data` is the whole `RelayExtraData` / `OnDemandRelayData` object, required for Solana and Bitcoin (any other chain's tx is relayed by its hash), and `chainKey` is the source `SpokeChainKey`. Runs `submitTransaction` and then polls until the destination packet reaches `executed`.
478
478
 
479
479
  These functions are **not** exposed on the `Sodax` instance. Consumers don't call them directly — every feature service (`swaps.swap`, `bridge.bridge`, `staking.stake`, …) wraps the spoke→hub leg internally. If you genuinely need custom relay orchestration (rare), import `relayTxAndWaitPacket` / `submitTransaction` from `@sodax/sdk` and pass the same `relayerApiEndpoint` your `Sodax` instance uses.
480
480
 
@@ -76,9 +76,11 @@ an allowance change from one non-zero value to another (the 2017 TetherToken lin
76
76
  wallet already holds a stale allowance — a wallet in that state cannot approve at all until it is
77
77
  zeroed.
78
78
 
79
- Broadcast `resetTx` first and wait for it to be mined, then broadcast `tx`. The two cannot be
80
- batched: the approval is only valid once the reset has landed on-chain. Submitting `tx` while a
81
- non-zero stale allowance remains is a guaranteed revert.
79
+ Broadcast `resetTx` first and wait for it to be mined, then broadcast `tx`. As separate transactions
80
+ they cannot go out together: the approval is only valid once the reset has landed on-chain. An
81
+ EIP-5792 atomic batch is different — it runs its calls in order, so it can carry both (the SDK's
82
+ `bridgeWithApproval` does, see `bridge.md`). Submitting `tx` while a non-zero stale allowance
83
+ remains is a guaranteed revert.
82
84
 
83
85
  ```ts
84
86
  const { tx, resetTx } = approveResponse;
@@ -14,6 +14,10 @@ A bridge call deposits the source token into its vault on the hub, then triggers
14
14
 
15
15
  ```ts
16
16
  sodax.bridge.bridge<K>(action: BridgeParams<K, false>): Promise<Result<TxHashPair, SodaxError>>;
17
+ // bridge() with the approval folded in: one EIP-5792 batch (one signature) when the wallet can, else approve → wait → bridge.
18
+ sodax.bridge.bridgeWithApproval<K>(action: BridgeWithApprovalParams<K>): Promise<Result<BridgeWithApprovalResponse, SodaxError>>;
19
+ // 'not-required' | 'atomic-batch' | 'sequential' — the path bridgeWithApproval would take; label the button with it.
20
+ sodax.bridge.getApprovalStrategy<K>(action: BridgeWithApprovalParams<K>): Promise<Result<ApprovalStrategy, SodaxError>>;
17
21
  sodax.bridge.createBridgeIntent<K, Raw>(action: BridgeParams<K, Raw>): Promise<Result<IntentTxResult<K, Raw>, SodaxError>>;
18
22
  sodax.bridge.approve<K, Raw>(args): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
19
23
  // Unsigned callers only: returns both transactions when a stale allowance must be cleared first.
@@ -228,11 +232,15 @@ different contract on the hub.
228
232
  | Method | Codes | `error.context` |
229
233
  |---|---|---|
230
234
  | `bridge` | full exec set | `action: 'bridge'` |
235
+ | `bridgeWithApproval` | `bridge`'s codes + `APPROVE_FAILED`, `ALLOWANCE_CHECK_FAILED` | approval-step errors: `action: 'bridgeWithApproval'`, `approvalStrategy` (after the broadcast, `bridge()`'s own context); a batch that may still land is `TX_VERIFICATION_FAILED` with `reason: ATOMIC_BATCH_UNCONFIRMED` — never bridge it again; call again with `resumeBatchId: context.batchId, resumeBatchCallCount: context.callCount`, which sends nothing and relays the deposit once the batch lands |
236
+ | `getApprovalStrategy` | `VALIDATION_FAILED`, `ALLOWANCE_CHECK_FAILED`, `UNKNOWN` (`isAllowanceValid`'s) | `action: 'bridgeWithApproval'` |
231
237
  | `createBridgeIntent` | `VALIDATION_FAILED`, `INTENT_CREATION_FAILED`, `UNKNOWN` | `action: 'bridge'` |
232
238
  | `approve` | `VALIDATION_FAILED`, `APPROVE_FAILED`, `UNKNOWN` | n/a |
233
239
  | `isAllowanceValid` | `VALIDATION_FAILED`, `ALLOWANCE_CHECK_FAILED`, `UNKNOWN` | n/a |
234
240
  | `getBridgeableAmount`, `getBridgeableTokens` | `VALIDATION_FAILED`, `LOOKUP_FAILED`, `UNKNOWN` | `method: 'getBridgeableAmount' \| 'getBridgeableTokens'` |
235
241
 
242
+ **A `bridge()` failure after broadcast still carries the source tx.** `TX_VERIFICATION_FAILED` and the relay codes set `error.context.srcTxHash` (plus `srcChainKey`). The deposit is on-chain and the bridge may still complete — a slow relay can deliver late, and on the default backend path the backend keeps working after `bridge()` gives up — so keep polling `getDetailedStatus` with it instead of reporting the bridge as lost or retrying `bridge()`. Failures before the broadcast carry no `srcTxHash`. After `TX_SUBMIT_FAILED`, if the backend did not take the deposit (submit-tx off or rejected) nothing else submits it: when no packet ever shows up, resubmit the same tx with `submitTransaction({ action: 'submit', params: { chain_id, tx_hash } }, relayerApiEndpoint)` — the relay ignores a tx it already has. A Solana or Bitcoin source also needs the original `relayData`, which `bridge()` does not return.
243
+
236
244
  ## Cross-references
237
245
 
238
246
  - v1 → v2 bridge migration: [`features/bridge.md`](../../../migration-v1-to-v2/knowledge/features/bridge.md).