@sodax/skills 2.2.0-rc.5 → 2.2.0-rc.6
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/package.json +1 -1
- package/skills/sodax-dapp-kit/auxiliary-services/SKILL.md +2 -2
- package/skills/sodax-dapp-kit/integration/knowledge/features/auxiliary-services.md +4 -4
- package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +62 -2
- package/skills/sodax-dapp-kit/integration/knowledge/features/money-market.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/backend-queries.md +2 -2
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +165 -0
- package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +3 -3
- package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +3 -3
- package/skills/sodax-dapp-kit/leverage-yield/SKILL.md +22 -1
- package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/features/auxiliary-services.md +1 -1
- package/skills/sodax-dapp-kit/migration-v1-to-v2/knowledge/reference/renamed-hooks.md +1 -1
- package/skills/sodax-sdk/SKILL.md +3 -3
- package/skills/sodax-sdk/backend-api/SKILL.md +1 -1
- package/skills/sodax-sdk/bridge-api/SKILL.md +2 -2
- package/skills/sodax-sdk/integration/knowledge/architecture.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/features/README.md +3 -3
- package/skills/sodax-sdk/integration/knowledge/features/backend-api.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/features/bridge-api.md +10 -3
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield-api.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +177 -2
- package/skills/sodax-sdk/integration/knowledge/features/swap.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +2 -2
- package/skills/sodax-sdk/integration/knowledge/reference/error-codes.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/reference/public-api.md +37 -1
- package/skills/sodax-sdk/leverage-yield/SKILL.md +25 -1
- package/skills/sodax-sdk/leverage-yield-api/SKILL.md +2 -2
- package/skills/sodax-sdk/swap/SKILL.md +1 -1
- package/skills/sodax-sdk/swaps-api/SKILL.md +2 -2
- package/skills/sodax-wallet-sdk-core/integration/knowledge/features/evm.md +1 -1
- package/skills/sodax-wallet-sdk-react/integration/knowledge/recipes/sign-message.md +2 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-dapp-kit-auxiliary-services
|
|
3
|
-
description: 'Granular skill for the @sodax/dapp-kit v2 auxiliary surfaces — partner fee claiming (useFeeClaimSwap, useApproveToken, useSetSwapPreference, useGetAutoSwapPreferences, useIsTokenApproved), recovery (useHubAssetBalances, useWithdrawHubAsset), read-only backend queries (useBackendIntentByTxHash, useBackendUserIntents, useBackendOrderbook, useBackendMoneyMarketPosition), the Swaps API
|
|
3
|
+
description: 'Granular skill for the @sodax/dapp-kit v2 auxiliary surfaces — partner fee claiming (useFeeClaimSwap, useApproveToken, useSetSwapPreference, useGetAutoSwapPreferences, useIsTokenApproved), recovery (useHubAssetBalances, useWithdrawHubAsset), read-only backend queries (useBackendIntentByTxHash, useBackendUserIntents, useBackendOrderbook, useBackendMoneyMarketPosition), the Swaps API client hooks (useSwapsApiQuote, useSwapsApiSubmitTx, useSwapsApiStatus), sponsored Stellar account activation (useStellarGate, useStellarAccountActive, useStellarAccountStatus, useSponsorConfig, useActivateStellarAccount), and shared utilities (useSodaxContext, useHubProvider, useBalances, useXBalances, useDeriveUserWalletAddress, useEstimateGas, useStellarTrustlineCheck, useEstablishTrustline). Use when a React dapp task is partner fees, recovering stuck hub assets, backend data reads (intent tracking / orderbook / MM data, no wallet), activating a Stellar account for a user who holds no XLM, or cross-cutting utilities (token balances, gas estimation, Stellar trustlines). Covers BOTH integration and migration. Links into the parent sodax-dapp-kit knowledge tree.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -17,7 +17,7 @@ Granular skill for the smaller `@sodax/dapp-kit` v2 surfaces grouped together: *
|
|
|
17
17
|
2. **Which surface?**
|
|
18
18
|
- **Partner fees:** `useIsTokenApproved` → `useApproveToken` → `useSetSwapPreference` → `useFeeClaimSwap` (returns `IntentAutoSwapResult`, NOT `SwapResponse`); `useGetAutoSwapPreferences`, `useFetchAssetsBalances` for reads.
|
|
19
19
|
- **Recovery:** `useHubAssetBalances` (list stuck hub assets) → `useWithdrawHubAsset` (withdraw one back to a spoke). Follows a *known* failed cross-chain op — investigate the failure first.
|
|
20
|
-
- **Backend reads (no wallet):** intent tracking (`useBackendIntentByTxHash` polls 1s, `useBackendIntentByHash`, `useBackendUserIntents`), orderbook (`useBackendOrderbook` — `pagination` nests under `params`), MM data (`useBackendMoneyMarketPosition` etc.), and the Swaps API
|
|
20
|
+
- **Backend reads (no wallet):** intent tracking (`useBackendIntentByTxHash` polls 1s, `useBackendIntentByHash`, `useBackendUserIntents`), orderbook (`useBackendOrderbook` — `pagination` nests under `params`), MM data (`useBackendMoneyMarketPosition` etc.), and the Swaps API client (`useSwapsApi*` — e.g. `useSwapsApiSubmitTx`, `useSwapsApiSubmitTxStatus`, `useSwapsApiQuote`).
|
|
21
21
|
- **Stellar prerequisites:** `useStellarGate` sequences the ordered prerequisites — the account must EXIST (sponsored activation, free to the user), must TRUST the token, and only then must be able to PAY for the trustline it needs. A freshly activated account holds zero XLM. An account that already holds the trustline needs no XLM at all, which is why affordability is checked last. A failed check sets `checkFailed` with `error`/`retry` — render it, or the fail-closed gate becomes an unexplained dead button. Lower-level: `useStellarAccountStatus`, `useStellarAccountActive`, `useSponsorConfig`, `useActivateStellarAccount`.
|
|
22
22
|
- **Shared utilities:** `useSodaxContext`, `useHubProvider`, `useBalances` (SDK-backed — no `xService`, reads via `SodaxProvider`) / `useXBalances` (needs `xService` from wallet-sdk-react), `useDeriveUserWalletAddress` / `useGetUserHubWalletAddress`, `useEstimateGas`, `useStellarTrustlineCheck` / `useEstablishTrustline`.
|
|
23
23
|
|
|
@@ -75,7 +75,7 @@ useBackendOracleCandles({ params: { symbol, interval, from, to }, queryOptions }
|
|
|
75
75
|
|
|
76
76
|
### Swaps API (`sodax.api.swaps`)
|
|
77
77
|
|
|
78
|
-
Typed React Query wrappers over the backend **Swaps API
|
|
78
|
+
Typed React Query wrappers over the backend **Swaps API** — one `useSwapsApi*` hook per endpoint of `sodax.api.swaps.*` (21 total: tokens, quote, deadline, allowance, approve, create / submit / cancel intent, status, intent hash / packet / extra-data, intent lookups, limit orders, gas estimate, fees, submit-tx + status). They call the backend HTTP API and are distinct from the on-chain `swap/` hooks (`useQuote`/`useStatus`/`useSwap`/…), which drive `sodax.swaps` (the on-chain `SwapService`). Reads take `{ params, queryOptions }`; the six actions (`approve`, `createIntent`, `submitIntent`, `cancelIntent`, `createLimitOrder`, `submitTx`) are mutations taking `{ mutationOptions }`, with domain inputs flowing through `mutate(vars)`.
|
|
79
79
|
|
|
80
80
|
```ts
|
|
81
81
|
// @ai-snippets-skip
|
|
@@ -142,7 +142,7 @@ const { mutateAsync: submitSwapTx } = useSwapsApiSubmitTx();
|
|
|
142
142
|
await submitSwapTx({ request, apiConfig: { baseURL: 'https://...' } });
|
|
143
143
|
```
|
|
144
144
|
|
|
145
|
-
`useSwapsApiSubmitTxStatus` polls the processing status and returns `SubmitTxStatusResponseV2 | undefined`. Its query runs only when **both** `txHash` and `srcChainKey` are supplied — the
|
|
145
|
+
`useSwapsApiSubmitTxStatus` polls the processing status and returns `SubmitTxStatusResponseV2 | undefined`. Its query runs only when **both** `txHash` and `srcChainKey` are supplied — the status endpoint requires the source chain key:
|
|
146
146
|
|
|
147
147
|
```ts
|
|
148
148
|
// @ai-snippets-skip
|
|
@@ -154,7 +154,7 @@ const { data: status } = useSwapsApiSubmitTxStatus({ params: { txHash, srcChainK
|
|
|
154
154
|
|
|
155
155
|
### Bridge API (`sodax.api.bridge`)
|
|
156
156
|
|
|
157
|
-
Typed React Query wrappers over the backend **Bridge API
|
|
157
|
+
Typed React Query wrappers over the backend **Bridge API** — `useBridgeApi*` hooks over `sodax.api.bridge.*` (tokens, allowance, approve, create-bridge-intent, submit-tx + status, plus the fee / bridgeable-amount / bridgeable discovery quotes). They are the HTTP-API parallel of the on-chain `bridge/` hooks (`useBridge`/`useBridgeAllowance`/…, which drive `sodax.bridge`). Mirrors the swaps family minus the solver/intent surface; reads take `{ params, queryOptions }`, the three actions (`approve`, `createBridgeIntent`, `submitTx`) are mutations taking `{ mutationOptions }`.
|
|
158
158
|
|
|
159
159
|
```ts
|
|
160
160
|
// @ai-snippets-skip
|
|
@@ -178,7 +178,7 @@ await submitBridgeTx({ request, apiConfig: { baseURL: 'https://...' } });
|
|
|
178
178
|
|
|
179
179
|
### Leverage Yield API (`sodax.api.leverageYield`)
|
|
180
180
|
|
|
181
|
-
Typed React Query wrappers over the backend **Leverage Yield API
|
|
181
|
+
Typed React Query wrappers over the backend **Leverage Yield API** — `useLeverageYieldApi*` hooks over `sodax.api.leverageYield.*` (vault registry, vault reads, split deposit/withdraw quote + create-intent, deadline, allowance/approve, the intent lifecycle, gas/fees, submit-tx + status). They are the HTTP-API parallel of the on-chain `leverageYield/` hooks (`useLeverageYieldDeposit`/`useLeverageYieldWithdraw`/…, which drive `sodax.leverageYield`). A vault deposit/withdraw IS an intent-based swap, so the intent / gas / fee / submit-tx hooks mirror the swaps family; reads take `{ params, queryOptions }` and the actions are mutations taking `{ mutationOptions }`.
|
|
182
182
|
|
|
183
183
|
```ts
|
|
184
184
|
// @ai-snippets-skip
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
# Leverage Yield — `@sodax/dapp-kit`
|
|
2
2
|
|
|
3
|
-
Leveraged-yield ERC-4626 vaults on the Sonic hub. Deposit any token → `lsoda*` vault shares, withdraw shares → any token; plus position / APR / TVL / share-balance reads. New in v2 (no v1 equivalent).
|
|
3
|
+
Leveraged-yield ERC-4626 vaults on the Sonic hub. Deposit any token → `lsoda*` vault shares, withdraw shares → any token; plus vault-position / APR / TVL / share-balance reads. New in v2 (no v1 equivalent).
|
|
4
4
|
|
|
5
|
-
> **
|
|
5
|
+
> **Vaults and leverage positions are two different products on one hook namespace.** Everything up to "Leverage positions" below is the pooled ERC-4626 **vault** (`useLeverageYield*`). The `useLeveragePosition*` / `useOpenLeveragePosition` hooks drive **leverage positions** — one AAVE account per position. Do not mix the two: `useLeverageYieldPosition` is the vault's snapshot, not a leverage position's.
|
|
6
|
+
|
|
7
|
+
> **Backend-API variant:** the hooks below drive the on-chain `LeverageYieldService` (wallet → hub). To call the backend **Leverage Yield API** HTTP client (`sodax.api.leverageYield`) directly instead, use the `useLeverageYieldApi*` hooks — typed React Query wrappers over each endpoint (`useLeverageYieldApiVaults`, `useLeverageYieldApiEffectiveApr`, `useLeverageYieldApiDepositQuote` / `useLeverageYieldApiWithdrawQuote`, `useLeverageYieldApiAllowance` / `useLeverageYieldApiApprove`, `useLeverageYieldApiCreateDepositIntent` / `useLeverageYieldApiCreateWithdrawIntent`, `useLeverageYieldApiSubmitTx` / `useLeverageYieldApiSubmitTxStatus`, and the intent-lifecycle/vault-read hooks). Their `queryKey`/`mutationKey` namespace is `leverageYieldApi`. For the endpoint contract, load the `sodax-sdk` skill's leverage-yield-api feature doc.
|
|
6
8
|
|
|
7
9
|
## Hook surface
|
|
8
10
|
|
|
@@ -115,6 +117,64 @@ Read hooks here are **already unwrapped** — they throw on SDK `!ok` so `isErro
|
|
|
115
117
|
6. **`useLeverageYieldVaultSwap` invalidates xBalances on both chains** (`['shared', 'xBalances', srcChainKey]` and `dstChainKey`) on success. Compose your own `onSuccess` after the hook's — it runs first.
|
|
116
118
|
7. **`useLeverageYieldNotifySolver` is for the manual flow only.** `useLeverageYieldVaultSwap` already notifies the solver internally — only reach for the standalone notify hook when you built the intent with `sodax.leverageYield.createVaultIntent` and relayed it yourself. It does NOT invalidate any queries: its only var is `{ intent_tx_hash }` (no chain context), and the fill lands asynchronously afterward.
|
|
117
119
|
|
|
120
|
+
## Leverage positions (separate from vaults)
|
|
121
|
+
|
|
122
|
+
A vault is one shared ERC-4626 position at a single target LTV. A **leverage position** is one AAVE account per position, cloned by `LeveragePositionFactory`, so an owner can hold several at different eMode categories and leverage tiers at once. Different hooks, different reads — `useLeverageYieldPosition` is the **vault's** snapshot and is unrelated to `useLeveragePosition*`.
|
|
123
|
+
|
|
124
|
+
> **`@experimental` off the hub.** Position writes are proven end to end on Sonic only; from a spoke the inbound half is verified by a fork replay and the outbound half has never run on mainnet. **Bitcoin is refused outright** — a Bitcoin `srcChainKey` returns `VALIDATION_FAILED` rather than funding the wrong hub wallet. The deployed `positionFactory` ships as a packaged default, so positions work from `new Sodax()` with no configuration.
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
// @ai-snippets-skip
|
|
128
|
+
// Reads — data already unwrapped, read it directly
|
|
129
|
+
useLeveragePositions({ params: { owner } }); // readonly Address[] key: ['leverageYield','positions',owner]
|
|
130
|
+
useLeveragePositionsForUser({ params: { spokeChainKey, spokeAddress } }); // same, via the hub wallet — note spoke*, NOT src*
|
|
131
|
+
useLeveragePositionInfo({ params: { position } }); // LeveragePosition — static descriptor
|
|
132
|
+
useLeveragePositionAccount({ params: { position } }); // LeveragePositionAccount (30s)
|
|
133
|
+
useLeveragePositionCollateral({ params: { position, collateral } });// LeveragePositionCollateral (30s)
|
|
134
|
+
useLeveragePositionPending({ params: { position } }); // LeveragePositionPendingState (15s)
|
|
135
|
+
useLeveragePositionFundingAllowance({ params: { srcChainKey, srcAddress, token, amount } }); // boolean
|
|
136
|
+
|
|
137
|
+
// NOT a query — returns synchronously, no data/isLoading
|
|
138
|
+
useLeveragePositionPayoutAddress({ params: { chainKey, signerAddress, owner } }); // Address | undefined
|
|
139
|
+
|
|
140
|
+
// Mutations
|
|
141
|
+
useOpenLeveragePosition(); // key: ['leverageYield','openPosition'] → LeveragePositionIntentResult
|
|
142
|
+
useSubmitLeveragePositionIntent(); // key: ['leverageYield','submitPositionIntent'] → LeveragePositionIntentResult
|
|
143
|
+
useRunLeveragePositionOperation(); // key: ['leverageYield','runPositionOperation'] → TxHashPair
|
|
144
|
+
useApproveLeveragePositionFunding();// key: ['leverageYield','approvePositionFunding']
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
| Type | Fields |
|
|
148
|
+
|---|---|
|
|
149
|
+
| `LeveragePosition` | `{ address, owner, collateral, borrowToken, eModeCategory, feeBps, feeReceiver }` |
|
|
150
|
+
| `LeveragePositionAccount` | `{ totalCollateralBase, totalDebtBase, availableBorrowsBase, currentLiquidationThreshold, ltv, healthFactor }` — bigint; `healthFactor` is WAD, `*Base` is the oracle's 8-dp unit |
|
|
151
|
+
| `LeveragePositionCollateral` | `{ aToken, balance }` |
|
|
152
|
+
| `LeveragePositionPendingState` | `{ kind: number, isLive: boolean, needsSettle: boolean }` |
|
|
153
|
+
| `LeveragePositionIntentResult` | `{ txHashes: TxHashPair, notified: boolean, notifyError?: string }` |
|
|
154
|
+
|
|
155
|
+
### Which mutation — decided by the operation, not by preference
|
|
156
|
+
|
|
157
|
+
`addLeverage` / `decreaseLeverage` only **post** a solver intent, and an intent the solver was never told about expires unfilled — leaving the owner funded with leverage that never arrives. `withdraw`, `settle` and `cancel` are synchronous on the hub and need no notification.
|
|
158
|
+
|
|
159
|
+
| operation | hook | notifies |
|
|
160
|
+
|---|---|---|
|
|
161
|
+
| open (collateral or debt side) | `useOpenLeveragePosition` | yes |
|
|
162
|
+
| `buildAddLeverage` / `buildDecreaseLeverage` | `useSubmitLeveragePositionIntent` | yes |
|
|
163
|
+
| `buildPositionWithdraw` / `buildSettlePosition` / `buildCancelPositionOperation` | `useRunLeveragePositionOperation` | no |
|
|
164
|
+
|
|
165
|
+
TypeScript enforces the rows: the first two builders return `PositionIntentCall`, the last three `PositionDirectCall`, and each hook accepts only its own.
|
|
166
|
+
|
|
167
|
+
### Position gotchas
|
|
168
|
+
|
|
169
|
+
1. **Resolving ≠ the position is open.** The mutations unwrap the SDK `Result`, so `mutateAsync` gives you `LeveragePositionIntentResult` directly — check **`result.notified`** (not `result.value.notified`, which is the SDK-level shape). `false` means the intent is live but nothing will fill it before it expires. A failed notification deliberately still resolves: the money has moved, and a caller that retried on failure would open a second position.
|
|
170
|
+
2. **`useLeverageYieldPosition` is the VAULT, not a leverage position.** Reading vault LTV/health for a position, or vice versa, silently shows the wrong numbers.
|
|
171
|
+
3. **`useLeveragePositionPayoutAddress` is not a query.** It returns `Address | undefined` synchronously — no `data`, no `isLoading`. Off the hub a withdrawal pays to an address on the hub, which is **not** the signer, and this is what resolves it.
|
|
172
|
+
4. **Size an exit from `useLeveragePositionCollateral`, never from `totalCollateralBase`.** The base-currency figures are display-only; dividing one back out by a price lands *near* the balance, and a `decreaseLeverage` asking for more than the position holds reverts at fill time and the intent silently expires.
|
|
173
|
+
5. **Fees come from `useLeveragePositionInfo` for an existing position.** `getEffectivePositionFee()` is what a NEW position would carry; a position's fee is fixed at creation, so the two disagree once config changes.
|
|
174
|
+
6. **Approve with `useApproveLeveragePositionFunding`, gated on `useLeveragePositionFundingAllowance`.** The spender differs per chain — the hub wallet on Sonic, the spoke asset manager elsewhere — so a hand-rolled approval picks the wrong one half the time. Nothing is ever approved to the factory.
|
|
175
|
+
7. **Poll `useLeveragePositionPending`, don't trust the receipt.** A leverage change is filled by a solver afterwards, and a position refuses a second operation while one is in flight.
|
|
176
|
+
8. **Size the leg with `sizeLeverageBorrow` + `projectLeverageLeg`, never oracle parity.** The hook borrows against what the solver actually paid, so parity sizing gets the borrow rejected with Aave `'36'` after the fill. `exceedsMaxLtv` is a hard gate. Display `exposureLeverage`, not the leverage the user chose — the position reports more. Read `ltv` / `liquidationThreshold` from `useEModes` whenever the position sets an `eModeCategory`. Full treatment in [`../recipes/leverage-yield.md`](../recipes/leverage-yield.md).
|
|
177
|
+
|
|
118
178
|
## Cross-references
|
|
119
179
|
|
|
120
180
|
- [`../recipes/leverage-yield.md`](../recipes/leverage-yield.md) — full worked deposit / withdraw / reads examples.
|
|
@@ -127,7 +127,7 @@ if (!isApproved) await approve({ params: supplyParams, walletProvider });
|
|
|
127
127
|
| `useReservesData` | `[ReserveData[], ...]` | Raw data for custom rendering |
|
|
128
128
|
| `useReservesHumanized` | `ReserveDataHumanized[]` | Decimal-normalized (most common for UI) |
|
|
129
129
|
| `useReservesList` | `Address[]` | Just the reserve addresses |
|
|
130
|
-
| `useReservesUsdFormat` | `
|
|
130
|
+
| `useReservesUsdFormat` | `ReserveUsdFormat[]` | With USD price overlays |
|
|
131
131
|
| `useUserFormattedSummary` | `{ totalCollateralUSD, totalBorrowsUSD, healthFactor, ... }` | Dashboard-ready summary |
|
|
132
132
|
| `useUserReservesData` | `UserReserveData[]` | Per-reserve user position |
|
|
133
133
|
|
|
@@ -45,7 +45,7 @@ Read-only data hooks. No wallet connection required.
|
|
|
45
45
|
| `useSwapsApiSubmitTx` | Submit swap tx to backend |
|
|
46
46
|
| `useSwapsApiSubmitTxStatus` | Check submitted swap status |
|
|
47
47
|
|
|
48
|
-
The full Swaps API
|
|
48
|
+
The full Swaps API surface (quote, allowance, approve, create/submit/cancel intent, fees, gas, …) is wrapped one hook per endpoint under the `useSwapsApi*` prefix — see [hooks-index.md](../reference/hooks-index.md).
|
|
49
49
|
|
|
50
50
|
## Track Intent
|
|
51
51
|
|
|
@@ -193,7 +193,7 @@ function SubmitButton({ request, baseURL }: { request: SubmitTxRequestV2; baseUR
|
|
|
193
193
|
}
|
|
194
194
|
```
|
|
195
195
|
|
|
196
|
-
Poll the processing status with `useSwapsApiSubmitTxStatus` — it requires **both** `txHash` and `srcChainKey` (the
|
|
196
|
+
Poll the processing status with `useSwapsApiSubmitTxStatus` — it requires **both** `txHash` and `srcChainKey` (the status endpoint needs the source chain key) and stops polling on `solved` / `failed`:
|
|
197
197
|
|
|
198
198
|
```tsx
|
|
199
199
|
import { useSwapsApiSubmitTxStatus } from '@sodax/dapp-kit';
|
|
@@ -26,6 +26,18 @@ Leveraged-yield ERC-4626 vaults on Sonic. Deposit any token → `lsoda*` shares,
|
|
|
26
26
|
| `useLeverageYieldTotalAssets` | Vault TVL (18-dp bigint) |
|
|
27
27
|
| `useLeverageYieldPreviewRedeem` | Assets for N shares (pass `1e18` for price-per-share) |
|
|
28
28
|
| `useLeverageYieldShareBalances` | Per-chain share balances (array via `useQueries`) |
|
|
29
|
+
| `useLeveragePositions` | List an owner's leverage-position clones (needs `positionFactory` config) |
|
|
30
|
+
| `useLeveragePositionsForUser` | The same, resolved from a spoke address's hub wallet |
|
|
31
|
+
| `useLeveragePositionInfo` | Static descriptor for one position (owner, both legs, eMode category) |
|
|
32
|
+
| `useLeveragePositionAccount` | Live AAVE account for one position (collateral, debt, LTV, health factor) |
|
|
33
|
+
| `useOpenLeveragePosition` | Open a position and report its intent — `side: 'collateral' \| 'debt'` |
|
|
34
|
+
| `useSubmitLeveragePositionIntent` | `addLeverage` / `decreaseLeverage`, then report the intent |
|
|
35
|
+
| `useRunLeveragePositionOperation` | `withdraw` / `settle` / `cancel` — no intent, nothing to report |
|
|
36
|
+
| `useLeveragePositionPayoutAddress` | Where a withdrawal can be paid; off the hub, not the signer |
|
|
37
|
+
| `useLeveragePositionFundingAllowance` | Is the funding token approved? The spender differs per chain |
|
|
38
|
+
| `useApproveLeveragePositionFunding` | Approve it, against the spender the SDK resolves |
|
|
39
|
+
| `useLeveragePositionCollateral` | Exact aToken balance — what sizes a full exit, less the position's `feeBps` |
|
|
40
|
+
| `useLeveragePositionPending` | The operation slot: is an intent live, does it need settling |
|
|
29
41
|
|
|
30
42
|
> A deposit is a swap-style intent, so it approves the **spoke asset manager** via the swap-domain hooks — there is no leverage-yield-specific approve hook. A withdraw carries `hubWalletSwap: true` and needs no spoke approval.
|
|
31
43
|
|
|
@@ -168,3 +180,156 @@ function WithdrawButton({ vault, srcAddress, outputToken, shares }: { vault: Add
|
|
|
168
180
|
- **Configured fee:** vault flows are monetized via `leverageYield.partnerFee` (else the global `fee`). `swaps.partnerFee` does not apply to them.
|
|
169
181
|
- **Withdraw:** no spoke approval — the hub wallet authorises the share spend via `Connection.sendMessage`. Output lands at `recipient` (defaults to `srcAddress`) on `dstChainKey`.
|
|
170
182
|
- **Reads** (`useLeverageYieldEffectiveApr`, `Position`, `TotalAssets`, `PreviewRedeem`) are already unwrapped — read `data` directly. `useLeverageYieldShareBalances` returns an array; aggregate the `shares` yourself.
|
|
183
|
+
|
|
184
|
+
## Leverage positions vs vaults
|
|
185
|
+
|
|
186
|
+
A vault is one shared ERC-4626 position at a single target LTV. A **leverage position** is one
|
|
187
|
+
AAVE account per user, cloned by `LeveragePositionFactory` — so an owner can hold several at
|
|
188
|
+
different eMode categories and leverage tiers at once, which a vault cannot express because AAVE
|
|
189
|
+
allows one eMode category per address.
|
|
190
|
+
|
|
191
|
+
Positions have no static registry; discover them with `useLeveragePositions({ params: { owner } })`
|
|
192
|
+
and read health with `useLeveragePositionAccount({ params: { position } })`. Health factor is WAD
|
|
193
|
+
(1e18) and comes from the pool's `getUserAccountData`, not the position contract — surface it
|
|
194
|
+
prominently, because there is no keeper deleveraging on the owner's behalf.
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
// @ai-snippets-skip — two-line excerpt; `owner` is the caller's. Exact per-hook shapes are in
|
|
198
|
+
// features/leverage-yield.md.
|
|
199
|
+
const { data: positions } = useLeveragePositions({ params: { owner } });
|
|
200
|
+
const { data: account } = useLeveragePositionAccount({ params: { position: positions?.[0] } });
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
> **Experimental off the hub.** Position writes are proven end to end on Sonic only. From a spoke the
|
|
204
|
+
> inbound half is verified by a fork replay, and the outbound half (exit or cancel delivering back to
|
|
205
|
+
> the source chain) has not run on mainnet. Prefer `srcChainKey: 'sonic'` unless the integrator has
|
|
206
|
+
> accepted that risk. **Bitcoin is refused outright** — the position paths do not resolve the Bound
|
|
207
|
+
> trading wallet, so a Bitcoin `srcChainKey` returns `VALIDATION_FAILED` instead of funding the wrong
|
|
208
|
+
> hub wallet.
|
|
209
|
+
|
|
210
|
+
Every position call is `onlyOwner` against the user's **hub wallet**, so a builder's transaction sent
|
|
211
|
+
from the signer reverts `NotOwner`. Three mutation hooks run the calls as that wallet — locally
|
|
212
|
+
through the wallet router on Sonic, relayed from anywhere else.
|
|
213
|
+
|
|
214
|
+
**Which hook is decided by the operation, not by preference.** `addLeverage` and
|
|
215
|
+
`decreaseLeverage` only *post* a solver intent, and an intent the solver was never told about expires
|
|
216
|
+
unfilled — leaving the owner funded with leverage that never arrives. `withdraw`, `settle` and
|
|
217
|
+
`cancel` are synchronous on the hub and need no notification.
|
|
218
|
+
|
|
219
|
+
| operation | hook | notifies |
|
|
220
|
+
| --- | --- | --- |
|
|
221
|
+
| open (collateral or debt side) | `useOpenLeveragePosition` | yes |
|
|
222
|
+
| `buildAddLeverage` / `buildDecreaseLeverage` | `useSubmitLeveragePositionIntent` | yes |
|
|
223
|
+
| `buildPositionWithdraw` / `buildSettlePosition` / `buildCancelPositionOperation` | `useRunLeveragePositionOperation` | no |
|
|
224
|
+
|
|
225
|
+
TypeScript enforces the rows: the first two builders return `PositionIntentCall`, the last three
|
|
226
|
+
`PositionDirectCall`, and each hook accepts only its own. Position fees come from `getPositionInfo`
|
|
227
|
+
for an existing position — `getEffectivePositionFee()` is what a NEW one would carry, and the two
|
|
228
|
+
disagree once config changes, since a position's fee is fixed at creation.
|
|
229
|
+
|
|
230
|
+
The hooks are thin over SDK methods of the same shape — `sodax.leverageYield.openLeveragePosition`,
|
|
231
|
+
`submitLeveragePositionIntent`, `runLeveragePositionOperation` — so a non-React caller gets the same
|
|
232
|
+
pairing. The low-level `openPosition` / `operatePosition` / `notifySolver` remain for anyone driving
|
|
233
|
+
the relay by hand.
|
|
234
|
+
|
|
235
|
+
```ts
|
|
236
|
+
// @ai-snippets-skip — illustrative open flow; the funding and sizing values are the caller's.
|
|
237
|
+
// Exact per-hook shapes are in features/leverage-yield.md.
|
|
238
|
+
import { useOpenLeveragePosition, useSodaxContext } from '@sodax/dapp-kit';
|
|
239
|
+
|
|
240
|
+
const { sodax } = useSodaxContext();
|
|
241
|
+
const { mutateAsync: openPosition } = useOpenLeveragePosition();
|
|
242
|
+
|
|
243
|
+
// 1. Approve, and wait for it — `approvePositionFunding` resolves the right spender per chain.
|
|
244
|
+
const approved = await sodax.leverageYield.approvePositionFunding({
|
|
245
|
+
srcChainKey, srcAddress, token, amount, walletProvider,
|
|
246
|
+
});
|
|
247
|
+
if (!approved.ok) throw approved.error;
|
|
248
|
+
|
|
249
|
+
// 2. Open. `borrowAmount` / `minCollateralOut` come from `sizeLeverageBorrow` + `projectLeverageLeg`
|
|
250
|
+
// (sized below) — never from oracle parity. The hook reports the intent for you.
|
|
251
|
+
const result = await openPosition({
|
|
252
|
+
side: 'collateral', // 'debt' funds with the debt token instead
|
|
253
|
+
params: { srcChainKey, srcAddress, token, amount, eModeCategory, borrowToken, borrowAmount, minCollateralOut },
|
|
254
|
+
walletProvider,
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
// 3. Resolving means the intent is LIVE, not that the position is open. Check this before telling
|
|
258
|
+
// the user to wait: false means nothing will fill it before it expires.
|
|
259
|
+
if (!result.notified) showWarning(result.notifyError);
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Payouts have one more trap: `withdraw` pays to an address **on the hub**, which off the hub is not the
|
|
263
|
+
signer. `useLeveragePositionPayoutAddress({ params: { chainKey, signerAddress, owner } })` returns the one that works.
|
|
264
|
+
|
|
265
|
+
**Sizing the leg.** The hook borrows against what the solver actually paid, so the pool sees
|
|
266
|
+
`deposit + solver output`, never `deposit × leverage` — size from oracle parity and the borrow reverts
|
|
267
|
+
at fill with Aave `'36'`. Two SDK helpers size it, with the solver quote taken between them:
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
// @ai-snippets-skip — illustrative sizing flow; the reserves, prices and risk params are the
|
|
271
|
+
// caller's. Exact shapes are in features/leverage-yield.md.
|
|
272
|
+
import { sizeLeverageBorrow, projectLeverageLeg, type LeverageLegRequest } from '@sodax/sdk';
|
|
273
|
+
|
|
274
|
+
const request: LeverageLegRequest = {
|
|
275
|
+
side: 'collateral', // 'debt' when funding with the debt token instead
|
|
276
|
+
deposit, depositDecimals, collateralPriceUsd, borrowPriceUsd, borrowDecimals, leverage,
|
|
277
|
+
feeBps, // the position's own PositionConfig fee — borrowed on top, so it moves LTV
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
// Quote `intentInput`, not `borrowAmount`: a debt-side open hands your contribution to the solver too.
|
|
281
|
+
const { borrowAmount, intentInput } = sizeLeverageBorrow(request);
|
|
282
|
+
// `getPositionLegQuote` names the HUB reserves the intent actually swaps and quotes gross — the two
|
|
283
|
+
// details a hand-rolled `getQuote` gets wrong, and both only surface as an unfillable floor.
|
|
284
|
+
const quote = await sodax.leverageYield.getPositionLegQuote({
|
|
285
|
+
inputHubToken: borrowReserve.underlyingAsset, // the hub reserve ADDRESS, not the reserve object
|
|
286
|
+
outputHubToken: collateralReserve.underlyingAsset,
|
|
287
|
+
amount: intentInput,
|
|
288
|
+
});
|
|
289
|
+
if (!quote.ok) throw quote.error;
|
|
290
|
+
|
|
291
|
+
const projected = projectLeverageLeg(
|
|
292
|
+
request,
|
|
293
|
+
{ quotedCollateral: quote.value.quotedAmount, collateralDecimals },
|
|
294
|
+
{ ltv, liquidationThreshold },
|
|
295
|
+
slippagePct,
|
|
296
|
+
);
|
|
297
|
+
if (projected.exceedsMaxLtv) throw new Error(`max ~${projected.usableMaxLeverage.toFixed(2)}x at this quote`);
|
|
298
|
+
// Show `projected.exposureLeverage`, not `leverage`: the position reports the former.
|
|
299
|
+
// Open with `borrowAmount` and `minCollateralOut: projected.minCollateralOut`.
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
`exceedsMaxLtv` is a hard gate, not a warning: post through it and the intent is accepted, then fails
|
|
303
|
+
at fill. `leverage` is a multiple of the DEPOSIT, so the open position reports MORE — the borrow is
|
|
304
|
+
booked in full while the collateral arrives short by the haircut, leaving less equity than was deposited
|
|
305
|
+
(2.00x in, 2.0488x out at 4.657%). Display `projected.exposureLeverage` — measured at the floor, so it
|
|
306
|
+
reads above the fill by the slippage tolerance. Read `ltv` / `liquidationThreshold` from `useEModes` whenever the position sets an
|
|
307
|
+
`eModeCategory`, since a category's LTV replaces the reserve's own. Why parity fails, and what
|
|
308
|
+
`haircut` / `costUsd` are for, is in the SDK's `LEVERAGE_YIELD.md` § "Sizing the leg".
|
|
309
|
+
|
|
310
|
+
Approve the deposit with `approvePositionFunding` (gate on `isPositionFundingAllowanceValid`): the
|
|
311
|
+
spender is the hub wallet on Sonic and the spoke asset manager elsewhere, so a hand-rolled approval
|
|
312
|
+
picks the wrong one half the time. Nothing is ever approved to the factory — it pulls from nobody, and
|
|
313
|
+
`openPosition` funds the position by transferring to the address it will be created at.
|
|
314
|
+
|
|
315
|
+
You can only open a position you own: the factory requires `cfg.owner == msg.sender` and the caller is
|
|
316
|
+
always your hub wallet, so `openPosition` takes no `owner`. Fund someone else with
|
|
317
|
+
`pool.supply(collateral, amount, position, 0)` into a position they already own.
|
|
318
|
+
|
|
319
|
+
`addLeverage` and `decreaseLeverage` only *post* an intent — a solver fills it afterwards, so poll
|
|
320
|
+
`useLeveragePositionPending` rather than treating the receipt as completion. Reporting the intent is
|
|
321
|
+
`useSubmitLeveragePositionIntent`'s job, so do not call `notifySolver` yourself on this path; read
|
|
322
|
+
`notified` on the result instead. It reports the HUB hash, `dstChainTxHash` — off-hub the signed
|
|
323
|
+
`srcChainTxHash` is a different chain's transaction and names no intent at all.
|
|
324
|
+
|
|
325
|
+
**Closing.** Selling only the debt's worth of collateral and then withdrawing the rest leaves the
|
|
326
|
+
owner holding collateral, and the withdrawal can pay out anywhere. Selling the *whole* collateral
|
|
327
|
+
balance instead — `buildDecreaseLeverage` sized by `useLeveragePositionCollateral`, never by dividing
|
|
328
|
+
`totalCollateralBase` out by a price — exits into the debt token: the hook repays the debt and leaves
|
|
329
|
+
the surplus in the position for `buildSettlePosition` to sweep to the owner. A full exit whose fill
|
|
330
|
+
would not cover the debt reverts on the pool's health-factor check rather than half-closing, so check
|
|
331
|
+
the floor covers the debt before posting.
|
|
332
|
+
|
|
333
|
+
> The deployed `leverageYield.positionFactory` ships as a packaged default, so positions work from
|
|
334
|
+
> `new Sodax()` with no configuration. Override it for a fork or a staging deployment; blank it and
|
|
335
|
+
> the SDK fails closed with a lookup error rather than guessing an address.
|
|
@@ -174,7 +174,7 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
|
|
|
174
174
|
|
|
175
175
|
## Swaps API (`sodax.api.swaps`)
|
|
176
176
|
|
|
177
|
-
Typed React Query wrappers over the backend Swaps API
|
|
177
|
+
Typed React Query wrappers over the backend Swaps API (`sodax.api.swaps.*`), one per endpoint. Distinct from the on-chain `swap/` hooks (`useQuote`/`useStatus`/`useSwap`/…), which drive `sodax.swaps` (the `SwapService`).
|
|
178
178
|
|
|
179
179
|
### Tokens · quote · fees · gas (reads)
|
|
180
180
|
|
|
@@ -215,7 +215,7 @@ Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`),
|
|
|
215
215
|
|
|
216
216
|
## Bridge API (`sodax.api.bridge`)
|
|
217
217
|
|
|
218
|
-
Typed React Query wrappers over the backend Bridge API
|
|
218
|
+
Typed React Query wrappers over the backend Bridge API (`sodax.api.bridge.*`). Distinct from the on-chain `bridge/` hooks (`useBridge`/`useBridgeAllowance`/…), which drive `sodax.bridge` (the `BridgeService`). Smaller than the swaps family (no intent/solver surface). The fee / bridgeable-amount / bridgeable quotes are computable client-side (prefer the on-chain `useGetBridgeableAmount` / `sodax.bridge.*` — no round-trip), but are also mirrored here as HTTP hooks for parity.
|
|
219
219
|
|
|
220
220
|
| Hook | Type / Polling |
|
|
221
221
|
|---|---|
|
|
@@ -233,7 +233,7 @@ Typed React Query wrappers over the backend Bridge API v2 (`sodax.api.bridge.*`)
|
|
|
233
233
|
|
|
234
234
|
## Leverage Yield API (`sodax.api.leverageYield`)
|
|
235
235
|
|
|
236
|
-
Typed React Query wrappers over the backend Leverage Yield API
|
|
236
|
+
Typed React Query wrappers over the backend Leverage Yield API (`sodax.api.leverageYield.*`), one per endpoint. Distinct from the on-chain `leverageYield/` hooks (`useLeverageYieldDeposit`/`useLeverageYieldWithdraw`/…), which drive `sodax.leverageYield` (the `LeverageYieldService`). A vault deposit/withdraw IS an intent-based swap, so the intent / gas / fee / submit-tx hooks mirror the swaps family; the vault registry, vault reads and the split deposit/withdraw quote + create-intent hooks are leverage-yield's own.
|
|
237
237
|
|
|
238
238
|
| Hook | Type / Polling |
|
|
239
239
|
|---|---|
|
|
@@ -157,7 +157,7 @@ Backend read hooks (`useBackendIntentByTxHash`, `useBackendIntentByHash`, `useBa
|
|
|
157
157
|
|
|
158
158
|
### Swaps API (`sodax.api.swaps`)
|
|
159
159
|
|
|
160
|
-
Typed wrappers over `sodax.api.swaps.*` (one per Swaps API
|
|
160
|
+
Typed wrappers over `sodax.api.swaps.*` (one per Swaps API endpoint), all keyed `['swapsApi', action, ...]`.
|
|
161
161
|
|
|
162
162
|
| Key | Hook |
|
|
163
163
|
|---|---|
|
|
@@ -186,7 +186,7 @@ Typed wrappers over `sodax.api.swaps.*` (one per Swaps API v2 endpoint), all key
|
|
|
186
186
|
|
|
187
187
|
### Bridge API (`sodax.api.bridge`)
|
|
188
188
|
|
|
189
|
-
Typed wrappers over `sodax.api.bridge.*` (one per Bridge API
|
|
189
|
+
Typed wrappers over `sodax.api.bridge.*` (one per Bridge API endpoint), all keyed `['bridgeApi', action, ...]`.
|
|
190
190
|
|
|
191
191
|
| Key | Hook |
|
|
192
192
|
|---|---|
|
|
@@ -204,7 +204,7 @@ Typed wrappers over `sodax.api.bridge.*` (one per Bridge API v2 endpoint), all k
|
|
|
204
204
|
|
|
205
205
|
### Leverage Yield API (`sodax.api.leverageYield`)
|
|
206
206
|
|
|
207
|
-
Typed wrappers over `sodax.api.leverageYield.*` (one per Leverage Yield API
|
|
207
|
+
Typed wrappers over `sodax.api.leverageYield.*` (one per Leverage Yield API endpoint), all keyed `['leverageYieldApi', action, ...]`.
|
|
208
208
|
|
|
209
209
|
| Key | Hook |
|
|
210
210
|
|---|---|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-dapp-kit-leverage-yield
|
|
3
|
-
description: 'Granular skill for the @sodax/dapp-kit v2 leverage-yield feature only
|
|
3
|
+
description: 'Granular skill for the @sodax/dapp-kit v2 leverage-yield feature only, covering BOTH products: (1) React Query hooks for leveraged-yield ERC-4626 VAULTS on Sonic — useLeverageYieldDeposit and useLeverageYieldWithdraw (build a swap payload), useLeverageYieldVaultSwap (execute it end-to-end), plus reads useLeverageYieldEffectiveApr, useLeverageYieldPosition, useLeverageYieldTotalAssets, useLeverageYieldPreviewRedeem, useLeverageYieldShareBalances; and (2) LEVERAGE POSITIONS — one owner-controlled AAVE account per position, via useOpenLeveragePosition, useSubmitLeveragePositionIntent, useRunLeveragePositionOperation, useApproveLeveragePositionFunding, and the reads useLeveragePositions, useLeveragePositionsForUser, useLeveragePositionInfo, useLeveragePositionAccount, useLeveragePositionCollateral, useLeveragePositionPending, useLeveragePositionPayoutAddress, useLeveragePositionFundingAllowance. Use when a React dapp task is leverage-yield vaults (e.g. "deposit into a leverage vault with dapp-kit", "useLeverageYieldVaultSwap hook", "render vault APR / TVL", "lsoda share balances across chains") OR leverage positions (e.g. "open a leverage position in React", "useOpenLeveragePosition hook", "adjust / increase / decrease leverage", "close a leveraged position", "render position health factor / LTV", "list a user''s leverage positions"). New in v2 — integration only, no v1 migration path. Links into the parent sodax-dapp-kit knowledge tree. For backend/Node, use the sodax-sdk skill.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -13,11 +13,19 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
13
13
|
|
|
14
14
|
## Step 1 — Clarify with user before coding
|
|
15
15
|
|
|
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.
|
|
16
17
|
1. **Deposit or withdraw?** Deposit = any token → `lsoda*` shares (lands in the hub wallet). Withdraw = `lsoda*` shares → any token on any chain.
|
|
17
18
|
2. **Build vs execute.** `useLeverageYieldDeposit` / `useLeverageYieldWithdraw` only *build* a `LeverageYieldSwapPayload`; `useLeverageYieldVaultSwap` *executes* it (create → relay → notify solver). You always need both.
|
|
18
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
20
|
4. **Which reads?** `useLeverageYieldEffectiveApr` (headline APR), `useLeverageYieldPosition` (LTV/health), `useLeverageYieldTotalAssets` (TVL), `useLeverageYieldPreviewRedeem` (price-per-share), `useLeverageYieldShareBalances` (per-chain balances — returns an array).
|
|
20
21
|
|
|
22
|
+
### Step 1b — leverage positions
|
|
23
|
+
|
|
24
|
+
1. **Which mutation?** Decided by the operation, not by preference. Open → `useOpenLeveragePosition`. Leverage change (`buildAddLeverage` / `buildDecreaseLeverage`) → `useSubmitLeveragePositionIntent`. Withdraw / settle / cancel → `useRunLeveragePositionOperation`. The first two report the intent; the third has nothing to report, and routing a leverage change through it leaves an intent nothing will fill. TypeScript enforces this via the `PositionIntentCall` / `PositionDirectCall` brands.
|
|
25
|
+
2. **Approval?** Gate on `useLeveragePositionFundingAllowance`, approve with `useApproveLeveragePositionFunding` — the spender differs per chain and the SDK resolves it. Nothing is ever approved to the factory.
|
|
26
|
+
3. **Sized the leg?** `borrowAmount` / `minCollateralOut` come from `sizeLeverageBorrow` → `getPositionLegQuote` → `projectLeverageLeg`, never oracle parity. Read `ltv` / `liquidationThreshold` from `useEModes` when the position sets an `eModeCategory`.
|
|
27
|
+
4. **Which reads?** `useLeveragePositions` / `useLeveragePositionsForUser` (discovery), `useLeveragePositionAccount` (health/LTV), `useLeveragePositionCollateral` (sizes an exit), `useLeveragePositionPending` (is an intent live), `useLeveragePositionInfo` (this position's own `feeBps`), `useLeveragePositionPayoutAddress` (where a withdrawal can pay — **not a query**, returns synchronously).
|
|
28
|
+
|
|
21
29
|
## Integration workflow (new v2 code)
|
|
22
30
|
|
|
23
31
|
1. [`../integration/knowledge/ai-rules.md`](../integration/knowledge/ai-rules.md) — DO / DO NOT (read first).
|
|
@@ -34,6 +42,17 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
34
42
|
- **Reaching for a `useLeverageYieldApprove` hook.** It doesn't exist — the deposit approves the spoke asset manager, so use the swap-domain hooks.
|
|
35
43
|
- **Quoting on the pre-fee amount.** A deposit's per-intent `partnerFee` is deducted from `inputAmount` before the swap — quote on the post-fee amount or `minOutputAmount` is unfillable.
|
|
36
44
|
|
|
45
|
+
### Leverage-position anti-patterns (dapp-kit)
|
|
46
|
+
|
|
47
|
+
- **Reading `useLeverageYieldPosition` for a leverage position.** That is the **vault's** snapshot. A leverage position's live account is `useLeveragePositionAccount`.
|
|
48
|
+
- **Treating a resolved `useOpenLeveragePosition` as an open position.** It resolves when the intent is LIVE. The hook unwraps the SDK `Result`, so check **`result.notified`** on `mutateAsync`'s value (not `result.value.notified`); `false` means nothing will fill it before it expires. Do not retry on it — that opens a second position.
|
|
49
|
+
- **Routing a leverage change through `useRunLeveragePositionOperation`.** It does not notify. Leverage changes go through `useSubmitLeveragePositionIntent`; the brands refuse the mistake at compile time, so never cast past them.
|
|
50
|
+
- **Calling `notifySolver` yourself after `useSubmitLeveragePositionIntent`.** The hook already reports the intent — read `notified` on its result instead.
|
|
51
|
+
- **Awaiting `useLeveragePositionPayoutAddress` like a query.** It is synchronous: `Address | undefined`, no `data` / `isLoading`. Off the hub a withdrawal pays to a hub address that is **not** the signer, which is exactly what it resolves.
|
|
52
|
+
- **Sizing an exit from `totalCollateralBase`.** Display-only. Use `useLeveragePositionCollateral` — an over-sized `decreaseLeverage` reverts at fill time and the intent silently expires.
|
|
53
|
+
- **Charging an existing position the configured fee.** Read `feeBps` from `useLeveragePositionInfo`; `getEffectivePositionFee()` is what a NEW position would carry.
|
|
54
|
+
- **Treating the mutation receipt as completion.** A solver fills a leverage change afterwards — poll `useLeveragePositionPending`.
|
|
55
|
+
|
|
37
56
|
## Verification
|
|
38
57
|
|
|
39
58
|
1. `pnpm tsc --noEmit` clean.
|
|
@@ -41,6 +60,8 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
41
60
|
3. `useLeverageYieldShareBalances` consumers treat `data` as an array and aggregate.
|
|
42
61
|
4. Withdraw flows do not gate on `useSwapAllowance`.
|
|
43
62
|
5. Mutation flows use `mutateAsyncSafe` and branch on `result.ok`; reads read `data` directly (no `.ok`/`.value`).
|
|
63
|
+
6. Positions: leverage changes use `useSubmitLeveragePositionIntent` (never `useRunLeveragePositionOperation`), `notified` is checked on every open and leverage change, and exits are sized from `useLeveragePositionCollateral` with the fee from `useLeveragePositionInfo`.
|
|
64
|
+
7. Positions: funding is gated on `useLeveragePositionFundingAllowance` + `useApproveLeveragePositionFunding`, and `borrowAmount` / `minCollateralOut` trace back to `sizeLeverageBorrow` + `projectLeverageLeg`.
|
|
44
65
|
|
|
45
66
|
## Related granular skills (same family)
|
|
46
67
|
|
|
@@ -53,7 +53,7 @@ Read-only. No `walletProvider` involved. Convert to single-object query shape.
|
|
|
53
53
|
+ await submit({ request: swapPayload, apiConfig: { baseURL: 'https://...' } }); // v2: per-call config
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
-
`useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTxStatus`) now requires **both** `txHash` and `srcChainKey` (the
|
|
56
|
+
`useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTxStatus`) now requires **both** `txHash` and `srcChainKey` (the status endpoint needs the source chain key) — a v1 call that passed only a tx hash won't run until `srcChainKey` is supplied. The full Swaps API surface is now wrapped as `useSwapsApi*` hooks (see the integration `hooks-index`).
|
|
57
57
|
|
|
58
58
|
## Shared utilities
|
|
59
59
|
|
|
@@ -52,7 +52,7 @@ These keep their name but their TypeScript signature is different. Usually requi
|
|
|
52
52
|
| `useRequestTrustline` → `useEstablishTrustline` | Canonical mutation hook: `{ mutationOptions }` in, `SafeUseMutationResult` out, vars `{ token, amount, srcChainKey, walletProvider }`. `useRequestTrustline` remains as a deprecated wrapper with its 2.0.0 shape — positional `(token: string \| undefined)` (ignored) and `{ requestTrustline, isLoading, isRequested, error, data }` — and is removed in the next major. |
|
|
53
53
|
| `useBackendOrderbook` / `useBackendAllMoneyMarketBorrowers` | Pagination MUST be nested under `params`: `{ params: { pagination: { offset, limit } } }`. |
|
|
54
54
|
| `useBackendUserIntents` | Data is `UserIntentsResponse = { items: IntentResponse[], total, offset, limit }` — NOT a bare array. Access `data?.items`. |
|
|
55
|
-
| `useSwapsApiSubmitTx` / `useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTx` / `useBackendSubmitSwapTxStatus`) | Renamed + moved to the `swapsApi/` namespace (keys now `['swapsApi', …]`). Mutation `apiConfig` moved from hook init to `mutate(vars)`; the status query now requires `srcChainKey`. The rest of the Swaps API
|
|
55
|
+
| `useSwapsApiSubmitTx` / `useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTx` / `useBackendSubmitSwapTxStatus`) | Renamed + moved to the `swapsApi/` namespace (keys now `['swapsApi', …]`). Mutation `apiConfig` moved from hook init to `mutate(vars)`; the status query now requires `srcChainKey`. The rest of the Swaps API is newly wrapped as `useSwapsApi*` hooks. |
|
|
56
56
|
| All migration hooks | **NEW**: 6 per-action hooks replacing v1's single `useMigrate`. See [`deleted-hooks.md`](deleted-hooks.md). |
|
|
57
57
|
| `useMigrationAllowance` | Query params nest under `params` with inner field literally named `params` (NOT `payload`): `{ params: { params: <migration-params>, action: 'migrate' \| 'revert' } }`. |
|
|
58
58
|
| `BalnMigrateParams` (used by `useMigrateBaln`) | NEW required field `stake: boolean`. `lockupPeriod` is the `LockupPeriod` enum (5 members; values in seconds, not months). |
|
|
@@ -35,9 +35,9 @@ If the user has already picked a single feature, load the matching granular skil
|
|
|
35
35
|
| Stuck-asset recovery | [`./recovery/SKILL.md`](./recovery/SKILL.md) | "recover stuck assets on Sonic", "RecoveryService", "withdrawHubAsset" |
|
|
36
36
|
| Sponsored Stellar account activation | [`./sponsoring/SKILL.md`](./sponsoring/SKILL.md) | "activate a Stellar account", "user has no XLM", "sponsor base reserve", "sodax.sponsoring" |
|
|
37
37
|
| Backend HTTP client (intents, orderbook, MM reads) | [`./backend-api/SKILL.md`](./backend-api/SKILL.md) | "getIntentByHash", "Sodax backend API", "orderbook", "custom IConfigApiV1" |
|
|
38
|
-
| Swaps API
|
|
39
|
-
| Leverage Yield API
|
|
40
|
-
| Bridge API
|
|
38
|
+
| Swaps API client (quote, create-intent, submit-tx, fees) | [`./swaps-api/SKILL.md`](./swaps-api/SKILL.md) | "sodax.api.swaps", "swap quote from backend", "submit swap tx", "swaps API v2" |
|
|
39
|
+
| Leverage Yield API client (vault reads, APR, deposit/withdraw quote + intents) | [`./leverage-yield-api/SKILL.md`](./leverage-yield-api/SKILL.md) | "sodax.api.leverageYield", "vault APR from backend", "vault position from API", "leverage-yield API v2" |
|
|
40
|
+
| Bridge API client (allowance/approve, create-intent, submit-tx, tokens, fee/bridgeable discovery) | [`./bridge-api/SKILL.md`](./bridge-api/SKILL.md) | "sodax.api.bridge", "createBridgeIntent via backend", "submit bridge tx", "bridge API v2" |
|
|
41
41
|
|
|
42
42
|
Load this broad skill (keep reading below) when:
|
|
43
43
|
|
|
@@ -52,7 +52,7 @@ Granular skill for `BackendApiService` — `sodax.backendApi`. HTTP client used
|
|
|
52
52
|
## Related granular skills (same family)
|
|
53
53
|
|
|
54
54
|
- [`../swap/SKILL.md`](../swap/SKILL.md) — `sodax.api.swaps.submitTx` is the backend half of the step-by-step swap flow.
|
|
55
|
-
- [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the full typed Swaps API
|
|
55
|
+
- [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the full typed Swaps API client (`sodax.api.swaps`): quote, create-intent, submit-tx, fees, status.
|
|
56
56
|
- [`../money-market/SKILL.md`](../money-market/SKILL.md) — `BackendApiService` is the canonical source of MM position reads.
|
|
57
57
|
- [`../partner/SKILL.md`](../partner/SKILL.md), [`../recovery/SKILL.md`](../recovery/SKILL.md) — diagnostics for failures via intent / tx lookups.
|
|
58
58
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-sdk-bridge-api
|
|
3
|
-
description: 'Granular skill for the @sodax/sdk v2 Bridge API client — `sodax.api.bridge` (class BridgeApiService), a typed HTTP client for the backend Bridge API
|
|
3
|
+
description: 'Granular skill for the @sodax/sdk v2 Bridge API client — `sodax.api.bridge` (class BridgeApiService), a typed HTTP client for the backend Bridge API (`/bridge/*`: tokens, allowance/approve, create-bridge-intent, submit-tx + status, fee/bridgeable-amount/bridgeable discovery). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the bridge backend directly (e.g. "sodax.api.bridge", "createBridgeIntent via the backend API", "submit bridge tx", "poll bridge submit-tx status", "bridge API v2", "point bridge at a custom endpoint", "bridge.useBackendSubmitTx"). For the higher-level end-to-end bridge orchestrator use the `bridge` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Bridge API (Core SDK granular skill)
|
|
7
7
|
|
|
8
8
|
Granular skill for `sodax.api.bridge` (class `BridgeApiService`) — the typed HTTP client for the backend
|
|
9
|
-
**Bridge API
|
|
9
|
+
**Bridge API** (`/bridge/*`). `sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the bridge
|
|
10
10
|
client. One method per endpoint; every method returns `Promise<Result<T>>` (never throws) and
|
|
11
11
|
validates the response. Errors carry `feature: 'backend'`, `context.api: 'bridge'`, `context.endpoint`.
|
|
12
12
|
|
|
@@ -138,7 +138,7 @@ Sodax
|
|
|
138
138
|
├── partners — PartnerService (partner fee claiming)
|
|
139
139
|
├── recovery — RecoveryService (withdraw stuck hub-wallet assets)
|
|
140
140
|
├── backendApi — BackendApiService (intent lookup, orderbook, money-market reads, config fetching)
|
|
141
|
-
├── api — alias for backendApi; `api.swaps` is SwapsApiService (typed Swaps API
|
|
141
|
+
├── api — alias for backendApi; `api.swaps` is SwapsApiService (typed Swaps API client)
|
|
142
142
|
├── config — ConfigService (dynamic config; see § 4)
|
|
143
143
|
├── hubProvider — HubProvider (hub contract interactions; concrete impl `EvmHubProvider`)
|
|
144
144
|
└── spoke — SpokeService (per-chain-family router; see § 2)
|
|
@@ -15,9 +15,9 @@ One file per feature service. Each file documents the v2 API surface, common cal
|
|
|
15
15
|
| [`recovery.md`](recovery.md) | `RecoveryService` | Withdraw stuck hub-wallet assets back to a spoke chain. |
|
|
16
16
|
| [`backend-api.md`](backend-api.md) | `BackendApiService` | HTTP client for backend services: swap-tx submission, intent / orderbook lookups, money-market reads. |
|
|
17
17
|
| [`sponsoring.md`](sponsoring.md) | `SponsoringService` | Stellar account activation via sponsored reserves. The sponsor pays the base reserve; the user's wallet signs. |
|
|
18
|
-
| [`swaps-api.md`](swaps-api.md) | `SwapsApiService` | Typed HTTP client for the backend Swaps API
|
|
19
|
-
| [`bridge-api.md`](bridge-api.md) | `BridgeApiService` | Typed HTTP client for the backend Bridge API
|
|
20
|
-
| [`leverage-yield-api.md`](leverage-yield-api.md) | `LeverageYieldApiService` | Typed HTTP client for the backend Leverage Yield API
|
|
18
|
+
| [`swaps-api.md`](swaps-api.md) | `SwapsApiService` | Typed HTTP client for the backend Swaps API (`sodax.api.swaps`, `/swaps/*`). Quote, create-intent, submit-tx + status, fees. |
|
|
19
|
+
| [`bridge-api.md`](bridge-api.md) | `BridgeApiService` | Typed HTTP client for the backend Bridge API (`sodax.api.bridge`, `/bridge/*`). Allowance/approve/create-intent, submit-tx + status, tokens. |
|
|
20
|
+
| [`leverage-yield-api.md`](leverage-yield-api.md) | `LeverageYieldApiService` | Typed HTTP client for the backend Leverage Yield API (`sodax.api.leverageYield`, `/leverage-yield/*`). Vault registry + reads, deposit/withdraw quote + intents, submit-tx + status, fees. |
|
|
21
21
|
|
|
22
22
|
All feature services are constructed and wired by the `Sodax` facade. You don't instantiate them directly — access them via `sodax.swaps`, `sodax.moneyMarket`, etc. See [`../architecture.md`](../architecture.md) for the service graph.
|
|
23
23
|
|
|
@@ -103,7 +103,7 @@ The `IConfigApiV1` interface itself still matters for both patterns — every me
|
|
|
103
103
|
|
|
104
104
|
- v1 → v2 migration of `BackendApiService` (the load-bearing change: every method now returns `Promise<Result<T>>`): [`features/backend-api.md`](../../../migration-v1-to-v2/knowledge/features/backend-api.md).
|
|
105
105
|
- The full submit-tx flow with `createIntent` upstream: [`./swap.md`](swap.md) § "Backend submit-tx flow".
|
|
106
|
-
- The full typed Swaps API
|
|
106
|
+
- The full typed Swaps API client (`sodax.api.swaps`, 21 endpoints — quote, create-intent, submit-tx, fees, status, …): [`./swaps-api.md`](swaps-api.md).
|
|
107
107
|
- Partner-fee handling (separate service): [`./partner.md`](partner.md).
|
|
108
108
|
- Stuck-asset recovery (separate service): [`./recovery.md`](recovery.md).
|
|
109
109
|
- Error model context fields (`error.context.api`, `error.context.method`): [`../reference/`](../reference/) § 3.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Bridge API — `BridgeApiService`
|
|
2
2
|
|
|
3
|
-
Typed HTTP client for the backend **Bridge API
|
|
3
|
+
Typed HTTP client for the backend **Bridge API** (`/bridge/*`). Reachable as `sodax.api.bridge`
|
|
4
4
|
(`sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the `BridgeApiService` instance). One method
|
|
5
5
|
per endpoint. Every method returns `Promise<Result<T>>` — it **never throws** — and every
|
|
6
6
|
response is validated at runtime against a valibot schema, so a backend contract drift surfaces as
|
|
@@ -8,8 +8,15 @@ response is validated at runtime against a valibot schema, so a backend contract
|
|
|
8
8
|
|
|
9
9
|
Access: `sodax.api.bridge`. Service class: `BridgeApiService`. **Errors:** every failure (network, timeout,
|
|
10
10
|
non-2xx HTTP, or response-shape mismatch) returns `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with
|
|
11
|
-
`feature: 'backend'`, `context.api: 'bridge'`, and `context.endpoint` (the path)
|
|
12
|
-
is on `error.cause
|
|
11
|
+
`feature: 'backend'`, `context.api: 'bridge'`, and `context.endpoint` (the path). The underlying failure
|
|
12
|
+
is preserved on `error.cause` — a `BridgeApiError` from the `@sodax/bridge-api` client this service wraps
|
|
13
|
+
(read its `code`: `NETWORK_ERROR` | `TIMEOUT_ERROR` | `HTTP_ERROR` | `PARSE_ERROR` | `VALIDATION_ERROR`;
|
|
14
|
+
the same code is mirrored on `error.context.code`, and both `BridgeApiError` and the `BridgeApiErrorCode`
|
|
15
|
+
union are re-exported from `@sodax/sdk`). Idempotent
|
|
16
|
+
reads/polls (and pure-compute POSTs like `getFee`) retry transient failures; mutating calls do not —
|
|
17
|
+
except the apiguard's transient key-verification `503`, which the wire client replays for every call
|
|
18
|
+
(the guard rejects before the handler runs). A `401`/`403` is terminal until the consumer fixes the key.
|
|
19
|
+
Like `sodax.api.swaps`, the bridge **HTTP client** is uniformly `feature: 'backend'`
|
|
13
20
|
(with a per-service `context.api` tag — `'bridge'`).
|
|
14
21
|
|
|
15
22
|
> Lower-level than `sodax.bridge` (the `BridgeService` orchestrator that deposits + relays end-to-end).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Leverage Yield API — `LeverageYieldApiService`
|
|
2
2
|
|
|
3
|
-
Typed HTTP client for the backend **Leverage Yield API
|
|
3
|
+
Typed HTTP client for the backend **Leverage Yield API** (`/leverage-yield/*`). Reachable as
|
|
4
4
|
`sodax.api.leverageYield` (`sodax.api` is an alias for `sodax.backendApi`; `.leverageYield` is the
|
|
5
5
|
`LeverageYieldApiService` instance). One method per endpoint (33 total). Every method returns
|
|
6
6
|
`Promise<Result<T>>` — it **never throws** — and every response is validated at runtime against a valibot
|
|
@@ -4,7 +4,9 @@ Leveraged-yield ERC-4626 vaults on the Sonic hub. A vault loops supply → borro
|
|
|
4
4
|
|
|
5
5
|
Access: `sodax.leverageYield`. Service class: `LeverageYieldService`. Feature tag for errors: `'leverageYield'`.
|
|
6
6
|
|
|
7
|
-
> **
|
|
7
|
+
> **Two products on one service.** Everything above the "Leverage positions" section is the **vault** — one shared ERC-4626 position at a single target LTV, entered and exited as an intent swap. A **leverage position** is the unpooled counterpart: one owner-controlled AAVE account per position, cloned by `LeveragePositionFactory`, with its own eMode category and leverage tier. They share the service and nothing else — vault methods take a `vault` address, position methods take a `position` address or open a new clone.
|
|
8
|
+
|
|
9
|
+
> **Backend HTTP client:** for the typed `sodax.api.leverageYield` client that calls the backend Leverage Yield API directly (vault reads, deposit/withdraw quotes + intents, submit-tx), see [`leverage-yield-api.md`](leverage-yield-api.md). Opting into `new Sodax({ leverageYield: { useBackendSubmitTx: true } })` routes this service's `vaultSwap` through that client's submit-tx flow (with client-side fallback).
|
|
8
10
|
|
|
9
11
|
## How it works
|
|
10
12
|
|
|
@@ -169,7 +171,7 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
|
|
|
169
171
|
|
|
170
172
|
## Error codes
|
|
171
173
|
|
|
172
|
-
`feature: 'leverageYield'`. Action discriminator on `context.action`: `'deposit' | 'withdraw' | 'approve' | 'allowanceCheck' | 'vaultSwap'`. Read methods partition on `context.method`.
|
|
174
|
+
`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`.
|
|
173
175
|
|
|
174
176
|
| Method | Narrow code union |
|
|
175
177
|
|---|---|
|
|
@@ -181,9 +183,182 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
|
|
|
181
183
|
| `approve` | `VALIDATION_FAILED \| APPROVE_FAILED \| UNKNOWN` |
|
|
182
184
|
| `isAllowanceValid` | `VALIDATION_FAILED \| ALLOWANCE_CHECK_FAILED \| UNKNOWN` (action `'allowanceCheck'`) |
|
|
183
185
|
| Read methods | `VALIDATION_FAILED \| LOOKUP_FAILED \| UNKNOWN` (with `method` discriminator) |
|
|
186
|
+
| `openPosition`, `openPositionFromDebtToken`, `openLeveragePosition` | `LeverageYieldSwapError \| LeverageYieldLookupError` — the swap subset plus `LOOKUP_FAILED` (hub-wallet / factory resolution). `VALIDATION_FAILED` with `field: 'srcChainKey'` is the Bitcoin refusal |
|
|
187
|
+
| `operatePosition`, `submitLeveragePositionIntent`, `runLeveragePositionOperation` | `LeverageYieldSwapError` |
|
|
188
|
+
| `getPositionLegQuote` | same as `getQuote` — a `SolverErrorResponse` arm plus the lookup subset; guard with `isSodaxError` |
|
|
189
|
+
| `isPositionFundingAllowanceValid` / `approvePositionFunding` | `ALLOWANCE_CHECK_FAILED` / `APPROVE_FAILED` subsets (actions `'allowanceCheck'` / `'approve'`) |
|
|
190
|
+
| Position reads + `getEffectivePositionFee` | `VALIDATION_FAILED \| LOOKUP_FAILED \| UNKNOWN`. A blanked `positionFactory` fails closed here |
|
|
184
191
|
|
|
185
192
|
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.
|
|
186
193
|
|
|
194
|
+
## Leverage positions
|
|
195
|
+
|
|
196
|
+
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.
|
|
197
|
+
|
|
198
|
+
The factory ships as a packaged default, so `new Sodax()` drives positions with no configuration. Override only to point at a fork or staging deployment (`new Sodax({ leverageYield: { positionFactory: '0x…' } })`). Blanking it deliberately is honoured and factory-backed methods then fail closed with `LOOKUP_FAILED` rather than guessing an address. Position-only reads (`getPositionInfo`, `getPositionAccount`, `getPositionCollateralBalance`, `getPositionPendingState`) target the position directly and never need the factory.
|
|
199
|
+
|
|
200
|
+
> **`@experimental` off the hub.** Proven end to end on Sonic only. From a spoke the inbound half is verified by a fork replay of a real relayed message; the outbound half (an exit or cancel delivering the underlying back to the source chain) has never run on mainnet. **Bitcoin is refused outright** — in TRADING mode the deposit is pulled from the Bound trading wallet and these paths do not derive the hub wallet from it, so a Bitcoin `srcChainKey` returns `VALIDATION_FAILED` (`field: 'srcChainKey'`) instead of funding the wrong wallet.
|
|
201
|
+
|
|
202
|
+
### Reads
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
sodax.leverageYield.listPositions(owner: Address): Promise<Result<readonly Address[], LeverageYieldLookupError>>;
|
|
206
|
+
sodax.leverageYield.listPositionsForUser(srcChainKey, srcAddress): Promise<Result<readonly Address[], …>>; // POSITIONAL args, not an object
|
|
207
|
+
sodax.leverageYield.getPositionInfo(position: Address): Promise<Result<LeveragePosition, …>>;
|
|
208
|
+
sodax.leverageYield.getPositionAccount(position: Address): Promise<Result<LeveragePositionAccount, …>>;
|
|
209
|
+
sodax.leverageYield.getPositionCollateralBalance(position, collateral?): Promise<Result<LeveragePositionCollateral, …>>;
|
|
210
|
+
sodax.leverageYield.getPositionPendingState(position: Address): Promise<Result<LeveragePositionPendingState, …>>;
|
|
211
|
+
sodax.leverageYield.predictPosition(creator, owner, positionId?): Promise<Result<Address, …>>; // defaults to the next id
|
|
212
|
+
sodax.leverageYield.getEffectivePositionFee(override?): Result<{ feeReceiver: Address; feeBps: number }, …>; // SYNCHRONOUS
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
| Type | Fields |
|
|
216
|
+
|---|---|
|
|
217
|
+
| `LeveragePosition` | `{ address, owner, collateral, borrowToken, eModeCategory, feeBps, feeReceiver }` — static descriptor, fee fixed at creation |
|
|
218
|
+
| `LeveragePositionAccount` | `{ totalCollateralBase, totalDebtBase, availableBorrowsBase, currentLiquidationThreshold, ltv, healthFactor }` — all bigint |
|
|
219
|
+
| `LeveragePositionCollateral` | `{ aToken, balance }` — exact aToken balance in the collateral reserve's decimals |
|
|
220
|
+
| `LeveragePositionPendingState` | `{ kind: number, isLive: boolean, needsSettle: boolean }` |
|
|
221
|
+
|
|
222
|
+
`getPositionAccount` reads `getUserAccountData` on the pool, not the position contract (which keeps no accounting). `healthFactor` is WAD (1e18); the `*Base` figures use the pool oracle's 8-decimal base unit and are **display-only**. Any amount going into a transaction comes from `getPositionCollateralBalance` — dividing base currency back out by a price lands only *near* the balance, and a `decreaseLeverage` asking for more collateral than the position holds does not fail on submission: the hook's `transferFrom` reverts at fill time and the intent silently expires.
|
|
223
|
+
|
|
224
|
+
### Writes — use the high-level calls
|
|
225
|
+
|
|
226
|
+
`openPosition`, `openPositionFromDebtToken` and `operatePosition` only **post** the intent. Reporting it is a separate `notifySolver` call, and an unreported intent expires unfilled — the owner ends up funded with leverage that never arrives and nothing said so. Three methods pair the two steps, and which one to use is decided by the operation, not by preference:
|
|
227
|
+
|
|
228
|
+
| operation | method | notifies |
|
|
229
|
+
|---|---|---|
|
|
230
|
+
| open, either side | `openLeveragePosition({ side?, params, walletProvider })` | yes |
|
|
231
|
+
| `buildAddLeverage` / `buildDecreaseLeverage` | `submitLeveragePositionIntent({ params: { srcChainKey, srcAddress, calls }, walletProvider })` | yes |
|
|
232
|
+
| `buildPositionWithdraw` / `buildSettlePosition` / `buildCancelPositionOperation` | `runLeveragePositionOperation(…)` | no |
|
|
233
|
+
|
|
234
|
+
`withdraw`, `settle` and `cancel` are synchronous on the hub and need no notification. **The compiler enforces the rows:** `buildAddLeverage` / `buildDecreaseLeverage` return `PositionIntentCall`, the other three return `PositionDirectCall`, and each method accepts only its own. The brands are type-only and erased at runtime. A direct call may ride along in a reporting batch (`[buildSettlePosition, buildAddLeverage]` is the sequence batching exists for); an intent call on the route-only path is refused.
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
sodax.leverageYield.openLeveragePosition<K>(params:
|
|
238
|
+
| ({ side?: 'collateral' } & SpokeExecActionParams<K, false, OpenPositionParams<K>>)
|
|
239
|
+
| ({ side: 'debt' } & SpokeExecActionParams<K, false, OpenPositionFromDebtTokenParams<K>>)
|
|
240
|
+
): Promise<Result<LeveragePositionIntentResult, LeverageYieldSwapError | LeverageYieldLookupError>>;
|
|
241
|
+
|
|
242
|
+
sodax.leverageYield.submitLeveragePositionIntent<K>(
|
|
243
|
+
params: SpokeExecActionParams<K, false, PositionOperationParams<K, PositionBatchCall>>
|
|
244
|
+
): Promise<Result<LeveragePositionIntentResult, LeverageYieldSwapError>>;
|
|
245
|
+
|
|
246
|
+
sodax.leverageYield.runLeveragePositionOperation<K>(
|
|
247
|
+
params: SpokeExecActionParams<K, false, PositionOperationParams<K, PositionDirectCall>>
|
|
248
|
+
): Promise<Result<TxHashPair, LeverageYieldSwapError>>;
|
|
249
|
+
|
|
250
|
+
// LeveragePositionIntentResult = { txHashes: TxHashPair; notified: boolean; notifyError?: string }
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
**A failed notification is `ok: true`, deliberately.** The money has already moved and the intent is live on the hub; returning a failure would tell the caller nothing happened, and a caller that retries on failure would open a second position. Read `notified` on the value — `false` means nothing will fill the intent before it expires.
|
|
254
|
+
|
|
255
|
+
### Params shape
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
type PositionFundingParams<K> = {
|
|
259
|
+
srcChainKey: K;
|
|
260
|
+
srcAddress: string; // funds come from here; a failed intent refunds here
|
|
261
|
+
token: string; // token on srcChainKey to fund with
|
|
262
|
+
amount: bigint; // in `token`'s OWN decimals — wrapping to the 18-dp hub reserve happens in the batch
|
|
263
|
+
eModeCategory?: number; // fixed for the life of the position; defaults to 0
|
|
264
|
+
minCollateralOut: bigint; // slippage floor on what the solver must deliver
|
|
265
|
+
partnerFee?: PartnerFee; // percentage variant only; FIXED AT CREATION, capped (see `MAX_POSITION_FEE_BPS` in `packages/sdk/src/leverageYield/LeverageYieldService.ts`); rate and receiver must be set together or not at all; defaults to leverageYield.partnerFee
|
|
266
|
+
};
|
|
267
|
+
type OpenPositionParams<K> = PositionFundingParams<K> & { borrowToken: Address; borrowAmount: bigint };
|
|
268
|
+
type OpenPositionFromDebtTokenParams<K> = PositionFundingParams<K> & { collateral: Address; totalInput: bigint };
|
|
269
|
+
type PositionOperationParams<K, C> = { srcChainKey: K; srcAddress: string; calls: readonly C[] };
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
There is **no `owner`**: the factory requires `cfg.owner == msg.sender` and the caller is always the funder's own hub wallet. That binding is what makes the refund address safe — `originAddress` decides where a cancelled operation's funds go, and past a deadline anyone may trigger that cancel. To fund someone else, supply into a position they already own: `pool.supply(collateral, amount, position, 0)`.
|
|
273
|
+
|
|
274
|
+
### Funding approval
|
|
275
|
+
|
|
276
|
+
**Nothing is ever approved to the factory** — it pulls from nobody. Funding is a transfer to `predictPosition(...)` and the clone supplies whatever it finds, batched with the create so a stale prediction reverts and takes the transfer with it rather than stranding tokens. Do not open two positions for one owner concurrently: the owner's own second open is the only thing that can advance the id, and off the hub the deposit has already reached the hub wallet when the batch reverts — recover it with `sodax.recovery`. The one approval that does exist has a spender that **differs by chain** — the user's own hub wallet on the hub (the pull happens inside the routed batch), the spoke asset manager elsewhere:
|
|
277
|
+
|
|
278
|
+
```ts
|
|
279
|
+
sodax.leverageYield.isPositionFundingAllowanceValid({ srcChainKey, srcAddress, token, amount }): Promise<Result<boolean, …>>;
|
|
280
|
+
sodax.leverageYield.approvePositionFunding({ srcChainKey, srcAddress, token, amount, walletProvider? }): Promise<Result<TxReturnType<K, false>, …>>;
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
`approvePositionFunding` waits for the approve to land before resolving — `verifyTxHash` returns `{ ok: true }` for EVM without waiting, which is why hand-rolled callers were asking users to approve twice.
|
|
284
|
+
|
|
285
|
+
### Sizing the leg — do not skip
|
|
286
|
+
|
|
287
|
+
`borrowAmount` / `minCollateralOut` are yours to supply and **computing them from oracle prices does not work**. Leverage is bought through the solver and the two legs do not trade at their oracle ratio: `LeverageHook` supplies whatever the solver actually paid and only *then* borrows against it, so the pool sees `deposit + solver output`, never `deposit × leverage`. Parity sizing gets the borrow rejected with Aave `'36'` (COLLATERAL_CANNOT_COVER_NEW_BORROW) *after* the solver has filled, unwinding the whole fill. It happened twice on mainnet — once at 11.03x where parity predicted 84% LTV against a real 92.06% and a 91% cap.
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
import { sizeLeverageBorrow, projectLeverageLeg, type LeverageLegRequest } from '@sodax/sdk';
|
|
291
|
+
|
|
292
|
+
// LeverageLegRequest = { side, deposit, depositDecimals, collateralPriceUsd, borrowPriceUsd,
|
|
293
|
+
// borrowDecimals, leverage, feeBps? }
|
|
294
|
+
// 1. Oracle-sized, because there is nothing else yet.
|
|
295
|
+
const { borrowAmount, intentInput } = sizeLeverageBorrow(request);
|
|
296
|
+
// LeverageBorrowSizing = { borrowAmount, intentInput, depositUsd, borrowUsd, feeAmount }
|
|
297
|
+
|
|
298
|
+
// 2. Quote `intentInput`, NOT `borrowAmount` — on a debt-side open the user's contribution goes to
|
|
299
|
+
// the solver too. Use getPositionLegQuote: it names the hub reserves the intent actually swaps
|
|
300
|
+
// and quotes gross, the two details a hand-rolled getQuote gets wrong.
|
|
301
|
+
const leg = await sodax.leverageYield.getPositionLegQuote({
|
|
302
|
+
inputHubToken: borrowReserve.underlyingAsset, // the hub RESERVE ADDRESS, not the reserve object
|
|
303
|
+
outputHubToken: collateralReserve.underlyingAsset,
|
|
304
|
+
amount: intentInput,
|
|
305
|
+
});
|
|
306
|
+
if (!leg.ok) throw leg.error; // PositionLegQuote = { quotedAmount }
|
|
307
|
+
|
|
308
|
+
// 3. Now the honest numbers, from the quote.
|
|
309
|
+
const p = projectLeverageLeg(
|
|
310
|
+
request,
|
|
311
|
+
{ quotedCollateral: leg.value.quotedAmount, collateralDecimals }, // LeverageLegQuote
|
|
312
|
+
{ ltv, liquidationThreshold }, // ReserveRiskParams (numbers, not bps)
|
|
313
|
+
slippagePct,
|
|
314
|
+
);
|
|
315
|
+
if (p.exceedsMaxLtv) throw new Error(`max ~${p.usableMaxLeverage.toFixed(2)}x at this price`);
|
|
316
|
+
// open with { borrowAmount, minCollateralOut: p.minCollateralOut }
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
`LeverageLegProjection = { minCollateralOut, collateralUsd, debtUsd, ltv, healthFactor, exceedsMaxLtv, usableMaxLeverage, haircut, inputUsd, costUsd, exposureLeverage }`. Four things about it:
|
|
320
|
+
|
|
321
|
+
- **`exceedsMaxLtv` is a hard gate, not a warning.** Post through it and the intent is accepted, then fails at fill.
|
|
322
|
+
- **`usableMaxLeverage` is the real ceiling, strictly below `1 / (1 - ltv)`.** At `ltv` 91% with the solver returning 98.77% of parity it is 9.88x — so an 11.03x that looked fine against parity was never available.
|
|
323
|
+
- **Everything is projected from the FLOOR, not the quote** — the floor is the worst fill the intent permits, so if the floor is safe every fill is. `haircut` and `costUsd` are the exception: expected cost measured from the quote, which is what a payback period should use.
|
|
324
|
+
- **`leverage` is a multiple of the DEPOSIT and the open position reports more.** The borrow is booked in full while the collateral arrives short by the haircut, leaving `deposit × (1 - (L-1)h)` of equity. Always higher, never lower: 2.00x requested at a 4.657% haircut reports **2.0488x**. Display `exposureLeverage`, not the number the user chose.
|
|
325
|
+
|
|
326
|
+
Read `ltv` / `liquidationThreshold` from the eMode category whenever the position sets one — a category's LTV replaces the reserve's own. **On a debt-side open the deposit is not collateral**: it is handed to the solver as part of the input, so the only collateral the position ends up with is what the solver delivers. Counting it on both sides is the other half of that 84%-vs-92% miss; `side: 'debt'` handles it.
|
|
327
|
+
|
|
328
|
+
### Fees — read them from the POSITION, not from config
|
|
329
|
+
|
|
330
|
+
`getEffectivePositionFee()` answers what a position created *now* would carry, which is what an **open** needs. An existing position's fee was fixed at creation, so config changes and per-call overrides make the two disagree — `getPositionInfo` returns that position's own `feeBps` / `feeReceiver`, and an adjust or exit has to charge those. The fee is given up **on top of** what the solver is paid, so at a non-zero fee an exit sized at the whole collateral balance leaves nothing for it and cannot settle: the input is `balance × 10_000 / (10_000 + feeBps)`.
|
|
331
|
+
|
|
332
|
+
### Low-level builders
|
|
333
|
+
|
|
334
|
+
Builders return an `EvmRawTransaction` for the caller to run as the hub wallet. Every position write is `onlyOwner` and the owner is the hub wallet, so a builder's transaction sent from the signing address reverts — setting `from` does not help, an address cannot send as another address. Reach for the three high-level methods above; these are the unit they carry.
|
|
335
|
+
|
|
336
|
+
| Builder | Effect |
|
|
337
|
+
|---|---|
|
|
338
|
+
| `buildCreatePositionAndLeverage(…)` | Clone and lever in one tx. `initialAssets` must ALREADY be at the position's address |
|
|
339
|
+
| `buildCreatePositionFromDebtToken(…)` | Open from the **debt** token with no collateral of your own |
|
|
340
|
+
| `buildAddLeverage(…)` | Borrow and swap into more collateral → `PositionIntentCall` |
|
|
341
|
+
| `buildDecreaseLeverage(…)` | Give up collateral to repay debt; with the whole balance this is a close into the debt token → `PositionIntentCall` |
|
|
342
|
+
| `buildPositionWithdraw(…)` | Withdraw collateral out, to any address → `PositionDirectCall` |
|
|
343
|
+
| `buildSettlePosition(…)` | Clear a resolved operation and sweep loose funds to the owner. Permissionless → `PositionDirectCall` |
|
|
344
|
+
| `buildCancelPositionOperation(…)` | Cancel the in-flight operation → `PositionDirectCall` |
|
|
345
|
+
|
|
346
|
+
The two create builders return a `Result` (they need the factory address); the rest target the position directly and return the transaction unwrapped. `encodePositionCalls(txs)` gives the hub-wallet payload if you want to drive `spoke.deposit` / `spoke.sendMessage` yourself.
|
|
347
|
+
|
|
348
|
+
Three behaviours to design around:
|
|
349
|
+
|
|
350
|
+
- **Leverage changes are asynchronous.** `addLeverage` / `decreaseLeverage` only post an intent; poll `getPositionPendingState` instead of treating the receipt as completion. A position refuses a second operation while one is in flight.
|
|
351
|
+
- **Which hash to report.** `TxHashPair` returns both. `srcChainTxHash` is what the user signed; **`dstChainTxHash`** is the hub transaction the intent exists in, and that is the one `notifySolver` needs. On the hub they are the same transaction; from a spoke they are not.
|
|
352
|
+
- **Cancelling returns nothing, because nothing was escrowed.** Posting a position intent moves no funds; cancelling revokes the grant and clears the pending slot.
|
|
353
|
+
|
|
354
|
+
### Closing a position
|
|
355
|
+
|
|
356
|
+
Two exits, differing in what the owner ends up holding. **Into the collateral:** sell only as much collateral as the debt is worth (`buildDecreaseLeverage`), wait for the fill, then `buildPositionWithdraw` the remainder — two operations, and the withdrawal can pay out to any address. Overshoot the debt slightly; it accrues between quoting and filling, and dust debt left behind blocks the withdrawal entirely. **Into the debt token:** sell the collateral balance in one `buildDecreaseLeverage` (net of `feeBps`, see above); the solver delivers more debt token than is owed, the hook repays and leaves the surplus for `buildSettlePosition` to sweep to the position's `owner` — not to whoever signed.
|
|
357
|
+
|
|
358
|
+
A full exit cannot half-happen: were the delivered amount short of the debt, the hook's withdrawal would leave debt against no collateral and the pool's health-factor check rejects it, reverting the whole fill. Quote the full amount and check the floor covers the debt before posting.
|
|
359
|
+
|
|
360
|
+
Collateral top-ups and debt repayment need no SDK call — AAVE accepts both against an arbitrary account (`pool.supply(collateral, amount, position, 0)`, `pool.repay(borrowToken, amount, 2, position)`), so defending a position never waits on a solver fill.
|
|
361
|
+
|
|
187
362
|
## Cross-references
|
|
188
363
|
|
|
189
364
|
- ERC-4626 share-as-token model, APR math, and the deliberate swap-domain duplication: SDK source `packages/sdk/docs/LEVERAGE_YIELD.md`.
|
|
@@ -50,7 +50,7 @@ sodax.swaps.isAllowanceValid<K, Raw>(/* … */): Promise<Result<boolean, SodaxEr
|
|
|
50
50
|
sodax.swaps.getSwapSpeedTier(params: { srcToken: XToken; dstToken: XToken }): SwapSpeedTierResult;
|
|
51
51
|
// Synchronous, offline, no Result wrapper — estimates settlement speed from SDK config alone
|
|
52
52
|
// (no network / on-chain / backend call). SwapSpeedTierResult = { tier: 'fast'|'normal'|'slow', estimatedSeconds }.
|
|
53
|
-
// A token
|
|
53
|
+
// A token whose `vault` is a money-market reserve (sodaAsset) settles faster; an Ethereum leg adds a fixed penalty.
|
|
54
54
|
// Safe to call synchronously while rendering a quote (e.g. an ETA badge next to the output amount).
|
|
55
55
|
|
|
56
56
|
sodax.swaps.getStatus(
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Swaps API — `SwapsApiService`
|
|
2
2
|
|
|
3
|
-
Typed HTTP client for the backend **Swaps API
|
|
3
|
+
Typed HTTP client for the backend **Swaps API** (`/swaps/*`). Reachable as `sodax.api.swaps`
|
|
4
4
|
(`sodax.api` is an alias for `sodax.backendApi`; `.swaps` is the `SwapsApiService` instance). One method
|
|
5
5
|
per endpoint (21 total). Every method returns `Promise<Result<T>>` — it **never throws** — and every
|
|
6
6
|
response is validated at runtime against a valibot schema, so a backend contract drift surfaces as
|
|
@@ -95,7 +95,7 @@ Optional on the type, but no default: the backend does not fill it in, and
|
|
|
95
95
|
`new Sodax({ fee })` / `new Sodax({ swaps: { partnerFee } })` only reach the
|
|
96
96
|
`sodax.swaps` orchestrator — not this wire path. Send the same value on quote and
|
|
97
97
|
create-intent. `checkAllowance` / `approve` inherit the field but ignore it.
|
|
98
|
-
Bridge API
|
|
98
|
+
The Bridge API is different: omitted `partnerFee` falls back to `bridgePartnerFee`.
|
|
99
99
|
|
|
100
100
|
## API key
|
|
101
101
|
|
|
@@ -162,7 +162,7 @@ Both follow the same shape: action methods get the full exec union (`'EXECUTION_
|
|
|
162
162
|
|
|
163
163
|
### Backend / Swaps API (`feature: 'backend'`)
|
|
164
164
|
|
|
165
|
-
`BackendApiService` (`sodax.backendApi`) and the Swaps API
|
|
165
|
+
`BackendApiService` (`sodax.backendApi`) and the Swaps API client (`sodax.api.swaps`) are the HTTP-client layer — not domain features. Every method returns `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with `context.endpoint`, and the transport failure (timeout / non-2xx / response-shape mismatch) preserved on `error.cause`. `context.api` distinguishes the two clients: `'backend'` for `BackendApiService`, `'swaps'` for the `sodax.api.swaps` client.
|
|
166
166
|
|
|
167
167
|
### Leverage Yield (`feature: 'leverageYield'`)
|
|
168
168
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Import everything from `@sodax/sdk`. The barrel re-exports the entire `@sodax/types` surface — you don't need a separate `@sodax/types` dependency.
|
|
4
4
|
|
|
5
|
-
`sodax.api` is an alias for `sodax.backendApi`; `sodax.api.swaps` is the typed Swaps API
|
|
5
|
+
`sodax.api` is an alias for `sodax.backendApi`; `sodax.api.swaps` is the typed Swaps API client (`SwapsApiService`) — see [`../features/swaps-api.md`](../features/swaps-api.md).
|
|
6
6
|
|
|
7
7
|
### Top-level exports
|
|
8
8
|
|
|
@@ -15,6 +15,14 @@ import {
|
|
|
15
15
|
type SodaxDefaultConfig, // static data contract the backend serves / defaults are built from
|
|
16
16
|
type DeepPartial,
|
|
17
17
|
|
|
18
|
+
// Release identity — see "Config version" below
|
|
19
|
+
CONFIG_VERSION,
|
|
20
|
+
SDK_VERSION,
|
|
21
|
+
configVersionFor,
|
|
22
|
+
formatConfigVersion,
|
|
23
|
+
parseConfigVersion,
|
|
24
|
+
type ParsedConfigVersion,
|
|
25
|
+
|
|
18
26
|
// Logging (see recipes/logging.md)
|
|
19
27
|
type SodaxLogger,
|
|
20
28
|
type SodaxLoggerOption,
|
|
@@ -215,6 +223,34 @@ This is a partial list — see `src/index.ts` of the published tarball for the a
|
|
|
215
223
|
---
|
|
216
224
|
|
|
217
225
|
|
|
226
|
+
## Config version
|
|
227
|
+
|
|
228
|
+
`CONFIG_VERSION` identifies the SDK release a SODAX config belongs to. The backend serves this same
|
|
229
|
+
constant from the `@sodax/sdk` release it has installed, so comparing the two answers *are the SDK and
|
|
230
|
+
the API on the same release?* It is derived from the package version:
|
|
231
|
+
`major * 1e6 + minor * 1e4 + patch * 100 + (rc ?? 99)`, where the `99` rc slot means "stable".
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
import { CONFIG_VERSION, SDK_VERSION, configVersionFor, formatConfigVersion, parseConfigVersion } from '@sodax/sdk';
|
|
235
|
+
|
|
236
|
+
SDK_VERSION; // '2.0.0-rc.17' — computed from CONFIG_VERSION, so it cannot go stale
|
|
237
|
+
formatConfigVersion(2_020_099); // '2.2.0'
|
|
238
|
+
parseConfigVersion(2_020_006); // { major: 2, minor: 2, patch: 0, rc: 6 }
|
|
239
|
+
configVersionFor('2.2.0'); // 2_020_099
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
**All three helpers are total** — they return `null` rather than throwing, for anything outside the
|
|
243
|
+
encoding: an out-of-grammar version (`configVersionFor('2.3.0-beta.1')`), a field out of range
|
|
244
|
+
(`configVersionFor('2.2.100')` — minor and patch cap at 99, rc at 98, major at 1..99), or a number that
|
|
245
|
+
is not a config version at all (`parseConfigVersion(235)`, a legacy counter value). Handle the `null`;
|
|
246
|
+
do not assume a value came back.
|
|
247
|
+
|
|
248
|
+
`rc` is `null` for a stable release. `rc: 0` is legal and falsy, so compare against `null` rather than
|
|
249
|
+
testing truthiness.
|
|
250
|
+
|
|
251
|
+
Do not unpack the integer by hand, and do not write your own copy of the formula — the field widths are
|
|
252
|
+
part of the contract and are enforced at release time.
|
|
253
|
+
|
|
218
254
|
## Cross-references
|
|
219
255
|
|
|
220
256
|
- [`README.md`](README.md) — reference index.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-sdk-leverage-yield
|
|
3
|
-
description: 'Granular skill for the @sodax/sdk v2 leverage-yield feature only
|
|
3
|
+
description: 'Granular skill for the @sodax/sdk v2 leverage-yield feature only, covering BOTH products on LeverageYieldService: (1) leveraged-yield ERC-4626 vaults on Sonic — deposit any token → lsoda* shares, withdraw shares → any token (solver-tradeable intent swaps), createVaultIntent/vaultSwap/notifySolver, approve/isAllowanceValid, and reads (getApr, getEffectiveApr, getPosition, getTotalAssets, preview*, getMaxWithdraw*, getShareBalance*, listVaults); and (2) LEVERAGE POSITIONS — one owner-controlled AAVE account per position cloned by LeveragePositionFactory, via openLeveragePosition / submitLeveragePositionIntent / runLeveragePositionOperation, the openPosition / openPositionFromDebtToken / operatePosition low-level pair, position reads (listPositions, listPositionsForUser, getPositionInfo, getPositionAccount, getPositionCollateralBalance, getPositionPendingState, predictPosition), approvePositionFunding, and leg sizing with sizeLeverageBorrow / projectLeverageLeg / getPositionLegQuote. Use when the task is leverage-yield vaults (e.g. "deposit into a leverage vault", "withdraw lsoda shares", "vault APR / effective APR", "lsoda share balance") OR leverage positions (e.g. "open a leverage position", "adjust / increase / decrease leverage", "close a leveraged position", "position health factor / LTV", "size borrowAmount and minCollateralOut", "leveraged long with my own AAVE account"). New in v2 — integration only, no v1 migration path. Links into the parent sodax-sdk knowledge tree. For React dapps, prefer sodax-dapp-kit.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -13,11 +13,19 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
|
|
|
13
13
|
|
|
14
14
|
## Step 1 — Clarify with user before coding
|
|
15
15
|
|
|
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.
|
|
16
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.
|
|
17
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 })`.
|
|
18
19
|
3. **End-to-end or manual relay?** `vaultSwap` does create → verify → relay → notify. For backend submit-tx, use `createVaultIntent` then relay yourself and finish with the public `notifySolver`.
|
|
19
20
|
4. **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).
|
|
20
21
|
|
|
22
|
+
### Step 1b — leverage positions
|
|
23
|
+
|
|
24
|
+
1. **Which operation?** It decides the method, and the choice is not stylistic. Open → `openLeveragePosition`. Leverage change (`buildAddLeverage` / `buildDecreaseLeverage`) → `submitLeveragePositionIntent`. Withdraw / settle / cancel → `runLeveragePositionOperation`. The first two report the intent; the third has nothing to report. Sending a leverage change through the route-only path leaves an intent nothing will fill, and it expires without a word — the compiler refuses it via the `PositionIntentCall` / `PositionDirectCall` brands.
|
|
25
|
+
2. **Which side funds the open?** `side: 'collateral'` deposits the collateral asset. `side: 'debt'` funds with the debt token and the deposit is **not** collateral — it goes to the solver as part of the input, so the only collateral the position gets is what the solver delivers.
|
|
26
|
+
3. **Have you sized the leg?** `borrowAmount` / `minCollateralOut` must come from `sizeLeverageBorrow` → `getPositionLegQuote` → `projectLeverageLeg`. Oracle parity is wrong and fails *after* the solver fills. Never hand-roll it.
|
|
27
|
+
4. **Which chain?** Sonic (the hub) is the proven path. A non-hub `srcChainKey` is `@experimental`; Bitcoin is refused outright.
|
|
28
|
+
|
|
21
29
|
## Integration workflow
|
|
22
30
|
|
|
23
31
|
1. [`../integration/knowledge/ai-rules.md`](../integration/knowledge/ai-rules.md).
|
|
@@ -37,12 +45,28 @@ Granular skill for `LeverageYieldService` — `sodax.leverageYield`. Feature tag
|
|
|
37
45
|
- **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.
|
|
38
46
|
- **Assuming `swaps.partnerFee` monetizes vault flows.** It does not — configure `leverageYield.partnerFee` (or the global `fee`).
|
|
39
47
|
|
|
48
|
+
### Leverage-position anti-patterns
|
|
49
|
+
|
|
50
|
+
- **Sizing `borrowAmount` / `minCollateralOut` from oracle prices.** The hook supplies what the solver actually paid and only then borrows against it, so the pool sees `deposit + solver output`, never `deposit × leverage`. Parity sizing is accepted, the solver fills, and the borrow then reverts with Aave `'36'` — unwinding the fill. Use `sizeLeverageBorrow` + `projectLeverageLeg` with a `getPositionLegQuote` between them, and treat `exceedsMaxLtv` as a hard gate.
|
|
51
|
+
- **Quoting `borrowAmount` instead of `intentInput`.** On a debt-side open the user's own contribution goes to the solver too, so quoting the borrow alone understates the input.
|
|
52
|
+
- **Calling `getQuote` for a position leg.** `getPositionLegQuote` names the hub reserves the intent actually swaps and quotes gross — both details a hand-rolled `getQuote` gets wrong, and both surface only as an unfillable floor. Pass the reserve **address** (`reserve.underlyingAsset`), not the reserve object.
|
|
53
|
+
- **Routing a leverage change through `runLeveragePositionOperation`.** It does not notify, so the intent expires unfilled. The brands refuse it at compile time — do not cast past them.
|
|
54
|
+
- **Treating a resolved open as an open position.** `openLeveragePosition` resolving means the intent is LIVE. Read `notified` on the value; `false` means nothing will fill it. It is deliberately not an error — retrying would open a second position.
|
|
55
|
+
- **Treating the transaction receipt as completion.** `addLeverage` / `decreaseLeverage` are filled by a solver afterwards; poll `getPositionPendingState`.
|
|
56
|
+
- **Reporting `srcChainTxHash` to `notifySolver`.** The intent exists in the **hub** transaction — `dstChainTxHash`. They are the same only on the hub.
|
|
57
|
+
- **Sizing a transaction from `totalCollateralBase`.** Base-currency figures are display-only; use `getPositionCollateralBalance`. An over-sized `decreaseLeverage` does not fail on submission — it reverts at fill and the intent silently expires.
|
|
58
|
+
- **Charging an existing position the configured fee.** `getEffectivePositionFee()` is what a NEW position would carry; an existing one's fee was fixed at creation — read `getPositionInfo`. The fee is given up on top of the solver's payment, so an exit sized at the whole collateral balance cannot settle.
|
|
59
|
+
- **Approving the factory.** It pulls from nobody. Funding is a transfer to `predictPosition(...)`; the one real approval has a spender that differs per chain, which `approvePositionFunding` resolves.
|
|
60
|
+
- **Passing an `owner`.** There is none — the factory requires `cfg.owner == msg.sender` and the caller is always the funder's own hub wallet.
|
|
61
|
+
|
|
40
62
|
## Verification
|
|
41
63
|
|
|
42
64
|
1. `pnpm tsc --noEmit` clean.
|
|
43
65
|
2. Every `await sodax.leverageYield.<method>(...)` has `if (!result.ok)`.
|
|
44
66
|
3. Deposit/withdraw build a payload that is then run through `vaultSwap` (or `createVaultIntent` + relay + `notifySolver`).
|
|
45
67
|
4. APR display uses `getEffectiveApr`; share/withdraw sizing from a spoke address uses the `*ForUser` reads.
|
|
68
|
+
5. 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.
|
|
69
|
+
6. Positions: leverage changes go through `submitLeveragePositionIntent`, not `runLeveragePositionOperation`; `notifySolver` is given `dstChainTxHash`; exits are sized from `getPositionCollateralBalance` and charge the fee from `getPositionInfo`.
|
|
46
70
|
|
|
47
71
|
## Related granular skills (same family)
|
|
48
72
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-sdk-leverage-yield-api
|
|
3
|
-
description: 'Granular skill for the @sodax/sdk v2 Leverage Yield API client — `sodax.api.leverageYield` (class LeverageYieldApiService), a typed HTTP client for the backend Leverage Yield API
|
|
3
|
+
description: 'Granular skill for the @sodax/sdk v2 Leverage Yield API client — `sodax.api.leverageYield` (class LeverageYieldApiService), a typed HTTP client for the backend Leverage Yield API (`/leverage-yield/*`, 33 endpoints: vault registry, vault reads (asset/position/APR/effective-APR/LSD-APR/total-assets/previews/share-balance/max-withdraw), deposit & withdraw quote, deadline, allowance/approve, create-deposit-intent & create-withdraw-intent, intent submit/status/cancel/hash/packet/extra-data/fill/get, gas estimate, partner/solver fees, submit-tx + status). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the leverage-yield backend directly (e.g. "sodax.api.leverageYield", "leverage vault APR from the backend", "vault position from the API", "leverage-yield deposit quote", "createDepositIntent via the backend API", "leverage-yield API v2"). For the higher-level end-to-end vault-swap orchestrator use the `leverage-yield` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Leverage Yield API (Core SDK granular skill)
|
|
7
7
|
|
|
8
8
|
Granular skill for `sodax.api.leverageYield` (class `LeverageYieldApiService`) — the typed HTTP client for
|
|
9
|
-
the backend **Leverage Yield API
|
|
9
|
+
the backend **Leverage Yield API** (`/leverage-yield/*`). `sodax.api` is an alias for `sodax.backendApi`;
|
|
10
10
|
`.leverageYield` is the leverage-yield client. 33 endpoints, one method each; every method returns
|
|
11
11
|
`Promise<Result<T>>` (never throws) and validates the response. Errors carry `feature: 'backend'`,
|
|
12
12
|
`context.api: 'leverageYield'`, `context.endpoint`.
|
|
@@ -63,7 +63,7 @@ Read in order. Skipping `ai-rules.md` is the most common cause of agents reverti
|
|
|
63
63
|
- [`../partner/SKILL.md`](../partner/SKILL.md) — partner fees on swap.
|
|
64
64
|
- [`../recovery/SKILL.md`](../recovery/SKILL.md) — stuck-asset recovery for failed swaps.
|
|
65
65
|
- [`../backend-api/SKILL.md`](../backend-api/SKILL.md) — `sodax.api.swaps.submitTx` and intent / orderbook lookups (step-by-step swap flow + diagnostics).
|
|
66
|
-
- [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the typed Swaps API
|
|
66
|
+
- [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the typed Swaps API backend client (`sodax.api.swaps`: quote, create-intent, submit-tx, fees) the swap flow calls under the hood.
|
|
67
67
|
|
|
68
68
|
For tasks spanning multiple features, load the broad [`sodax-sdk` skill](../SKILL.md) instead.
|
|
69
69
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-sdk-swaps-api
|
|
3
|
-
description: 'Granular skill for the @sodax/sdk v2 Swaps API client — `sodax.api.swaps` (class SwapsApiService), a typed HTTP client for the backend Swaps API
|
|
3
|
+
description: 'Granular skill for the @sodax/sdk v2 Swaps API client — `sodax.api.swaps` (class SwapsApiService), a typed HTTP client for the backend Swaps API (`/swaps/*`, 21 endpoints: quote, deadline, allowance/approve, create-intent, intent submit/status/cancel/hash/packet/extra-data, limit orders, gas estimate, partner/solver fees, submit-tx + status). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the swaps backend directly (e.g. "get a swap quote from the Sodax backend", "sodax.api.swaps", "submit swap tx", "createIntent via the backend API", "poll submit-tx status", "swaps API v2", "point swaps at a custom endpoint"). For the higher-level end-to-end swap orchestrator use the `swap` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Swaps API (Core SDK granular skill)
|
|
7
7
|
|
|
8
8
|
Granular skill for `sodax.api.swaps` (class `SwapsApiService`) — the typed HTTP client for the backend
|
|
9
|
-
**Swaps API
|
|
9
|
+
**Swaps API** (`/swaps/*`). `sodax.api` is an alias for `sodax.backendApi`; `.swaps` is the swaps
|
|
10
10
|
client. 21 endpoints, one method each; every method returns `Promise<Result<T>>` (never throws) and
|
|
11
11
|
validates the response. Errors carry `feature: 'backend'`, `context.api: 'swaps'`, `context.endpoint`.
|
|
12
12
|
|
|
@@ -8,7 +8,7 @@ Backed by [viem](https://viem.sh). One class covers **every** SODAX EVM spoke ch
|
|
|
8
8
|
| Interface | `IEvmWalletProvider` (from `@sodax/types`) |
|
|
9
9
|
| Discriminant style | **Field presence** (no `type` field) |
|
|
10
10
|
| Underlying SDK | `viem` |
|
|
11
|
-
| Supported chains | Sonic (hub), Ethereum, Arbitrum, Base, BSC, Optimism, Polygon, Avalanche, HyperEVM, Lightlink, Redbelly, Kaia, Hedera |
|
|
11
|
+
| Supported chains | Sonic (hub), Ethereum, Arbitrum, Base, BSC, Optimism, Polygon, Avalanche, HyperEVM, Lightlink, Redbelly, Kaia, Hedera, Robinhood |
|
|
12
12
|
|
|
13
13
|
---
|
|
14
14
|
|
|
@@ -58,9 +58,9 @@ Bitcoin's signing flow inspects the connected address and picks the right method
|
|
|
58
58
|
| P2SH (legacy multi-sig, `3…`) | ECDSA | Unisat, Xverse, OKX, Hana |
|
|
59
59
|
| P2PKH (legacy, `1…`) | ECDSA | Unisat, Xverse, OKX, Hana |
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
The methods live on the connector's `IBitcoinWalletProvider`, not on the connector: `chainRegistry` resolves the provider via `getWalletProvider()` (falling back to `recreateWalletProvider(xAccount)` after a page reload) and dispatches on it. A custom connector must return a provider implementing both methods; if it implements only one, calling `signMessage` from a wrongly-typed address surfaces the error inline.
|
|
62
62
|
|
|
63
|
-
The same logic mirrors the SDK's `
|
|
63
|
+
The same logic mirrors the SDK's `RadfiProvider.authenticateWithWallet` — the React layer doesn't reinvent the dispatch.
|
|
64
64
|
|
|
65
65
|
---
|
|
66
66
|
|