@sodax/skills 2.2.0 → 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 (55) hide show
  1. package/AGENTS.md +7 -7
  2. package/README.md +5 -5
  3. package/package.json +4 -4
  4. package/skills/sodax-build/SKILL.md +1 -1
  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/auxiliary-services/SKILL.md +4 -1
  11. package/skills/sodax-dapp-kit/bridge/SKILL.md +1 -1
  12. package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +18 -4
  13. package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +23 -1
  14. package/skills/sodax-dapp-kit/integration/knowledge/features/bridge.md +8 -0
  15. package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +4 -2
  16. package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +24 -0
  17. package/skills/sodax-dapp-kit/integration/knowledge/recipes/bridge.md +2 -0
  18. package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +1 -0
  19. package/skills/sodax-dapp-kit/integration/knowledge/recipes/swap.md +141 -1
  20. package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +8 -0
  21. package/skills/sodax-dapp-kit/integration/knowledge/reference/public-api.md +1 -1
  22. package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +8 -0
  23. package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +2 -2
  24. package/skills/sodax-dapp-kit/swap/SKILL.md +3 -3
  25. package/skills/sodax-sdk/bridge/SKILL.md +3 -1
  26. package/skills/sodax-sdk/integration/knowledge/architecture.md +1 -1
  27. package/skills/sodax-sdk/integration/knowledge/features/bridge-api.md +5 -3
  28. package/skills/sodax-sdk/integration/knowledge/features/bridge.md +8 -0
  29. package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +24 -1
  30. package/skills/sodax-sdk/integration/knowledge/features/swap.md +68 -2
  31. package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +56 -2
  32. package/skills/sodax-sdk/integration/knowledge/reference/error-codes.md +27 -1
  33. package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +30 -1
  34. package/skills/sodax-sdk/leverage-yield/SKILL.md +2 -1
  35. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/architecture.md +1 -1
  36. package/skills/sodax-sdk/migration-v1-to-v2/knowledge/reference/sodax-config.md +9 -1
  37. package/skills/sodax-sdk/swap/SKILL.md +3 -1
  38. package/skills/sodax-sdk/swaps-api/SKILL.md +3 -2
  39. package/skills/sodax-wallet-sdk-core/evm/SKILL.md +2 -1
  40. package/skills/sodax-wallet-sdk-core/integration/knowledge/README.md +1 -1
  41. package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +6 -0
  42. package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/interfaces.md +4 -1
  43. package/skills/sodax-wallet-sdk-core/migration-v1-to-v2/knowledge/README.md +1 -1
  44. package/skills/sodax-wallet-sdk-react/SKILL.md +5 -3
  45. package/skills/sodax-wallet-sdk-react/integration/knowledge/README.md +2 -1
  46. package/skills/sodax-wallet-sdk-react/integration/knowledge/ai-rules.md +2 -0
  47. package/skills/sodax-wallet-sdk-react/integration/knowledge/architecture.md +10 -6
  48. package/skills/sodax-wallet-sdk-react/integration/knowledge/examples/05-privy-email-login.tsx +157 -0
  49. package/skills/sodax-wallet-sdk-react/integration/knowledge/examples/README.md +1 -0
  50. package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/privy-email-login.md +111 -0
  51. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/api-surface.md +14 -0
  52. package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/chain-support.md +1 -1
  53. package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/README.md +1 -1
  54. package/skills/sodax-wallet-sdk-react/privy/SKILL.md +53 -0
  55. 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
 
@@ -107,6 +112,8 @@ No hook lists the vaults: read the registry with `useSodaxContext().sodax.levera
107
112
  |---|---|---|
108
113
  | `useLeverageYieldDeposit` | Mutation | Build a deposit payload (any token → `lsoda*` shares) — spread into `useLeverageYieldVaultSwap` |
109
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 |
110
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 |
111
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 |
112
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` |
@@ -212,6 +219,7 @@ Typed React Query wrappers over the backend Swaps API (`sodax.api.swaps.*`), one
212
219
  |---|---|
