@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.
- package/AGENTS.md +11 -10
- package/README.md +5 -5
- package/package.json +6 -5
- package/skills/sodax-build/SKILL.md +3 -3
- package/skills/sodax-build/knowledge/README.md +1 -1
- package/skills/sodax-build/knowledge/feature-catalog.md +4 -0
- package/skills/sodax-build/knowledge/glossary.md +1 -0
- package/skills/sodax-build/knowledge/handoff.md +3 -0
- package/skills/sodax-build/knowledge/interview-guide.md +1 -0
- package/skills/sodax-dapp-kit/SKILL.md +23 -5
- package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +4 -1
- package/skills/sodax-dapp-kit/bridge/SKILL.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/ai-rules.md +3 -0
- package/skills/sodax-dapp-kit/integration/knowledge/architecture.md +18 -4
- package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +31 -1
- package/skills/sodax-dapp-kit/integration/knowledge/features/bridge.md +8 -0
- package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +17 -3
- package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +24 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/README.md +1 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/bridge.md +2 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/dex.md +23 -8
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield-product-anatomy.md +150 -0
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +122 -38
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/swap.md +141 -1
- package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +14 -3
- package/skills/sodax-dapp-kit/integration/knowledge/reference/public-api.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +8 -0
- package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +27 -10
- package/skills/sodax-dapp-kit/swap/SKILL.md +3 -3
- package/skills/sodax-sdk/SKILL.md +2 -1
- package/skills/sodax-sdk/bridge/SKILL.md +3 -1
- package/skills/sodax-sdk/integration/knowledge/ai-rules.md +3 -0
- package/skills/sodax-sdk/integration/knowledge/architecture.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/features/bridge-api.md +5 -3
- package/skills/sodax-sdk/integration/knowledge/features/bridge.md +8 -0
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +81 -12
- package/skills/sodax-sdk/integration/knowledge/features/swap.md +68 -2
- package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +56 -2
- package/skills/sodax-sdk/integration/knowledge/reference/error-codes.md +27 -1
- package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +30 -1
- package/skills/sodax-sdk/leverage-yield/SKILL.md +16 -8
- package/skills/sodax-sdk/migration-v1-to-v2/knowledge/breaking-changes/architecture.md +1 -1
- package/skills/sodax-sdk/migration-v1-to-v2/knowledge/reference/sodax-config.md +9 -1
- package/skills/sodax-sdk/swap/SKILL.md +3 -1
- package/skills/sodax-sdk/swaps-api/SKILL.md +3 -2
- package/skills/sodax-wallet-sdk-core/SKILL.md +20 -2
- package/skills/sodax-wallet-sdk-core/evm/SKILL.md +2 -1
- package/skills/sodax-wallet-sdk-core/integration/knowledge/README.md +1 -1
- package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +6 -0
- package/skills/sodax-wallet-sdk-core/integration/knowledge/reference/interfaces.md +4 -1
- package/skills/sodax-wallet-sdk-core/migration-v1-to-v2/knowledge/README.md +1 -1
- package/skills/sodax-wallet-sdk-react/SKILL.md +20 -3
- package/skills/sodax-wallet-sdk-react/integration/knowledge/README.md +2 -1
- package/skills/sodax-wallet-sdk-react/integration/knowledge/ai-rules.md +2 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/architecture.md +10 -6
- package/skills/sodax-wallet-sdk-react/integration/knowledge/examples/05-privy-email-login.tsx +157 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/examples/README.md +1 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/privy-email-login.md +111 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/api-surface.md +14 -0
- package/skills/sodax-wallet-sdk-react/integration/knowledge/reference/chain-support.md +1 -1
- package/skills/sodax-wallet-sdk-react/migration-v1-to-v2/knowledge/README.md +1 -1
- package/skills/sodax-wallet-sdk-react/privy/SKILL.md +53 -0
- package/skills/sodax-wallet-sdk-react/wallet-modal/SKILL.md +1 -0
|
@@ -13,7 +13,7 @@ Access: `sodax.leverageYield`. Service class: `LeverageYieldService`. Feature ta
|
|
|
13
13
|
- A vault holds `asset` (a Sodax vault token like the weETH vault, `SodaTokens.sodaWEETH`) as collateral, borrows `borrowToken` (e.g. sodaETH) from the Sodax-forked AAVE pool, swaps it back into the asset, and re-supplies — to a `targetLTV`.
|
|
14
14
|
- The ERC-4626 **share token is the vault proxy address itself** (`lsoda*`). Holding shares = holding the leveraged position.
|
|
15
15
|
- **Deposit** = swap any spoke token → `lsoda*`, delivered to the user's **hub wallet** on Sonic. **Withdraw** = swap `lsoda*` (held in the hub wallet) → any token on any chain.
|
|
16
|
-
- **Steady-state APR**: `netAprRay = supplyAprRay + leverageMultiplier × (supplyAprRay − borrowAprRay)`, where `leverageMultiplier = targetLTV / (1 − targetLTV)`. Rates are RAY (`1e27`); the multiplier
|
|
16
|
+
- **Steady-state APR**: `netAprRay = supplyAprRay + leverageMultiplier × (supplyAprRay − borrowAprRay)`, where `leverageMultiplier = targetLTV / (1 − targetLTV)` — the **borrowed** multiple of equity (debt ÷ equity), not total exposure. Exposure (collateral ÷ equity) is `1 + leverageMultiplier` = `1 / (1 − targetLTV)`: at `targetLtvBps` 8200 that is 4.56× borrowed, 5.56× exposure, so a UI label reading "Leverage" shows `1 + multiplier`. Rates are RAY (`1e27`); the multiplier and `healthFactor` are WAD (`1e18`); `targetLtvBps` and the position `ltv` are basis points (`10_000` = 100%). `netAprRay` goes **negative** when the borrow rate exceeds supply — for LSD-backed vaults the LSD's native staking yield (folded in by `getEffectiveApr`) is the real alpha.
|
|
17
17
|
|
|
18
18
|
## Public methods
|
|
19
19
|
|
|
@@ -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
|
|
|
@@ -40,7 +44,7 @@ sodax.leverageYield.getDetailedStatus(key: { srcChainKey, srcTxHash }, config?:
|
|
|
40
44
|
Promise<Result<DetailedLeverageYieldStatus, SodaxError>>;
|
|
41
45
|
sodax.leverageYield.getIntentStatus(request: { intent_tx_hash: string }): Promise<Result<SolverIntentStatusResponse, SodaxError>>;
|
|
42
46
|
|
|
43
|
-
// Sonic-direct allowance for the vault's underlying asset
|
|
47
|
+
// Sonic-direct allowance for the vault's underlying asset — NOT the deposit approval (that is sodax.swaps.isAllowanceValid / approve)
|
|
44
48
|
sodax.leverageYield.approve<R>(params: LeverageYieldApproveParams<R>): Promise<Result<TxReturnType<HubChainKey, R>, SodaxError>>;
|
|
45
49
|
sodax.leverageYield.isAllowanceValid(params: LeverageYieldAllowanceParams): Promise<Result<boolean, SodaxError>>;
|
|
46
50
|
|
|
@@ -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
|
|
@@ -117,39 +123,98 @@ type DetailedLeverageYieldStatus =
|
|
|
117
123
|
### Deposit (any token → `lsoda*`)
|
|
118
124
|
|
|
119
125
|
```ts
|
|
126
|
+
const srcChainKey = ChainKeys.ARBITRUM_MAINNET;
|
|
127
|
+
const inputToken = '0x…weETHonArbitrum';
|
|
128
|
+
const inputAmount = parseUnits('1', 18);
|
|
129
|
+
const SLIPPAGE_BPS = 100n; // 1%; take it from the user, capped
|
|
130
|
+
|
|
131
|
+
// Size the minimum from a live quote: vault as token_dst. Never ship 0n — that accepts any fill.
|
|
132
|
+
const quote = await sodax.leverageYield.getQuote({
|
|
133
|
+
token_src: inputToken,
|
|
134
|
+
token_src_blockchain_id: srcChainKey,
|
|
135
|
+
token_dst: vault.vault,
|
|
136
|
+
token_dst_blockchain_id: ChainKeys.SONIC_MAINNET,
|
|
137
|
+
amount: inputAmount,
|
|
138
|
+
quote_type: 'exact_input',
|
|
139
|
+
});
|
|
140
|
+
if (!quote.ok) return;
|
|
141
|
+
const minOutputAmount = (quote.value.quoted_amount * (10_000n - SLIPPAGE_BPS)) / 10_000n;
|
|
142
|
+
|
|
120
143
|
const built = await sodax.leverageYield.deposit({
|
|
121
144
|
vault: vault.vault,
|
|
122
|
-
srcChainKey
|
|
145
|
+
srcChainKey,
|
|
123
146
|
srcAddress: '0x…',
|
|
124
|
-
inputToken
|
|
125
|
-
inputAmount
|
|
126
|
-
minOutputAmount
|
|
127
|
-
partnerFee: { address: '0x…', percentage: 100 }, // optional 1% per-intent fee
|
|
147
|
+
inputToken,
|
|
148
|
+
inputAmount,
|
|
149
|
+
minOutputAmount,
|
|
128
150
|
});
|
|
129
151
|
if (!built.ok) return;
|
|
130
152
|
|
|
153
|
+
// deposit()/vaultSwap() never approve: the spoke asset manager pulls inputToken, so approve it swap-style first.
|
|
154
|
+
const allowance = await sodax.swaps.isAllowanceValid({ params: built.value.params, walletProvider });
|
|
155
|
+
if (!allowance.ok) return;
|
|
156
|
+
if (!allowance.value) {
|
|
157
|
+
// Pin the chain so the result narrows to an EVM tx hash.
|
|
158
|
+
const approval = await sodax.swaps.approve<typeof srcChainKey, false>({
|
|
159
|
+
params: { ...built.value.params, srcChainKey },
|
|
160
|
+
walletProvider,
|
|
161
|
+
});
|
|
162
|
+
if (!approval.ok) return;
|
|
163
|
+
const receipt = await walletProvider.waitForTransactionReceipt(approval.value);
|
|
164
|
+
// Providers report a revert as viem's 'reverted' or the JSON-RPC '0x0'.
|
|
165
|
+
if (receipt.status === 'reverted' || receipt.status === '0x0') return;
|
|
166
|
+
}
|
|
167
|
+
|
|
131
168
|
const result = await sodax.leverageYield.vaultSwap({ ...built.value, walletProvider });
|
|
132
169
|
if (!result.ok) return;
|
|
133
170
|
const { solverExecutionResponse, intent, intentDeliveryInfo } = result.value;
|
|
134
171
|
```
|
|
135
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
|
+
|
|
136
186
|
### Withdraw (`lsoda*` → any token)
|
|
137
187
|
|
|
138
188
|
```ts
|
|
189
|
+
const outputToken = '0x…weETHonArbitrum';
|
|
190
|
+
const SLIPPAGE_BPS = 100n;
|
|
191
|
+
// Withdraw quote: vault as token_src, on the hub (the shares live in the hub wallet).
|
|
192
|
+
const withdrawQuote = await sodax.leverageYield.getQuote({
|
|
193
|
+
token_src: vault.vault,
|
|
194
|
+
token_src_blockchain_id: ChainKeys.SONIC_MAINNET,
|
|
195
|
+
token_dst: outputToken,
|
|
196
|
+
token_dst_blockchain_id: ChainKeys.ARBITRUM_MAINNET,
|
|
197
|
+
amount: shareBalance,
|
|
198
|
+
quote_type: 'exact_input',
|
|
199
|
+
});
|
|
200
|
+
if (!withdrawQuote.ok) return;
|
|
201
|
+
|
|
139
202
|
const built = await sodax.leverageYield.withdraw({
|
|
140
203
|
vault: vault.vault,
|
|
141
204
|
srcChainKey: ChainKeys.ARBITRUM_MAINNET, // user signs the sendMessage here
|
|
142
205
|
srcAddress: '0x…',
|
|
143
206
|
dstChainKey: ChainKeys.ARBITRUM_MAINNET, // token delivered here
|
|
144
|
-
outputToken
|
|
207
|
+
outputToken,
|
|
145
208
|
inputAmount: shareBalance, // lsoda* to burn
|
|
146
|
-
minOutputAmount:
|
|
209
|
+
minOutputAmount: (withdrawQuote.value.quoted_amount * (10_000n - SLIPPAGE_BPS)) / 10_000n,
|
|
147
210
|
});
|
|
148
211
|
if (!built.ok) return;
|
|
149
212
|
// built.value.hubWalletSwap === true — no spoke approval; the hub wallet authorises the spend
|
|
150
213
|
await sodax.leverageYield.vaultSwap({ ...built.value, walletProvider });
|
|
151
214
|
```
|
|
152
215
|
|
|
216
|
+
**Partner fee is opt-in.** Omit `partnerFee` unless the integrator supplied their own receiver address. To override the fee per intent, pass the same `partnerFee` to `getQuote` and to `deposit()` / `withdraw()`, and quote the gross `inputAmount`: `getQuote` deducts the fee itself, so both sides end up on the same net input.
|
|
217
|
+
|
|
153
218
|
### Manual create → relay → notify
|
|
154
219
|
|
|
155
220
|
```ts
|
|
@@ -171,10 +236,10 @@ await sodax.leverageYield.notifySolver({ intent_tx_hash: hubIntentTxHash });
|
|
|
171
236
|
| `notifySolver` | `SolverExecutionResponse` (`{ answer, intent_hash }`) |
|
|
172
237
|
| `approve` | `TxReturnType<HubChainKey, R>` |
|
|
173
238
|
| `isAllowanceValid` | `boolean` |
|
|
174
|
-
| `getApr` | `LeverageYieldApr` (`{ supplyAprRay, borrowAprRay, targetLtvBps, leverageMultiplierWad, netAprRay }
|
|
239
|
+
| `getApr` | `LeverageYieldApr` (`{ supplyAprRay, borrowAprRay, targetLtvBps, leverageMultiplierWad, netAprRay }` — rates RAY, `targetLtvBps` basis points, multiplier WAD and the **borrowed** multiple) |
|
|
175
240
|
| `getEffectiveApr` | `LeverageYieldEffectiveApr` (= `LeverageYieldApr & { lsdApr, effectiveSupplyAprRay, effectiveNetAprRay }`) |
|
|
176
241
|
| `getLsdApr` | `LeverageYieldLsdApr` (`{ aprRay, label, stale }`) |
|
|
177
|
-
| `getPosition` | `LeverageYieldPosition` (`{ collateral, debt, ltv, healthFactor, idleAsset }`) |
|
|
242
|
+
| `getPosition` | `LeverageYieldPosition` (`{ collateral, debt, ltv, healthFactor, idleAsset }` — `ltv` basis points, `healthFactor` WAD, amounts 18 dp) |
|
|
178
243
|
| `getTotalAssets`, `preview*`, `getMaxWithdraw*`, `getShareBalance*` | `bigint` |
|
|
179
244
|
| `getAsset` | `Address` |
|
|
180
245
|
| `listVaults` / `getVault` / `getVaultByAddress` | `LeverageYieldVault[]` / `LeverageYieldVault \| undefined` (synchronous) |
|
|
@@ -187,7 +252,7 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
|
|
|
187
252
|
|
|
188
253
|
## Error codes
|
|
189
254
|
|
|
190
|
-
`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`.
|
|
191
256
|
|
|
192
257
|
| Method | Narrow code union |
|
|
193
258
|
|---|---|
|
|
@@ -195,6 +260,8 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
|
|
|
195
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) |
|
|
196
261
|
| `createVaultIntent` | `VALIDATION_FAILED \| INTENT_CREATION_FAILED \| UNKNOWN` (create-intent subset) |
|
|
197
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` |
|
|
198
265
|
| `notifySolver` | `EXECUTION_FAILED \| EXTERNAL_API_ERROR \| UNKNOWN` (with `phase: 'postExecution'`) |
|
|
199
266
|
| `approve` | `VALIDATION_FAILED \| APPROVE_FAILED \| UNKNOWN` |
|
|
200
267
|
| `isAllowanceValid` | `VALIDATION_FAILED \| ALLOWANCE_CHECK_FAILED \| UNKNOWN` (action `'allowanceCheck'`) |
|
|
@@ -207,6 +274,8 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
|
|
|
207
274
|
|
|
208
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.
|
|
209
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
|
+
|
|
210
279
|
## Leverage positions
|
|
211
280
|
|
|
212
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
|
|
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 }; //
|
|
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
|
|
@@ -63,8 +63,9 @@ applies per-call overrides that take precedence over the service config (see "Pe
|
|
|
63
63
|
allowance change from one non-zero value to another (the 2017 TetherToken lineage) **and** the wallet
|
|
64
64
|
already holds a stale allowance — a wallet in that state cannot approve at all until it is zeroed.
|
|
65
65
|
|
|
66
|
-
Broadcast `resetTx` first and wait for it to be mined, then broadcast `tx`.
|
|
67
|
-
|
|
66
|
+
Broadcast `resetTx` first and wait for it to be mined, then broadcast `tx`. As separate transactions
|
|
67
|
+
they cannot go out together: the approval is only valid once the reset has landed on-chain. An
|
|
68
|
+
EIP-5792 atomic batch is different — it runs its calls in order, so it can carry both (next section).
|
|
68
69
|
|
|
69
70
|
```ts
|
|
70
71
|
const { tx, resetTx } = approveResponse;
|
|
@@ -80,6 +81,59 @@ await sendTransaction(tx);
|
|
|
80
81
|
The field is optional and absent for every other token, so ignoring it keeps existing behaviour —
|
|
81
82
|
it just cannot rescue a wallet stuck on a guarded token.
|
|
82
83
|
|
|
84
|
+
## Approve and send the intent in one signature
|
|
85
|
+
|
|
86
|
+
When `checkAllowance` says the allowance is short and the source is an EVM spoke, the approval can go
|
|
87
|
+
out in the same EIP-5792 atomic batch as the intent tx — one wallet prompt instead of two or three.
|
|
88
|
+
`/swaps/intents` only simulates on the hub, so the intent tx can be built before the approval lands.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import {
|
|
92
|
+
isAtomicBatchRefusal,
|
|
93
|
+
isEvmSpokeOnlyChainKeyType,
|
|
94
|
+
isEvmWalletProviderType,
|
|
95
|
+
resolveApprovalStrategy,
|
|
96
|
+
sendApprovalBatch,
|
|
97
|
+
} from '@sodax/sdk';
|
|
98
|
+
|
|
99
|
+
if (
|
|
100
|
+
isEvmSpokeOnlyChainKeyType(srcChainKey) &&
|
|
101
|
+
isEvmWalletProviderType(walletProvider) &&
|
|
102
|
+
(await resolveApprovalStrategy({ srcChainKey, walletProvider, allowAccountUpgrade })) === 'atomic-batch'
|
|
103
|
+
) {
|
|
104
|
+
// EVM source: approve.tx, approve.resetTx and createIntent's tx are all EvmRawTransaction.
|
|
105
|
+
const sent = await sendApprovalBatch({
|
|
106
|
+
walletProvider,
|
|
107
|
+
srcChainKey,
|
|
108
|
+
txs: [...(resetTx ? [resetTx] : []), tx, intentTx], // the intent tx last
|
|
109
|
+
timeoutMs: 120_000,
|
|
110
|
+
feature: 'swap',
|
|
111
|
+
onBatchSent: batchId => saveBatchId(batchId), // persist before the wait: the way back to an unconfirmed batch
|
|
112
|
+
});
|
|
113
|
+
if (sent.ok) {
|
|
114
|
+
// sent.value.txHash is the source tx: persist it, then submitTx({ txHash: sent.value.txHash, ... })
|
|
115
|
+
} else if (isAtomicBatchRefusal(sent.error)) {
|
|
116
|
+
// Refused before signing, nothing sent: approve separately (reset first), then create the intent again and send it.
|
|
117
|
+
} else {
|
|
118
|
+
// USER_REJECTED, 'atomic-batch-failed' (nothing landed) or ATOMIC_BATCH_UNCONFIRMED (may still land).
|
|
119
|
+
throw sent.error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The rules match `sodax.swaps.swapWithApproval`:
|
|
125
|
+
|
|
126
|
+
- `'sequential'` for the Sonic hub and any wallet without EIP-5792 support — approve, wait, then sign.
|
|
127
|
+
- Only `ATOMIC_BATCH_REFUSED` may fall back to separate transactions; the wallet signed nothing.
|
|
128
|
+
- `USER_REJECTED` — with `context.reason === ACCOUNT_UPGRADE_DECLINED` when the user declined the
|
|
129
|
+
smart-account upgrade; offer the swap again with `allowAccountUpgrade: false`.
|
|
130
|
+
- `TX_VERIFICATION_FAILED` with `context.reason === ATOMIC_BATCH_UNCONFIRMED` — the batch may still
|
|
131
|
+
land. Do not resend it, as a batch or as separate transactions: resume it later with
|
|
132
|
+
`confirmApprovalBatch({ walletProvider, batchId, callCount, timeoutMs, feature })`, which reads the
|
|
133
|
+
deposit's `txHash` once the wallet confirms it.
|
|
134
|
+
|
|
135
|
+
In React, the `sodax-dapp-kit` skill's `useSwapsApiBroadcastWithApproval` hook wraps this whole flow.
|
|
136
|
+
|
|
83
137
|
## Wire shapes — `bigint` vs decimal strings
|
|
84
138
|
|
|
85
139
|
Request bodies that carry an `intent` struct (`cancelIntent`, `getIntentHash`,
|
|
@@ -99,10 +99,32 @@ type LookupErrorCode = 'VALIDATION_FAILED' | 'LOOKUP_FAILED' | 'UNKNOWN';
|
|
|
99
99
|
|---|---|
|
|
100
100
|
| `createIntent` | `CreateIntentErrorCode` |
|
|
101
101
|
| `swap` | All of {`USER_REJECTED`, `VALIDATION_FAILED`, `INTENT_CREATION_FAILED`, `EXECUTION_FAILED`, `TX_VERIFICATION_FAILED`, `TX_SUBMIT_FAILED`, `RELAY_TIMEOUT`, `RELAY_FAILED`, `EXTERNAL_API_ERROR`, `UNKNOWN`} |
|
|
102
|
+
| `swapWithApproval` | `SwapWithApprovalErrorCode`: the `swap` codes plus `APPROVE_FAILED \| ALLOWANCE_CHECK_FAILED`. See [Atomic approval batches](#atomic-approval-batches-contextreason) for the batch reasons |
|
|
103
|
+
| `getApprovalStrategy` | `ApprovalStrategyErrorCode` (`ALLOWANCE_CHECK_FAILED` only) |
|
|
102
104
|
| `postExecution` | `EXECUTION_FAILED \| EXTERNAL_API_ERROR \| UNKNOWN` (with `phase: 'postExecution'`) |
|
|
103
105
|
| `createLimitOrder`, `createLimitOrderIntent` | `CreateIntentErrorCode` |
|
|
104
106
|
| `cancelIntent`, `cancelLimitOrder` | `EXECUTION_FAILED \| VALIDATION_FAILED \| UNKNOWN` |
|
|
105
107
|
|
|
108
|
+
#### Atomic approval batches (`context.reason`)
|
|
109
|
+
|
|
110
|
+
When the approval and the deposit go out as one EIP-5792 batch (`swapWithApproval`,
|
|
111
|
+
`bridgeWithApproval`, `vaultSwapWithApproval`, or the shared `sendApprovalBatch` / `confirmApprovalBatch`
|
|
112
|
+
helpers), these codes carry a `context.reason` that changes
|
|
113
|
+
what the caller should do. Check it before the generic retry advice above.
|
|
114
|
+
|
|
115
|
+
| Code | `context.reason` | Meaning | Retry? |
|
|
116
|
+
|---|---|---|---|
|
|
117
|
+
| `USER_REJECTED` | `ACCOUNT_UPGRADE_DECLINED` | The user declined the smart-account upgrade, not the swap. | Offer it again with `allowAccountUpgrade: false` (two signatures). |
|
|
118
|
+
| `INTENT_CREATION_FAILED` | `ATOMIC_BATCH_REFUSED` | The wallet refused the batch before signing, or cannot batch. Nothing was sent. | Yes, approve separately. `swapWithApproval` does this itself; a caller of `sendApprovalBatch` does it. Test with `isAtomicBatchRefusal(error)`. |
|
|
119
|
+
| `INTENT_CREATION_FAILED` | `'atomic-batch-failed'` (with `batchId`, `statusCode`) | The batch was never included or fully reverted. Nothing was deposited. | Yes. |
|
|
120
|
+
| `TX_VERIFICATION_FAILED` | `ATOMIC_BATCH_UNCONFIRMED` (with `batchId`, `callCount`) | The wallet took the batch but it did not confirm in time. **It may still land.** | **No.** Do not let the user send it again. Resume it: call `swapWithApproval` / `bridgeWithApproval` / `vaultSwapWithApproval` again with `resumeBatchId` and `resumeBatchCallCount`, which sends nothing and finishes the flow once the batch lands; a `sendApprovalBatch` caller uses `confirmApprovalBatch`. |
|
|
121
|
+
|
|
122
|
+
`sendApprovalBatch` and `confirmApprovalBatch` return `ApprovalBatchErrorCode`
|
|
123
|
+
(`USER_REJECTED | INTENT_CREATION_FAILED | TX_VERIFICATION_FAILED`) on the `feature` the caller passes.
|
|
124
|
+
`confirmApprovalBatch` resumes a batch that came back unconfirmed, from the `batchId` that
|
|
125
|
+
`sendApprovalBatch` reported through `onBatchSent`. `resolveApprovalStrategy` does not fail: a wallet
|
|
126
|
+
whose capabilities cannot be read resolves to `'sequential'`.
|
|
127
|
+
|
|
106
128
|
### Money Market (`feature: 'moneyMarket'`)
|
|
107
129
|
|
|
108
130
|
| Method | Narrow code union |
|
|
@@ -129,6 +151,8 @@ type LookupErrorCode = 'VALIDATION_FAILED' | 'LOOKUP_FAILED' | 'UNKNOWN';
|
|
|
129
151
|
| Method | Narrow code union |
|
|
130
152
|
|---|---|
|
|
131
153
|
| `bridge` | All exec codes. |
|
|
154
|
+
| `bridgeWithApproval` | `BridgeWithApprovalErrorCode`: the `bridge` codes plus `APPROVE_FAILED \| ALLOWANCE_CHECK_FAILED`, with `context.action: 'bridgeWithApproval'` on the approval step. See [Atomic approval batches](#atomic-approval-batches-contextreason) for the batch reasons |
|
|
155
|
+
| `getApprovalStrategy` | `AllowanceCheckErrorCode` (the `isAllowanceValid` error, so invalid params stay `VALIDATION_FAILED`) |
|
|
132
156
|
| `createBridgeIntent` | `CreateIntentErrorCode` |
|
|
133
157
|
| `approve` | `ApproveErrorCode` |
|
|
134
158
|
| `isAllowanceValid` | `AllowanceCheckErrorCode` |
|
|
@@ -166,12 +190,14 @@ Both follow the same shape: action methods get the full exec union (`'EXECUTION_
|
|
|
166
190
|
|
|
167
191
|
### Leverage Yield (`feature: 'leverageYield'`)
|
|
168
192
|
|
|
169
|
-
Action discriminator on `context.action`: `'deposit' \| 'withdraw' \| 'approve' \| 'allowanceCheck' \| 'vaultSwap'
|
|
193
|
+
Action discriminator on `context.action`: `'deposit' \| 'withdraw' \| 'approve' \| 'allowanceCheck' \| 'vaultSwap' \| 'vaultSwapWithApproval'` (the last on the approval step of `vaultSwapWithApproval`).
|
|
170
194
|
|
|
171
195
|
| Method | Narrow code union |
|
|
172
196
|
|---|---|
|
|
173
197
|
| `deposit`, `withdraw`, `createVaultIntent` | `CreateIntentErrorCode` (create-intent subset) |
|
|
174
198
|
| `vaultSwap` | All exec codes: `VALIDATION_FAILED \| INTENT_CREATION_FAILED \| TX_VERIFICATION_FAILED \| TX_SUBMIT_FAILED \| RELAY_TIMEOUT \| RELAY_FAILED \| EXECUTION_FAILED \| EXTERNAL_API_ERROR \| UNKNOWN` |
|
|
199
|
+
| `vaultSwapWithApproval` | `VaultSwapWithApprovalErrorCode`: the `vaultSwap` codes plus `APPROVE_FAILED \| ALLOWANCE_CHECK_FAILED`. Errors after the broadcast are `vaultSwap`'s own. See [Atomic approval batches](#atomic-approval-batches-contextreason) for the batch reasons |
|
|
200
|
+
| `getApprovalStrategy` | `ApprovalStrategyErrorCode` (`ALLOWANCE_CHECK_FAILED` only); a hub-wallet swap resolves `'not-required'` |
|
|
175
201
|
| `notifySolver` | `EXECUTION_FAILED \| EXTERNAL_API_ERROR \| UNKNOWN` (with `phase: 'postExecution'`) |
|
|
176
202
|
| `approve` | `ApproveErrorCode` |
|
|
177
203
|
| `isAllowanceValid` | `AllowanceCheckErrorCode` (action `'allowanceCheck'`) |
|
|
@@ -103,6 +103,35 @@ import {
|
|
|
103
103
|
type INearWalletProvider,
|
|
104
104
|
type IBitcoinWalletProvider,
|
|
105
105
|
|
|
106
|
+
// Approve + swap in one signature (see features/swap.md)
|
|
107
|
+
type SwapApprovalStrategy, // 'not-required' | 'atomic-batch' | 'sequential'
|
|
108
|
+
type SwapWithApprovalParams,
|
|
109
|
+
type SwapWithApprovalResponse,
|
|
110
|
+
type SwapWithApprovalErrorCode,
|
|
111
|
+
type ApprovalStrategyErrorCode,
|
|
112
|
+
ATOMIC_BATCH_UNCONFIRMED, // context.reason: the batch may still land; resume it with resumeBatchId, never resend
|
|
113
|
+
ACCOUNT_UPGRADE_DECLINED, // context.reason: retry with allowAccountUpgrade: false
|
|
114
|
+
|
|
115
|
+
// Approval batch helpers, for flows that build their own deposit (see features/swaps-api.md)
|
|
116
|
+
type ApprovalStrategy,
|
|
117
|
+
type ApprovalOptions,
|
|
118
|
+
type ApprovalBatchErrorCode,
|
|
119
|
+
type ApprovalBatchResult,
|
|
120
|
+
resolveApprovalStrategy, // 'atomic-batch' | 'sequential'; never fails
|
|
121
|
+
sendApprovalBatch, // [reset?, approve, deposit] as one EIP-5792 batch
|
|
122
|
+
confirmApprovalBatch, // resume a batch that came back unconfirmed
|
|
123
|
+
isAtomicBatchRefusal, // the one batch failure that may fall back to separate txs
|
|
124
|
+
ATOMIC_BATCH_REFUSED, // context.reason of that refusal
|
|
125
|
+
type ApprovalStrategyError,
|
|
126
|
+
|
|
127
|
+
// Approve + bridge / vault deposit in one signature (see features/bridge.md, features/leverage-yield.md)
|
|
128
|
+
type BridgeWithApprovalParams,
|
|
129
|
+
type BridgeWithApprovalResponse,
|
|
130
|
+
type BridgeWithApprovalErrorCode,
|
|
131
|
+
type VaultSwapWithApprovalParams,
|
|
132
|
+
type VaultSwapWithApprovalResponse,
|
|
133
|
+
type VaultSwapWithApprovalErrorCode,
|
|
134
|
+
|
|
106
135
|
// Param types (per feature)
|
|
107
136
|
type CreateIntentParams,
|
|
108
137
|
type CreateLimitOrderParams,
|
|
@@ -218,7 +247,7 @@ This is a partial list — see `src/index.ts` of the published tarball for the a
|
|
|
218
247
|
- **Import only from `@sodax/sdk` root.** No deep imports from `dist/...`.
|
|
219
248
|
- **Do not depend on `@sodax/types` separately.** It's a transitive of `@sodax/sdk` (force-bundled via tsup `noExternal`); declaring it as a direct dependency invites version skew.
|
|
220
249
|
- **Stable contract:** every export above is part of the public API. Anything not exported from the root barrel is internal — don't reach for it via `dist` paths.
|
|
221
|
-
- **Tarball contents:** `dist/` (compiled JS + types). Nothing else ships. Consumer-facing AI docs (this tree) are shipped separately via [`@sodax/skills`](https://github.com/
|
|
250
|
+
- **Tarball contents:** `dist/` (compiled JS + types). Nothing else ships. Consumer-facing AI docs (this tree) are shipped separately via [`@sodax/skills`](https://github.com/gosodax/sodax-sdks/tree/main/packages/skills).
|
|
222
251
|
|
|
223
252
|
---
|
|
224
253
|
|
|
@@ -15,9 +15,10 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
|
|
|
15
15
|
|
|
16
16
|
0. **Vault or leverage position?** Ask this first — they share the service and nothing else. A **vault** is one pooled ERC-4626 position at a single target LTV, entered/exited as an intent swap (`deposit` / `withdraw` / `vaultSwap`). A **leverage position** is the user's own AAVE account, cloned per position, with its own eMode category and leverage tier (`openLeveragePosition` and friends). "Deposit into a leverage vault" is the first; "open a leverage position", "adjust my leverage", "close my position" is the second. If the answer is positions, jump to Step 1b.
|
|
17
17
|
1. **Deposit or withdraw?** Deposit = any spoke token → `lsoda*` shares (delivered to the user's hub wallet). Withdraw = `lsoda*` shares (in the hub wallet) → any token on any chain.
|
|
18
|
-
2. **Build vs execute.** `deposit` / `withdraw` only *build* a `LeverageYieldSwapPayload`; `vaultSwap` *executes* it end-to-end. Spread the built payload into `vaultSwap({ ...payload, walletProvider })`.
|
|
19
|
-
3. **End-to-end or manual relay?** `vaultSwap`
|
|
20
|
-
4. **
|
|
18
|
+
2. **Build vs execute.** `deposit` / `withdraw` only *build* a `LeverageYieldSwapPayload`; `vaultSwap` *executes* it end-to-end. Spread the built payload into `vaultSwap({ ...payload, walletProvider })`. `vaultSwapWithApproval` does the same with the deposit's approval folded in (one EIP-5792 batch when the wallet can); `getApprovalStrategy` predicts the path.
|
|
19
|
+
3. **End-to-end or manual relay?** By default `vaultSwap` creates the intent and hands it to the backend submit-tx flow, which relays and notifies the solver; on any backend non-success it falls back to verify → relay → notify client-side, and then resolves before the fill (opt out of the backend path with `leverageYield: { useBackendSubmitTx: false }`). For a fully manual flow, use `createVaultIntent`, relay yourself, and finish with the public `notifySolver`.
|
|
20
|
+
4. **Which vaults?** `listVaults()` (synchronous registry: `{ name, vault, asset, borrowToken, lsdSource? }`); pass `vault` to every call.
|
|
21
|
+
5. **Reads?** `getEffectiveApr` (headline, AAVE + LSD), `getApr` (AAVE-only — can be negative), `getPosition`, `getTotalAssets`, `previewRedeem`, `getMaxWithdrawForUser` / `getShareBalanceForUser` (resolve the hub wallet from a spoke address internally).
|
|
21
22
|
|
|
22
23
|
### Step 1b — leverage positions
|
|
23
24
|
|
|
@@ -41,9 +42,13 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
|
|
|
41
42
|
- **Using `getApr` as the headline number.** For LSD-backed vaults the AAVE-only spread is often negative; `getEffectiveApr` folds in the LSD staking yield (the real source of return).
|
|
42
43
|
- **Passing a spoke address to `getShareBalance` / `getMaxWithdraw`.** Those take a hub address. Use the `*ForUser(vault, srcChainKey, srcAddress)` variants to resolve the hub wallet first.
|
|
43
44
|
- **Gating withdraw on `approve` / `isAllowanceValid`.** Those are Sonic-direct allowance helpers for the vault's underlying asset; the swap-style withdraw authorises the share spend via a hub-wallet `Connection.sendMessage` (`hubWalletSwap: true`).
|
|
45
|
+
- **Sending `minOutputAmount: 0n`.** Derive it from `sodax.leverageYield.getQuote`'s `quoted_amount` minus a slippage tolerance in basis points. The SDK does not reject zero, and 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
|
+
- **Reading `leverageMultiplierWad` as total exposure.** It is the borrowed multiple, `targetLTV / (1 − targetLTV)`; exposure is `1 + multiplier`. `targetLtvBps` and `getPosition().ltv` are basis points.
|
|
44
48
|
- **Quoting a vault flow through `sodax.swaps.getQuote`.** It deducts the effective *swap* fee, while the vault intent charges the effective *leverage-yield* fee (`leverageYield.partnerFee ?? fee`) — the two disagree whenever the feature fees differ. It can be made to agree by passing the leverage-yield fee explicitly (with a zero fee — `{ address, percentage: 0 }` — where that fee is `undefined`, since an explicit `undefined` falls back to the swap fee), but prefer `sodax.leverageYield.getQuote` (`token_dst` = vault for a deposit, `token_src` = vault for a withdraw).
|
|
45
49
|
- **Quoting with a different `partnerFee` than the intent charges.** The fee is deducted from the input before the swap, so the quote is sized on a different net input; when the intent's fee is the larger one, the `minOutputAmount` derived from that quote can't be met and the intent never fills. Pass the same `partnerFee` to `getQuote` and to `deposit()` / `vaultSwap()`, or omit it on both.
|
|
46
50
|
- **Assuming `swaps.partnerFee` monetizes vault flows.** It does not — configure `leverageYield.partnerFee` (or the global `fee`).
|
|
51
|
+
- **Reporting a vault swap as lost on a post-broadcast failure.** `TX_VERIFICATION_FAILED`, the relay codes and post-execution failures from `vaultSwap` carry `error.context.srcTxHash` — the vault swap may still complete, so keep polling `getDetailedStatus` with it. A failed solver notification also carries `error.context.dstTxHash`: call `notifySolver({ intent_tx_hash })` with it again first, since polling never notifies.
|
|
47
52
|
|
|
48
53
|
### Leverage-position anti-patterns
|
|
49
54
|
|
|
@@ -63,14 +68,17 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
|
|
|
63
68
|
|
|
64
69
|
1. `pnpm tsc --noEmit` clean.
|
|
65
70
|
2. Every `await sodax.leverageYield.<method>(...)` has `if (!result.ok)`.
|
|
66
|
-
3.
|
|
67
|
-
4.
|
|
68
|
-
5.
|
|
69
|
-
6. Positions:
|
|
71
|
+
3. Every `minOutputAmount` comes from `sodax.leverageYield.getQuote` minus slippage; no `0n`, no unrequested `partnerFee`.
|
|
72
|
+
4. Deposit/withdraw build a payload that is then run through `vaultSwap` (or `createVaultIntent` + relay + `notifySolver`).
|
|
73
|
+
5. APR display uses `getEffectiveApr`; share/withdraw sizing from a spoke address uses the `*ForUser` reads.
|
|
74
|
+
6. Positions: every `borrowAmount` / `minCollateralOut` traces back to `sizeLeverageBorrow` + `projectLeverageLeg` (never oracle parity), `exceedsMaxLtv` is checked before posting, and `notified` is read on every open / leverage change.
|
|
75
|
+
7. Positions: leverage changes go through `submitLeveragePositionIntent`, not `runLeveragePositionOperation`; `notifySolver` is given `dstChainTxHash`; exits are sized from `getPositionCollateralBalance` and charge the fee from `getPositionInfo`.
|
|
70
76
|
|
|
71
77
|
## Related granular skills (same family)
|
|
72
78
|
|
|
73
|
-
- [`../swap/SKILL.md`](../swap/SKILL.md) — `vaultSwap` is a leverage-yield copy of the swap intent flow
|
|
79
|
+
- [`../swap/SKILL.md`](../swap/SKILL.md) — `vaultSwap` is a leverage-yield copy of the swap intent flow. Quote `minOutputAmount` with `sodax.leverageYield.getQuote`, not the swap skill's `getQuote`.
|
|
74
80
|
- [`../recovery/SKILL.md`](../recovery/SKILL.md) — recover stuck hub-wallet assets (including `lsoda*` shares) back to a spoke chain.
|
|
75
81
|
|
|
76
82
|
For multi-feature tasks, load the broad [`sodax-sdk` skill](../SKILL.md).
|
|
83
|
+
|
|
84
|
+
Building a user-facing React vault screen? Load the `sodax-dapp-kit` skill's leverage-yield granular skill: its product anatomy covers the journey, the states, USD prices, derived values and the units table.
|
|
@@ -176,7 +176,7 @@ If you pass a config override to `new Sodax({ ... })`, put solver endpoints in `
|
|
|
176
176
|
v1 had per-feature relay helpers (each feature module had its own `*WaitForRelay()` or `relay*Tx()` function). v2 centralises this into `IntentRelayApiService` with two public entry points:
|
|
177
177
|
|
|
178
178
|
- `submitTransaction(payload, apiUrl)` — TWO positional args (`payload: IntentRelayRequest<'submit'>`, `apiUrl: HttpUrl`), not an options object. POSTs the spoke transaction to the relay submit endpoint and resolves the relay's first-stage acknowledgement.
|
|
179
|
-
- `relayTxAndWaitPacket({ srcTxHash, data
|
|
179
|
+
- `relayTxAndWaitPacket({ srcTxHash, data?, chainKey, relayerApiEndpoint, timeout, pollTxHash? })` — `RelayAndWaitParams`: `data` is the whole `RelayExtraData` / `OnDemandRelayData` object (required for Solana and Bitcoin), `chainKey` is the source `SpokeChainKey`. Runs `submitTransaction` and then polls until the destination packet reaches `executed`. Resolves with `{ srcTxHash, dstTxHash, packet }` on success.
|
|
180
180
|
|
|
181
181
|
Internally, every feature service now calls `relayTxAndWaitPacket` for the spoke→hub leg. Failures from this layer surface to consumers via `mapRelayFailure`.
|
|
182
182
|
|
|
@@ -52,7 +52,7 @@ All v1 fields were **optional**. v1 had **no** top-level `rpcConfig` on `SodaxCo
|
|
|
52
52
|
| `SodaxConfig.swaps` (`SolverConfigParams` — `{ intentsContract, solverApiEndpoint, protocolIntentsContract?, partnerFee? }`) | **Split into two:** `SodaxConfig.solver: SolverConfig` (`{ intentsContract, solverApiEndpoint, protocolIntentsContract }`) and `SodaxConfig.swaps: SwapsConfig` (supported tokens per chain — new in v2). | v1 partner-fee inside `SolverConfigParams` moves to the global `SodaxOptions.fee` option or per-feature configs. |
|
|
53
53
|
| `SodaxConfig.hubProviderConfig` (`EvmHubProviderConfig` — `{ hubRpcUrl, chainConfig }`) | **`SodaxConfig.hub`** (`HubConfig` — full hub addresses + native token + bnUSD + polling + RPC URL). | Field renamed `hubProviderConfig` → `hub`. Shape expanded: v1 just had RPC URL + chain config; v2 ships the full hub-contract address map. |
|
|
54
54
|
| `SodaxConfig.moneyMarket` (`MoneyMarketConfigParams`) | `SodaxConfig.moneyMarket` (`MoneyMarketConfig` — required, shape changed). | Reshape, see `@sodax/types/src/common/common.ts` MoneyMarketConfig. |
|
|
55
|
-
| `SodaxConfig.bridge` (`BridgeServiceConfig`) | `SodaxConfig.bridge` (`BridgeConfig` — `{ partnerFee }`). | Reshape; smaller. |
|
|
55
|
+
| `SodaxConfig.bridge` (`BridgeServiceConfig`) | `SodaxConfig.bridge` (`BridgeConfig` — `{ partnerFee }`). | Reshape; smaller. Client-side option `bridge.useBackendSubmitTx` (default **on**) selects the backend submit-tx path. |
|
|
56
56
|
| `SodaxConfig.dex` (`DexServiceConfig`) | `SodaxConfig.dex` (`DexConfig`). | Reshape. |
|
|
57
57
|
| `SodaxConfig.relayerApiEndpoint: HttpUrl` (string) | **`SodaxConfig.relay`** (`RelayConfig` — object with relayer URL + chain-id map). | Renamed + reshaped from string to object. |
|
|
58
58
|
| `SodaxConfig.backendApiConfig` (`BackendApiConfig`) | **`SodaxConfig.api`** (`ApiConfig`). | Renamed. |
|
|
@@ -63,6 +63,14 @@ All v1 fields were **optional**. v1 had **no** top-level `rpcConfig` on `SodaxCo
|
|
|
63
63
|
| (none in v1) | **`SodaxOptions.fee?: PartnerFee`** (new — a client-side option, NOT a `SodaxConfig` data field). | Global partner fee, set via `new Sodax({ fee })` and read back on `sodax.config.fee`. A client option like `logger` — never fetched from or overwritten by the backend. Per-feature overrides still live on `SodaxConfig` (`bridge.partnerFee`, `swaps.partnerFee`, `moneyMarket.partnerFee`). |
|
|
64
64
|
| (v1 had no top-level `configService` injection slot on `SodaxConfig` — `ConfigService` was always constructed internally from `backendApiConfig` + `sharedConfig`.) | Same — `ConfigService` is internal. v2 does **not** expose a typed slot to inject a custom `IConfigApi` either. To swap the backend in tests, point `SodaxConfig.api.baseURL` at a mock server. | See Pitfall below. |
|
|
65
65
|
|
|
66
|
+
**Within v2, too:** `swaps.useBackendSubmitTx` / `bridge.useBackendSubmitTx` (client-side options, default **on**)
|
|
67
|
+
replace the earlier `swapsOptions` / `bridgeOptions` keys (`SwapsClientOptions` / `BridgeClientOptions`). The old keys
|
|
68
|
+
are deprecated, honoured only when the new flag is omitted, and removed in v3, where the only form is
|
|
69
|
+
`swaps: { partnerFee, useBackendSubmitTx }` / `bridge: { partnerFee, useBackendSubmitTx }`. Do not generate the old
|
|
70
|
+
keys; an explicit `false` on the new key keeps the fully client-side relay path. A `SwapService` built directly
|
|
71
|
+
(not through `new Sodax`) also still accepts a deprecated `useBackendSubmitTx` constructor field, which wins over the
|
|
72
|
+
configured value; it is removed in v3 too.
|
|
73
|
+
|
|
66
74
|
Migration:
|
|
67
75
|
|
|
68
76
|
```diff
|
|
@@ -22,7 +22,7 @@ Swap has materially different code paths depending on the answers. Don't skip:
|
|
|
22
22
|
- Signed → `raw: false` + `walletProvider`.
|
|
23
23
|
- Unsigned → `raw: true`, you handle relay yourself.
|
|
24
24
|
3. **One-shot `swap()` or step-by-step (`createIntent` → backend submit → `postExecution`)?**
|
|
25
|
-
- One-shot is the default for frontends. Step-by-step is for backends that already have a relay/orchestration layer.
|
|
25
|
+
- One-shot is the default for frontends. If the token may need an approval, prefer `swapWithApproval()` — it approves only when needed, and on an EIP-5792 wallet does approve + swap in one signature (`getApprovalStrategy()` tells you which path it will take). A wallet that must first upgrade the account (`'ready'`) prompts for it; pass `allowAccountUpgrade: false` to skip that and approve separately, e.g. after a `USER_REJECTED` with `context.reason === ACCOUNT_UPGRADE_DECLINED`. Step-by-step is for backends that already have a relay/orchestration layer.
|
|
26
26
|
- Step-by-step code must reproduce BOTH paths `swap()` runs internally — the backend submit-tx attempt *and* the client-side relay fallback on any non-success. The helpers behind `swap()` are package-internal, so the loop is hand-written: [`../integration/knowledge/recipes/manual-submit-tx-with-fallback.md`](../integration/knowledge/recipes/manual-submit-tx-with-fallback.md).
|
|
27
27
|
4. **Market order or limit order?** Limit orders use a different params shape — `deadline` becomes optional (forced to `0n` internally), not required.
|
|
28
28
|
|
|
@@ -37,11 +37,13 @@ Read in order. Skipping `ai-rules.md` is the most common cause of agents reverti
|
|
|
37
37
|
- Backend step-by-step → [`../integration/knowledge/recipes/raw-tx-flow.md`](../integration/knowledge/recipes/raw-tx-flow.md) + [`../integration/knowledge/recipes/backend-server-init.md`](../integration/knowledge/recipes/backend-server-init.md)
|
|
38
38
|
4. Error handling for swap-specific codes (`INTENT_CREATION_FAILED`, `EXECUTION_FAILED`, `RELAY_TIMEOUT`, solver-side `EXTERNAL_API_ERROR`) → [`../integration/knowledge/recipes/result-and-errors.md`](../integration/knowledge/recipes/result-and-errors.md) and [`../integration/knowledge/reference/error-codes.md`](../integration/knowledge/reference/error-codes.md).
|
|
39
39
|
5. Cross-chain destination quirks (Stellar trustline, BTC PSBT, Solana PDA) → [`../integration/knowledge/chain-specifics.md`](../integration/knowledge/chain-specifics.md).
|
|
40
|
+
6. Reading swap status → [`../integration/knowledge/features/swap.md`](../integration/knowledge/features/swap.md) § Reading swap status. Default to `getDetailedStatus({ srcChainKey, srcTxHash })` (works whichever completion path ran) and collapse it with `summarizeSwapStatus`.
|
|
40
41
|
|
|
41
42
|
### Swap-specific anti-patterns
|
|
42
43
|
|
|
43
44
|
- **`try { await sodax.swaps.swap(...) } catch` for SDK-level failures.** v2 returns `Result<T>` — branch on `result.ok`. `catch` only fires for thrown exceptions (e.g. missing `walletProvider`), not for `RELAY_TIMEOUT` or `EXECUTION_FAILED`.
|
|
44
45
|
- **Forgetting the discriminator.** `raw: false` is required on signed swaps; without it TypeScript rejects `walletProvider`.
|
|
46
|
+
- **Reporting a swap as lost on a post-broadcast failure.** `TX_VERIFICATION_FAILED`, the relay codes and postExecution failures carry `error.context.srcTxHash` — the backend may still complete the swap, so keep polling `getDetailedStatus` with it. A failed solver notification also carries `error.context.dstTxHash`: call `postExecution({ intent_tx_hash })` with it again first, since polling never notifies.
|
|
45
47
|
- **Calling `sodax.api.swaps.submitTx` with the full `relayData` object.** The backend expects the `payload: string` field, not the wrapper.
|
|
46
48
|
|
|
47
49
|
## Migration workflow (port v1 swap to v2)
|