@sodax/skills 2.2.0-rc.4 → 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 +36 -1
- package/skills/sodax-sdk/integration/knowledge/chain-specifics.md +3 -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 +178 -3
- package/skills/sodax-sdk/integration/knowledge/features/swap.md +8 -1
- package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +2 -2
- package/skills/sodax-sdk/integration/knowledge/recipes/logging.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)
|
|
@@ -540,3 +540,38 @@ You drop down to the relay layer only when:
|
|
|
540
540
|
- Per-feature usage: [`features/`](features/).
|
|
541
541
|
- Non-EVM chain quirks: [`chain-specifics.md`](chain-specifics.md).
|
|
542
542
|
- v1 → v2 porting context: [`README.md`](../../migration-v1-to-v2/knowledge/README.md).
|
|
543
|
+
|
|
544
|
+
### RWA classification and token logos
|
|
545
|
+
|
|
546
|
+
`XToken.isRwa === true` marks a registered tokenized stock, ETF or commodity,
|
|
547
|
+
including registered cross-chain representations. An omitted flag means no RWA
|
|
548
|
+
classification is declared; it is not a general-purpose crypto/stablecoin taxonomy.
|
|
549
|
+
Chain membership and symbol spelling do not determine RWA status.
|
|
550
|
+
|
|
551
|
+
Use `isRealWorldAsset({ chainKey, address })` to resolve metadata from the packaged
|
|
552
|
+
SDK registry when your token data comes from an API without the flag. It returns
|
|
553
|
+
false for unknown chains or addresses, ignores symbols, and compares EVM addresses
|
|
554
|
+
case-insensitively while preserving non-EVM identifier casing. It does not read
|
|
555
|
+
custom constructor config or validate swap/money-market support. New registry
|
|
556
|
+
metadata requires an SDK update; it does not automatically update backend payloads.
|
|
557
|
+
|
|
558
|
+
```typescript
|
|
559
|
+
import { ChainKeys, getSupportedSolverTokens, isRealWorldAsset, tokenLogo } from '@sodax/sdk';
|
|
560
|
+
|
|
561
|
+
const tokens = getSupportedSolverTokens(ChainKeys.ROBINHOOD_MAINNET);
|
|
562
|
+
const rwaTokens = tokens.filter(isRealWorldAsset);
|
|
563
|
+
const rows = tokens.map(token => ({
|
|
564
|
+
symbol: token.symbol,
|
|
565
|
+
isRwa: isRealWorldAsset(token),
|
|
566
|
+
logo: tokenLogo(token.symbol),
|
|
567
|
+
}));
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
For API responses using `xChainId`, pass it as `chainKey` alongside the token's
|
|
571
|
+
on-chain `address`. Resolve each chain/address before grouping directory rows;
|
|
572
|
+
keep feature support and UI visibility filters separate from classification.
|
|
573
|
+
|
|
574
|
+
`tokenLogo(symbol)` serves shared PNGs from the SDK repository's `main` branch.
|
|
575
|
+
Robinhood equity/ETF entries use the Robinhood mark; xStocks retain their own
|
|
576
|
+
artwork. Image replacements become available after merge, subject to caching,
|
|
577
|
+
without an SDK release. Consumers must use these URLs to receive the replacements.
|