213
220
  | `useSwapsApiApprove` | Mutation; builds unsigned approval tx(s) — `{ tx, resetTx? }`, caller signs |
214
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) |
215
223
  | `useSwapsApiCreateIntent` | Mutation; builds `{ tx, intent, relayData }` |
216
224
  | `useSwapsApiSubmitIntent` | Mutation; submits broadcast intent to the relay |
217
225
  | `useSwapsApiCancelIntent` | Mutation; builds unsigned cancel tx |
@@ -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,7 +16,7 @@ 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`).
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
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
21
  5. **Which reads?** `useLeverageYieldEffectiveApr` (headline APR), `useLeverageYieldPosition` (LTV/health), `useLeverageYieldTotalAssets` (TVL), `useLeverageYieldPreviewRedeem` (price-per-share), `useLeverageYieldShareBalances` (per-chain balances — returns an array).
22
22
 
@@ -41,7 +41,7 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
41
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.
42
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`.
43
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`.
44
- - **Reaching for a `useLeverageYieldApprove` hook.** It doesn't exist — the deposit approves the spoke asset manager, so use the swap-domain hooks.
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
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
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
47
  - **Labelling `leverageMultiplierWad` as "Leverage".** It is the borrowed multiple, `targetLTV / (1 − targetLTV)`; exposure is `1 + multiplier`. `targetLtvBps` and `position.ltv` are basis points.
@@ -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
 
@@ -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
 
@@ -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).
@@ -31,6 +31,10 @@ sodax.leverageYield.withdraw(params: LeverageYieldSwapWithdrawParams): Promise<R
31
31
  // Intent create + end-to-end execute (leverage-yield copies of swap's createIntent / swap)
32
32
  sodax.leverageYield.createVaultIntent<K, Raw>(params: VaultSwapActionParams<K, Raw>): Promise<Result<CreateVaultIntentResult<K, Raw>, SodaxError>>;
33
33
  sodax.leverageYield.vaultSwap<K>(params: VaultSwapActionParams<K, false>): Promise<Result<VaultSwapResponse, SodaxError>>;
34
+ // vaultSwap() with a deposit's spoke-side approval folded in: one EIP-5792 batch (one signature) when the wallet can.
35
+ // A withdraw (hubWalletSwap) needs no approval and runs as vaultSwap does.
36
+ sodax.leverageYield.vaultSwapWithApproval<K>(params: VaultSwapWithApprovalParams<K>): Promise<Result<VaultSwapWithApprovalResponse, SodaxError>>;
37
+ sodax.leverageYield.getApprovalStrategy<K>(params: VaultSwapWithApprovalParams<K>): Promise<Result<ApprovalStrategy, SodaxError>>;
34
38
  sodax.leverageYield.notifySolver(request: { intent_tx_hash: string }): Promise<Result<SolverExecutionResponse, SodaxError>>;
35
39
  // notifySolver is PUBLIC — call it to finish a manual createVaultIntent → relay → notify flow
36
40
 
@@ -110,6 +114,8 @@ type DetailedLeverageYieldStatus =
110
114
  // On failure: LOOKUP_FAILED. A rejected key stops there with context.status set (isAuthFailure) —
111
115
  // never routed on. Otherwise branch on error.context.reason: DETAILED_STATUS_NOT_DELIVERED is the one
112
116
  // ambiguous miss a caller should bound with a retry budget; anything else is a live dependency failure.
117
+ // Same shape as DetailedSwapStatus, so swap's pure summarizeSwapStatus(status) collapses it to
118
+ // { state: 'pending' | 'solved' | 'failed', hubTxHash?, fillTxHash? }.
113
119
  ```
114
120
 
115
121
  ## Common call shapes
@@ -164,6 +170,19 @@ if (!result.ok) return;
164
170
  const { solverExecutionResponse, intent, intentDeliveryInfo } = result.value;
165
171
  ```
166
172
 
173
+ Or replace the allowance check, the approval and `vaultSwap` with one call. On an EIP-5792 wallet the approval and the
174
+ deposit go out as one batch, so the user signs once; it approves the same spender and keeps the leverage-yield fee and
175
+ the backend `operation`:
176
+
177
+ ```ts
178
+ const result = await sodax.leverageYield.vaultSwapWithApproval({ ...built.value, walletProvider });
179
+ // result.value.approvalStrategy: 'not-required' | 'atomic-batch' | 'sequential'
180
+ ```
181
+
182
+ A `TX_VERIFICATION_FAILED` with `context.reason === ATOMIC_BATCH_UNCONFIRMED` means the batch may still land — do not
183
+ deposit again. Call it again with `resumeBatchId: context.batchId` and `resumeBatchCallCount: context.callCount`: that
184
+ sends nothing, and once the batch lands it relays the deposit and notifies the solver.
185
+
167
186
  ### Withdraw (`lsoda*` → any token)
168
187
 
169
188
  ```ts
@@ -233,7 +252,7 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
233
252
 
234
253
  ## Error codes
235
254
 
236
- `feature: 'leverageYield'`. Action discriminator on `context.action`: `'deposit' | 'withdraw' | 'approve' | 'allowanceCheck' | 'vaultSwap' | 'openPosition' | 'openPositionFromDebtToken' | 'operatePosition' | 'openLeveragePosition' | 'submitLeveragePositionIntent' | 'runLeveragePositionOperation' | 'getPositionLegQuote'`. Read methods partition on `context.method`.
255
+ `feature: 'leverageYield'`. Action discriminator on `context.action`: `'deposit' | 'withdraw' | 'approve' | 'allowanceCheck' | 'vaultSwap' | 'vaultSwapWithApproval' | 'openPosition' | 'openPositionFromDebtToken' | 'operatePosition' | 'openLeveragePosition' | 'submitLeveragePositionIntent' | 'runLeveragePositionOperation' | 'getPositionLegQuote'`. Read methods partition on `context.method`.
237
256
 
238
257
  | Method | Narrow code union |
239
258
  |---|---|
@@ -241,6 +260,8 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
241
260
  | `deposit`, `withdraw` | `VALIDATION_FAILED \| INTENT_CREATION_FAILED \| LOOKUP_FAILED \| UNKNOWN` (create-intent subset + `LOOKUP_FAILED` with `method: 'resolveDeadline'` when the default-deadline hub-block read fails) |
242
261
  | `createVaultIntent` | `VALIDATION_FAILED \| INTENT_CREATION_FAILED \| UNKNOWN` (create-intent subset) |
243
262
  | `vaultSwap` | `VALIDATION_FAILED \| INTENT_CREATION_FAILED \| TX_VERIFICATION_FAILED \| TX_SUBMIT_FAILED \| RELAY_TIMEOUT \| RELAY_FAILED \| EXECUTION_FAILED \| EXTERNAL_API_ERROR \| UNKNOWN` |
263
+ | `vaultSwapWithApproval` | `vaultSwap`'s codes + `APPROVE_FAILED \| ALLOWANCE_CHECK_FAILED` (approval-step errors carry action `'vaultSwapWithApproval'`; after the broadcast, `vaultSwap`'s own context) |
264
+ | `getApprovalStrategy` | `ALLOWANCE_CHECK_FAILED` |
244
265
  | `notifySolver` | `EXECUTION_FAILED \| EXTERNAL_API_ERROR \| UNKNOWN` (with `phase: 'postExecution'`) |
245
266
  | `approve` | `VALIDATION_FAILED \| APPROVE_FAILED \| UNKNOWN` |
246
267
  | `isAllowanceValid` | `VALIDATION_FAILED \| ALLOWANCE_CHECK_FAILED \| UNKNOWN` (action `'allowanceCheck'`) |
@@ -253,6 +274,8 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
253
274
 
254
275
  Relay/tx-verification codes appear **only** on `vaultSwap` — `createVaultIntent` alone stays within the create-intent subset. `notifySolver` (public, for manual orchestration) emits the post-execution subset, which `vaultSwap` also surfaces.
255
276
 
277
+ **A `vaultSwap()` failure after broadcast still carries the source tx.** `TX_VERIFICATION_FAILED`, the relay codes and post-execution failures set `error.context.srcTxHash` (plus `srcChainKey`). The vault swap may still complete — on the default backend path the backend keeps working after `vaultSwap()` gives up — so keep polling `getDetailedStatus` with it instead of reporting the vault swap as lost. Failures before the broadcast carry no `srcTxHash`. A failed solver notification (`EXECUTION_FAILED` / `EXTERNAL_API_ERROR`, `phase: 'postExecution'`) also sets `error.context.dstTxHash`, the hub tx: unless the backend took the vault swap nothing else notifies the solver and the intent expires, so call `notifySolver({ intent_tx_hash: dstTxHash })` again, then poll.
278
+
256
279
  ## Leverage positions
257
280
 
258
281
  One AAVE account per position, cloned by `LeveragePositionFactory`. AAVE allows one eMode category per address, so a vault forces every depositor into one category and one leverage tier while an owner can hold several positions at different tiers at once. There is **no static registry** — discovery goes through the factory.
@@ -4,6 +4,19 @@ Intent-based swaps via a solver. Cross-chain by default.
4
4
 
5
5
  Access: `sodax.swaps`. Service class: `SwapService`. Feature tag for errors: `'swap'`.
6
6
 
7
+ ## Token environment
8
+
9
+ Use `getSupportedSolverTokens(chainKey)` for the packaged production list and
10
+ `getStagingSolverTokens(chainKey)` for production plus staging-only tokens.
11
+ `stagingSwapSupportedTokens` contains only the staging additions. These helpers do
12
+ not select a solver endpoint. `isSwapSupportedToken` accepts both tiers, so do not
13
+ use it to establish production readiness. Query the list for the environment the
14
+ integration targets instead of hardcoding symbols.
15
+
16
+ Staging membership does not imply money-market support. When a token has no
17
+ separate vault, its registry entry uses `vault === hubAsset` for the direct hub
18
+ asset. Canonical hub vault registration alone does not enable swaps or lending.
19
+
7
20
  ## How it works
8
21
 
9
22
  1. **Build an intent** — `createIntent` signs a spoke transaction encoding the swap declaration.
@@ -47,6 +60,18 @@ sodax.swaps.getCancelIntentRelayData(intent: Intent): Result<RelayExtraData>;
47
60
  sodax.swaps.approve<K, Raw>(/* … */): Promise<Result<TxReturnType<K, Raw>, SodaxError>>;
48
61
  sodax.swaps.isAllowanceValid<K, Raw>(/* … */): Promise<Result<boolean, SodaxError>>;
49
62
 
63
+ sodax.swaps.swapWithApproval<K extends SpokeChainKey>(
64
+ action: SwapActionParams<K, false>,
65
+ ): Promise<Result<SwapResponse & { approvalStrategy: SwapApprovalStrategy }, SodaxError>>;
66
+ // `swap` with the approval folded in: no approval when the allowance suffices; approve + deposit as ONE
67
+ // EIP-5792 atomic batch (one signature) on a batch-capable wallet + EVM spoke source; otherwise approve,
68
+ // wait for it to confirm, then swap. Same completion as `swap`. Adds APPROVE_FAILED / ALLOWANCE_CHECK_FAILED.
69
+
70
+ sodax.swaps.getApprovalStrategy<K extends SpokeChainKey>(
71
+ action: SwapActionParams<K, false>,
72
+ ): Promise<Result<SwapApprovalStrategy, SodaxError<'ALLOWANCE_CHECK_FAILED'>>>;
73
+ // SwapApprovalStrategy = 'not-required' | 'atomic-batch' | 'sequential' — read-only; use it to label the button.
74
+
50
75
  sodax.swaps.getSwapSpeedTier(params: { srcToken: XToken; dstToken: XToken }): SwapSpeedTierResult;
51
76
  // Synchronous, offline, no Result wrapper — estimates settlement speed from SDK config alone
52
77
  // (no network / on-chain / backend call). SwapSpeedTierResult = { tier: 'fast'|'normal'|'slow', estimatedSeconds }.
@@ -63,6 +88,37 @@ sodax.swaps.getDetailedStatus(
63
88
  // Routes to the backend submit-tx record or the solver. Does NOT define a new status vocabulary.
64
89
  ```
65
90
 
91
+ ## Approve and swap in one signature
92
+
93
+ `swapWithApproval` replaces the `isAllowanceValid` → `approve` → `swap` sequence with one call. It batches only
94
+ when the source is an EVM spoke (not the Sonic hub) and the wallet provider implements the optional EIP-5792 methods
95
+ (`EvmWalletProvider` does for a connected browser wallet, never for a private-key account) and reports
96
+ `'supported'` or `'ready'` for that chain — `'ready'` means the wallet asks the user to upgrade the account (MetaMask:
97
+ EIP-7702 smart account) on the first batch. Everything else takes the two-step path (three signatures for a token
98
+ that must reset a stale allowance), so the call is safe on any chain. Pass `allowAccountUpgrade: false` (to both
99
+ `getApprovalStrategy` and `swapWithApproval`) to keep a `'ready'` wallet on the two-step path and never show the
100
+ upgrade prompt; whether to do so is the app's call.
101
+
102
+ If the wallet refuses the batch before signing (e.g. EIP-5792 `5760`), the method approves separately on its own and
103
+ reports `approvalStrategy: 'sequential'`. Once the user has seen the batch it is never retried as separate
104
+ transactions:
105
+
106
+ - rejected batch → `USER_REJECTED`; a declined upgrade is `USER_REJECTED` with
107
+ `context.reason === ACCOUNT_UPGRADE_DECLINED` — the user refused the smart account, not the swap, so it is fine to
108
+ offer the same swap again with `allowAccountUpgrade: false`;
109
+ - batch never included or fully reverted (EIP-5792 `400` / `500`) → `INTENT_CREATION_FAILED` with
110
+ `context.reason: 'atomic-batch-failed'` (nothing deposited);
111
+ - anything else short of a confirmed deposit receipt (not confirmed within `timeout`, a partial revert, unclear
112
+ receipts) → `TX_VERIFICATION_FAILED` with `context.reason === ATOMIC_BATCH_UNCONFIRMED`, `context.batchId` and
113
+ `context.callCount`. It may have landed — **never send it again**; call `swapWithApproval` with the same `params`
114
+ and wallet plus `resumeBatchId: context.batchId` and `resumeBatchCallCount: context.callCount`, which only waits
115
+ for that batch and finishes the swap once it lands (the same unconfirmed error while it is still pending).
116
+
117
+ On the two-step path the intent is built unsigned before the approval, so invalid params fail before the user pays
118
+ for an approval.
119
+
120
+ Do not chain your own `approve` after any of these; that is exactly the double prompt this method avoids.
121
+
66
122
  ## Reading swap status
67
123
 
68
124
  Three readers. Pick by which transaction hash you hold:
@@ -71,18 +127,28 @@ Three readers. Pick by which transaction hash you hold:
71
127
  - **`sodax.swaps.getStatus({ intent_tx_hash })`** — the solver's view of one intent, keyed on the **hub** tx hash (`intentDeliveryInfo.dstTxHash`). Returns the legacy `SolverErrorResponse` error shape, so do not `switch (error.code)` on it.
72
128
  - **`sodax.swaps.getDetailedStatus({ srcChainKey, srcTxHash })`** — routes between the two, keyed on the **source** tx. Use this when you only have the source hash and do not know which path the swap took.
73
129
 
74
- `getDetailedStatus` defines no status of its own. It returns whichever source can answer, tagged, with that source's payload unmodified. The union is discriminated on `source` — no type guards are exported, narrow on the field:
130
+ `getDetailedStatus` defines no status of its own. It returns whichever source can answer, tagged. The backend record is unmodified; a solver answer short of `SOLVED`/`FAILED` is first checked against the backend's durable intent record, so a fill that consumed the remainder reads `SOLVED` and a cancelled intent with nothing filled reads `FAILED` (already refunded — do not offer a cancel). The union is discriminated on `source` — no type guards are exported, narrow on the field:
75
131
 
76
132
  ```ts
77
133
  type DetailedSwapStatus =
78
134
  | { source: 'backend'; data: SubmitTxStatusDataV2 } // same as getSubmitTxStatus
79
- | { source: 'solver'; dstTxHash: Hex; data: SolverIntentStatusResponse }; // same as getStatus
135
+ | { source: 'solver'; dstTxHash: Hex; data: SolverIntentStatusResponse }; // getStatus, reconciled
80
136
 
81
137
  if (status.source === 'backend') status.data.processingAttempts;
82
138
  ```
83
139
 
84
140
  Routing: backend record while it is in play (`success: true` and not abandoned) → `source: 'backend'`. **Any** unusable backend response — 404, `success: false`, transport/server error, or a record the backend gave up on (`failed` or `abandonedAt`) — resolves the hub tx hash and asks the solver → `source: 'solver'`. On the default path the abandoned-record branch is the common one, not the 404: the record usually exists, and abandonment is what signals the client-side fallback ran.
85
141
 
142
+ To render it without switching on `source`, collapse it with the pure `summarizeSwapStatus` (exported from `@sodax/sdk`):
143
+
144
+ ```ts
145
+ const { state, hubTxHash, fillTxHash } = summarizeSwapStatus(status); // state: 'pending' | 'solved' | 'failed'
146
+ ```
147
+
148
+ `fillTxHash` may be absent even when solved (the backend can confirm a fill from the on-chain journal without one).
149
+
150
+ **A `swap()` failure after broadcast still carries the source tx.** `TX_VERIFICATION_FAILED`, the relay codes and postExecution failures set `error.context.srcTxHash` (plus `srcChainKey`). The swap may still complete — the backend keeps working after `swap()` gives up — so keep polling `getDetailedStatus` with it instead of reporting the swap as lost. One case polling cannot fix: a failed solver notification (`EXECUTION_FAILED` / `EXTERNAL_API_ERROR`, `phase: 'postExecution'`) also sets `error.context.dstTxHash`, the hub tx. Unless the backend took the swap nothing else notifies the solver and the intent expires, so call `postExecution({ intent_tx_hash: dstTxHash })` again (the solver only re-affirms an intent it already has), then poll.
151
+
86
152
  The only error is `LOOKUP_FAILED`, meaning no source could answer — usually the relay has not delivered the packet, so there is no hub tx hash. When polling, branch on `error.context.reason`: `DETAILED_STATUS_NOT_DELIVERED` is the ambiguous miss (indistinguishable from "still in flight" — bound it with a retry budget), set only when the backend also answered. Anything else, including a relay miss behind a backend outage, is a dependency failing right now and should be retried until it recovers. A 401/403 from the backend does not route on at all — it surfaces directly with `context.status` lifted, so `isAuthFailure(error)` is true and polling should stop; only a corrected key changes the answer. Point-in-time — poll it yourself, or use dapp-kit's `useDetailedStatus`.
87
153
 
88
154
  ## Action params shape