@sodax/skills 2.2.0-rc.5 → 2.2.0-rc.7
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 +9 -8
- package/skills/sodax-dapp-kit/integration/knowledge/features/bridge.md +3 -0
- package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +71 -4
- package/skills/sodax-dapp-kit/integration/knowledge/features/money-market.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +2 -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 +166 -1
- package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +7 -5
- package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +5 -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/bridge.md +4 -0
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield-api.md +13 -8
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +194 -3
- package/skills/sodax-sdk/integration/knowledge/features/swap.md +24 -5
- package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +2 -2
- package/skills/sodax-sdk/integration/knowledge/recipes/README.md +1 -0
- package/skills/sodax-sdk/integration/knowledge/recipes/manual-submit-tx-with-fallback.md +184 -0
- 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 +2 -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
|
|
@@ -115,9 +115,10 @@ surface with `context.status` `401`/`403` — nothing but a corrected key fixes
|
|
|
115
115
|
terminal in your UI; the transient verification `503` is retried by the wire client. See the
|
|
116
116
|
`sodax-sdk` skill (integration mode), `swaps-api.md` § API key, for the precedence order.
|
|
117
117
|
|
|
118
|
-
Every retrying `useSwapsApi*` hook already handles this: its
|
|
119
|
-
(exported from `@sodax/dapp-kit`), which retries transport
|
|
120
|
-
401/403. `useSwapsApiStatus
|
|
118
|
+
Every retrying `useSwapsApi*`, `useLeverageYieldApi*` and `useBridgeApi*` hook already handles this: its
|
|
119
|
+
default `retry` is `retryUnlessAuthFailure` (exported from `@sodax/dapp-kit`), which retries transport
|
|
120
|
+
blips up to 3 times but never replays a 401/403. `useSwapsApiStatus`, `useSwapsApiSubmitTxStatus`,
|
|
121
|
+
`useLeverageYieldApiSubmitTxStatus` and `useBridgeApiSubmitTxStatus` additionally stop their 1s poll on a
|
|
121
122
|
rejected key, instead of re-requesting forever. So an invalid key surfaces once, fast, on `error`.
|
|
122
123
|
|
|
123
124
|
Override or compose it through `queryOptions` / `mutationOptions` when you want different behaviour:
|
|
@@ -142,7 +143,7 @@ const { mutateAsync: submitSwapTx } = useSwapsApiSubmitTx();
|
|
|
142
143
|
await submitSwapTx({ request, apiConfig: { baseURL: 'https://...' } });
|
|
143
144
|
```
|
|
144
145
|
|
|
145
|
-
`useSwapsApiSubmitTxStatus` polls the processing status and returns `SubmitTxStatusResponseV2 | undefined`. Its query runs only when **both** `txHash` and `srcChainKey` are supplied — the
|
|
146
|
+
`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
147
|
|
|
147
148
|
```ts
|
|
148
149
|
// @ai-snippets-skip
|
|
@@ -154,7 +155,7 @@ const { data: status } = useSwapsApiSubmitTxStatus({ params: { txHash, srcChainK
|
|
|
154
155
|
|
|
155
156
|
### Bridge API (`sodax.api.bridge`)
|
|
156
157
|
|
|
157
|
-
Typed React Query wrappers over the backend **Bridge API
|
|
158
|
+
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
159
|
|
|
159
160
|
```ts
|
|
160
161
|
// @ai-snippets-skip
|
|
@@ -172,13 +173,13 @@ const { mutateAsync: submitBridgeTx } = useBridgeApiSubmitTx();
|
|
|
172
173
|
await submitBridgeTx({ request, apiConfig: { baseURL: 'https://...' } });
|
|
173
174
|
```
|
|
174
175
|
|
|
175
|
-
`useBridgeApiSubmitTxStatus` polls (1s) and returns `BridgeSubmitTxStatusResponseV2 | undefined`, running only when **both** `txHash` and `srcChainKey` are supplied; terminal states are `executed` / `failed` (no `posting_execution`). The fee / bridgeable-amount / bridgeable quotes are computable client-side (config + vault math) — prefer the on-chain `useGetBridgeableAmount` / `sodax.bridge.*` for a no-round-trip read; `useBridgeApiFee` / `useBridgeApiBridgeableAmount` / `useBridgeApiIsBridgeable` mirror the backend endpoints for HTTP parity.
|
|
176
|
+
`useBridgeApiSubmitTxStatus` polls (1s) and returns `BridgeSubmitTxStatusResponseV2 | undefined`, running only when **both** `txHash` and `srcChainKey` are supplied; terminal states are `executed` / `failed` (no `posting_execution`), and it also stops on a set `abandonedAt` or once the backend rejects the API key. Every retrying `useBridgeApi*` hook defaults `retry` to `retryUnlessAuthFailure`, exactly as the swaps and leverage-yield hooks do. The fee / bridgeable-amount / bridgeable quotes are computable client-side (config + vault math) — prefer the on-chain `useGetBridgeableAmount` / `sodax.bridge.*` for a no-round-trip read; `useBridgeApiFee` / `useBridgeApiBridgeableAmount` / `useBridgeApiIsBridgeable` mirror the backend endpoints for HTTP parity.
|
|
176
177
|
|
|
177
178
|
> Full list in [hooks-index.md](../reference/hooks-index.md); key shapes in [querykey-conventions.md](../reference/querykey-conventions.md). For non-React callers, `sodax.api.bridge` is documented in the `sodax-sdk` skill (integration mode).
|
|
178
179
|
|
|
179
180
|
### Leverage Yield API (`sodax.api.leverageYield`)
|
|
180
181
|
|
|
181
|
-
Typed React Query wrappers over the backend **Leverage Yield API
|
|
182
|
+
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
183
|
|
|
183
184
|
```ts
|
|
184
185
|
// @ai-snippets-skip
|
|
@@ -15,6 +15,9 @@ useBridgeApprove({ mutationOptions });
|
|
|
15
15
|
// Queries
|
|
16
16
|
// useBridgeAllowance nests payload + walletProvider under params (NOT at top level)
|
|
17
17
|
useBridgeAllowance({ params: { payload: CreateBridgeIntentParams<K>, walletProvider }, queryOptions });
|
|
18
|
+
// Polls 3s from the source tx; stops on a terminal source, a rejected API key, or 40 consecutive
|
|
19
|
+
// ambiguous reads. Result-wrapped — narrow `data.value.source` ('backend' | 'relay').
|
|
20
|
+
useBridgeDetailedStatus({ params: { srcChainKey, srcTxHash, apiConfig? }, queryOptions });
|
|
18
21
|
useGetBridgeableAmount({ params: { from: XToken, to: XToken }, queryOptions });
|
|
19
22
|
useGetBridgeableTokens({ params: { from: SpokeChainKey, to: SpokeChainKey, token: string }, queryOptions });
|
|
20
23
|
```
|
|
@@ -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
|
|
|
@@ -15,6 +17,7 @@ useLeverageYieldVaultSwap({ mutationOptions }); // EXECUTE the built payload en
|
|
|
15
17
|
useLeverageYieldNotifySolver({ mutationOptions }); // manual-flow: notify the solver after a self-driven relay
|
|
16
18
|
|
|
17
19
|
// Reads
|
|
20
|
+
useLeverageYieldDetailedStatus({ params, queryOptions }); // track a vault swap from its SOURCE tx (3s)
|
|
18
21
|
useLeverageYieldQuote({ params, queryOptions }); // vault deposit/withdraw quote (3s) — NOT useQuote
|
|
19
22
|
useLeverageYieldEffectiveApr({ params, queryOptions }); // AAVE + LSD effective net APR (60s)
|
|
20
23
|
useLeverageYieldPosition({ params, queryOptions }); // collateral/debt/ltv/healthFactor/idle (30s)
|
|
@@ -23,7 +26,7 @@ useLeverageYieldPreviewRedeem({ params, queryOptions }); // assets for N shares;
|
|
|
23
26
|
useLeverageYieldShareBalances({ params, queryOptions }); // per-chain share balances via useQueries (15s)
|
|
24
27
|
```
|
|
25
28
|
|
|
26
|
-
`deposit` / `withdraw` are **builders** — they assemble a `LeverageYieldSwapPayload`, they do NOT broadcast. Spread the built payload into `useLeverageYieldVaultSwap`'s `mutate`, adding the `walletProvider`. There is no dedicated leverage-yield approve hook: the swap-style deposit approves the spoke-side asset manager, so reuse `useSwapApprove` / `useSwapAllowance` (see Approval pattern).
|
|
29
|
+
`deposit` / `withdraw` are **builders** — they assemble a `LeverageYieldSwapPayload`, they do NOT broadcast. Spread the built payload into `useLeverageYieldVaultSwap`'s `mutate`, adding the `walletProvider`. `vaultSwap` takes the **backend submit-tx** path by default and falls back to the client-side relay on any non-success, so track the result with `useLeverageYieldDetailedStatus` — it keys on the source tx and answers for whichever path completed. Pass `extras.apiKey` in `mutate` to key the backend leg per action. There is no dedicated leverage-yield approve hook: the swap-style deposit approves the spoke-side asset manager, so reuse `useSwapApprove` / `useSwapAllowance` (see Approval pattern).
|
|
27
30
|
|
|
28
31
|
`use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
|
|
29
32
|
transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
|
|
@@ -91,13 +94,19 @@ Leverage-yield has **no dedicated approve hook**. A deposit is a swap-style inte
|
|
|
91
94
|
|
|
92
95
|
## Return shapes
|
|
93
96
|
|
|
94
|
-
Read hooks here are **already unwrapped** — they throw on SDK `!ok` so `isError` / `error` / `retry` engage. Read `data` directly; do NOT branch on `data.ok`.
|
|
97
|
+
Read hooks here are **already unwrapped** — they throw on SDK `!ok` so `isError` / `error` / `retry` engage. Read `data` directly; do NOT branch on `data.ok`. **Two hooks are the exception** and return the SDK `Result` as `data`:
|
|
98
|
+
|
|
99
|
+
- `useLeverageYieldQuote`, matching `useQuote` on the swap side, because a quote failure ("no path", thin liquidity) is an expected UI branch and the `Result` preserves the solver's `detail.code`.
|
|
100
|
+
- `useLeverageYieldDetailedStatus`, matching `useDetailedStatus`, because a lookup miss is an expected state while a vault swap is in flight. Narrow `data?.ok`, then `data.value.source` (`'backend'` | `'solver'`); on `!ok`, `error.context.reason` separates the ambiguous not-yet-delivered miss from a failing dependency.
|
|
101
|
+
|
|
102
|
+
Branch on `data?.ok` for those two hooks only.
|
|
95
103
|
|
|
96
104
|
| Hook | Returns |
|
|
97
105
|
|---|---|
|
|
98
106
|
| `useLeverageYieldQuote` | `UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse \| LeverageYieldLookupError> \| undefined, Error>` (Result **not** unwrapped; `undefined` while `payload` is undefined). Guard the error with `isSodaxError` — the `SolverErrorResponse` arm has `detail.code`, the `SodaxError` arm has `.code` (`VALIDATION_FAILED` / `LOOKUP_FAILED` / `UNKNOWN`) |
|
|
99
107
|
| `useLeverageYieldDeposit` / `useLeverageYieldWithdraw` | `SafeUseMutationResult<LeverageYieldSwapPayload, Error, …>` (builder — `data` is the payload to spread into `useLeverageYieldVaultSwap`) |
|
|
100
108
|
| `useLeverageYieldVaultSwap` | `SafeUseMutationResult<VaultSwapResponse, Error, …>` (`{ solverExecutionResponse, intent, intentDeliveryInfo }`) |
|
|
109
|
+
| `useLeverageYieldDetailedStatus` | `UseQueryResult<Result<DetailedLeverageYieldStatus, LeverageYieldDetailedStatusError> \| undefined>` — Result-wrapped, narrow the value on `source` (`'backend'` \| `'solver'`) |
|
|
101
110
|
| `useLeverageYieldNotifySolver` | `SafeUseMutationResult<SolverExecutionResponse, Error, …>` (`{ answer: 'OK', intent_hash }`) |
|
|
102
111
|
| `useLeverageYieldEffectiveApr` | `UseQueryResult<LeverageYieldEffectiveApr, Error>` |
|
|
103
112
|
| `useLeverageYieldPosition` | `UseQueryResult<LeverageYieldPosition, Error>` |
|
|
@@ -115,6 +124,64 @@ Read hooks here are **already unwrapped** — they throw on SDK `!ok` so `isErro
|
|
|
115
124
|
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
125
|
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
126
|
|
|
127
|
+
## Leverage positions (separate from vaults)
|
|
128
|
+
|
|
129
|
+
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*`.
|
|
130
|
+
|
|
131
|
+
> **`@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.
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
// @ai-snippets-skip
|
|
135
|
+
// Reads — data already unwrapped, read it directly
|
|
136
|
+
useLeveragePositions({ params: { owner } }); // readonly Address[] key: ['leverageYield','positions',owner]
|
|
137
|
+
useLeveragePositionsForUser({ params: { spokeChainKey, spokeAddress } }); // same, via the hub wallet — note spoke*, NOT src*
|
|
138
|
+
useLeveragePositionInfo({ params: { position } }); // LeveragePosition — static descriptor
|
|
139
|
+
useLeveragePositionAccount({ params: { position } }); // LeveragePositionAccount (30s)
|
|
140
|
+
useLeveragePositionCollateral({ params: { position, collateral } });// LeveragePositionCollateral (30s)
|
|
141
|
+
useLeveragePositionPending({ params: { position } }); // LeveragePositionPendingState (15s)
|
|
142
|
+
useLeveragePositionFundingAllowance({ params: { srcChainKey, srcAddress, token, amount } }); // boolean
|
|
143
|
+
|
|
144
|
+
// NOT a query — returns synchronously, no data/isLoading
|
|
145
|
+
useLeveragePositionPayoutAddress({ params: { chainKey, signerAddress, owner } }); // Address | undefined
|
|
146
|
+
|
|
147
|
+
// Mutations
|
|
148
|
+
useOpenLeveragePosition(); // key: ['leverageYield','openPosition'] → LeveragePositionIntentResult
|
|
149
|
+
useSubmitLeveragePositionIntent(); // key: ['leverageYield','submitPositionIntent'] → LeveragePositionIntentResult
|
|
150
|
+
useRunLeveragePositionOperation(); // key: ['leverageYield','runPositionOperation'] → TxHashPair
|
|
151
|
+
useApproveLeveragePositionFunding();// key: ['leverageYield','approvePositionFunding']
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
| Type | Fields |
|
|
155
|
+
|---|---|
|
|
156
|
+
| `LeveragePosition` | `{ address, owner, collateral, borrowToken, eModeCategory, feeBps, feeReceiver }` |
|
|
157
|
+
| `LeveragePositionAccount` | `{ totalCollateralBase, totalDebtBase, availableBorrowsBase, currentLiquidationThreshold, ltv, healthFactor }` — bigint; `healthFactor` is WAD, `*Base` is the oracle's 8-dp unit |
|
|
158
|
+
| `LeveragePositionCollateral` | `{ aToken, balance }` |
|
|
159
|
+
| `LeveragePositionPendingState` | `{ kind: number, isLive: boolean, needsSettle: boolean }` |
|
|
160
|
+
| `LeveragePositionIntentResult` | `{ txHashes: TxHashPair, notified: boolean, notifyError?: string }` |
|
|
161
|
+
|
|
162
|
+
### Which mutation — decided by the operation, not by preference
|
|
163
|
+
|
|
164
|
+
`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.
|
|
165
|
+
|
|
166
|
+
| operation | hook | notifies |
|
|
167
|
+
|---|---|---|
|
|
168
|
+
| open (collateral or debt side) | `useOpenLeveragePosition` | yes |
|
|
169
|
+
| `buildAddLeverage` / `buildDecreaseLeverage` | `useSubmitLeveragePositionIntent` | yes |
|
|
170
|
+
| `buildPositionWithdraw` / `buildSettlePosition` / `buildCancelPositionOperation` | `useRunLeveragePositionOperation` | no |
|
|
171
|
+
|
|
172
|
+
TypeScript enforces the rows: the first two builders return `PositionIntentCall`, the last three `PositionDirectCall`, and each hook accepts only its own.
|
|
173
|
+
|
|
174
|
+
### Position gotchas
|
|
175
|
+
|
|
176
|
+
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.
|
|
177
|
+
2. **`useLeverageYieldPosition` is the VAULT, not a leverage position.** Reading vault LTV/health for a position, or vice versa, silently shows the wrong numbers.
|
|
178
|
+
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.
|
|
179
|
+
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.
|
|
180
|
+
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.
|
|
181
|
+
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.
|
|
182
|
+
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.
|
|
183
|
+
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).
|
|
184
|
+
|
|
118
185
|
## Cross-references
|
|
119
186
|
|
|
120
187
|
- [`../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
|
|
|
@@ -13,6 +13,7 @@ Pair: [`features/swap.md`](../../../migration-v1-to-v2/knowledge/features/swap.m
|
|
|
13
13
|
useQuote({ params: { payload }, queryOptions }); // Real-time quote (3s)
|
|
14
14
|
useSwapAllowance({ params: { payload, srcChainKey, walletProvider }, queryOptions }); // allowance (2s)
|
|
15
15
|
useStatus({ params: { intentTxHash }, queryOptions }); // Intent execution status (3s)
|
|
16
|
+
// Polls 3s; stops on a terminal source, a rejected API key, or 40 consecutive ambiguous reads.
|
|
16
17
|
useDetailedStatus({ params: { srcChainKey, srcTxHash }, queryOptions }); // Swap status by source tx (3s)
|
|
17
18
|
|
|
18
19
|
// Mutations — domain inputs flow through mutate(vars), see Mutation params below
|
|
@@ -106,7 +107,7 @@ type UseDetailedStatusParams = ReadHookParams<
|
|
|
106
107
|
| `useQuote` | `UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse> \| undefined, Error>` — `data?.ok` branching required; polls 3 s |
|
|
107
108
|
| `useSwapAllowance` | `UseQueryResult<boolean, Error>` — `data` is already-unwrapped `boolean \| undefined`; truthy when approved; polls 2 s |
|
|
108
109
|
| `useStatus` | `UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> \| undefined, Error>` — Result-wrapped like `useQuote`; `data?.ok` branching required; polls 3 s; stops on status `3`/`4`, and after 40 consecutive NOT_FOUND fetches |
|
|
109
|
-
| `useDetailedStatus` | `UseQueryResult<Result<DetailedSwapStatus, DetailedStatusError> \| undefined, Error>` — Result-wrapped tagged union; polls 3 s; stops when the answering source is terminal (backend `'solved'`, or solver `SOLVED`/`FAILED`), and — like `useStatus` — after 40 consecutive ambiguous reads (solver `NOT_FOUND`, or a relay with no packet for the tx); a dependency outage keeps polling |
|
|
110
|
+
| `useDetailedStatus` | `UseQueryResult<Result<DetailedSwapStatus, DetailedStatusError> \| undefined, Error>` — Result-wrapped tagged union; polls 3 s; stops when the answering source is terminal (backend `'solved'`, or solver `SOLVED`/`FAILED`), when the backend rejects the API key, and — like `useStatus` — after 40 consecutive ambiguous reads (solver `NOT_FOUND`, or a relay with no packet for the tx); a dependency outage keeps polling |
|
|
110
111
|
|
|
111
112
|
### `useStatus` vs `useDetailedStatus`
|
|
112
113
|
|
|
@@ -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';
|
|
@@ -12,7 +12,7 @@ Leveraged-yield ERC-4626 vaults on Sonic. Deposit any token → `lsoda*` shares,
|
|
|
12
12
|
|------|---------|
|
|
13
13
|
| `useLeverageYieldDeposit` | Build a deposit payload (any token → `lsoda*`) |
|
|
14
14
|
| `useLeverageYieldWithdraw` | Build a withdraw payload (`lsoda*` → any token) |
|
|
15
|
-
| `useLeverageYieldVaultSwap` | Execute a built payload end-to-end (
|
|
15
|
+
| `useLeverageYieldVaultSwap` | Execute a built payload end-to-end (backend submit-tx by default, client-side relay as fallback) |
|
|
16
16
|
| `useSwapApprove` | Approve the spoke `inputToken` (deposit only — swap-domain hook) |
|
|
17
17
|
|
|
18
18
|
### Queries
|
|
@@ -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.
|
|
@@ -49,6 +49,7 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
|
|
|
49
49
|
| Hook | Type | Purpose |
|
|
50
50
|
|---|---|---|
|
|
51
51
|
| `useBridge` | Mutation | Execute a cross-chain bridge transfer |
|
|
52
|
+
| `useBridgeDetailedStatus` | Query | Track a bridge from its source tx (`{ srcChainKey, srcTxHash, apiConfig? }`; polls 3s; Result-wrapped; stops on the answering source's terminal state, on a rejected API key, and after 40 consecutive ambiguous reads — a relay with no packet for the tx; outages keep polling). Returns a tagged union — backend submit-tx record or delivered relay packet — narrow on `source`. Unlike `useBridgeApiSubmitTxStatus`, answers for both `bridge()` completion paths |
|
|
52
53
|
| `useBridgeAllowance` | Query | Approval check |
|
|
53
54
|
| `useBridgeApprove` | Mutation | Approve tokens for bridge |
|
|
54
55
|
| `useGetBridgeableAmount` | Query | Max bridgeable amount between two `XToken`s |
|
|
@@ -104,7 +105,8 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
|
|
|
104
105
|
|---|---|---|
|
|
105
106
|
| `useLeverageYieldDeposit` | Mutation | Build a deposit payload (any token → `lsoda*` shares) — spread into `useLeverageYieldVaultSwap` |
|
|
106
107
|
| `useLeverageYieldWithdraw` | Mutation | Build a withdraw payload (`lsoda*` → any token; `hubWalletSwap`) |
|
|
107
|
-
| `useLeverageYieldVaultSwap` | Mutation | Execute a built payload end-to-end
|
|
108
|
+
| `useLeverageYieldVaultSwap` | Mutation | Execute a built payload end-to-end; backend submit-tx by default, falling back to the client-side create → verify → relay → notify path. `extras.apiKey` keys the backend leg per action |
|
|
109
|
+
| `useLeverageYieldDetailedStatus` | Query | Track a vault swap from its source tx (`{ srcChainKey, srcTxHash, apiConfig? }`; polls 3s; Result-wrapped; stops on the answering source's terminal state, on a rejected API key, and after 40 consecutive ambiguous reads — solver NOT_FOUND, or a relay with no packet for the tx; outages keep polling). Returns a tagged union — backend submit-tx record or solver answer — narrow on `source`. Unlike `useLeverageYieldApiSubmitTxStatus`, answers for both `vaultSwap()` completion paths |
|
|
108
110
|
| `useLeverageYieldNotifySolver` | Mutation | Manual-flow notify step (after a self-driven `createVaultIntent` + relay) |
|
|
109
111
|
| `useLeverageYieldEffectiveApr` | Query | AAVE + LSD effective net APR (60s) |
|
|
110
112
|
| `useLeverageYieldPosition` | Query | Live position: collateral, debt, LTV, health factor, idle (30s) |
|
|
@@ -174,7 +176,7 @@ Comprehensive hook table across 12 feature domains. Use this when you know the f
|
|
|
174
176
|
|
|
175
177
|
## Swaps API (`sodax.api.swaps`)
|
|
176
178
|
|
|
177
|
-
Typed React Query wrappers over the backend Swaps API
|
|
179
|
+
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
180
|
|
|
179
181
|
### Tokens · quote · fees · gas (reads)
|
|
180
182
|
|
|
@@ -215,7 +217,7 @@ Typed React Query wrappers over the backend Swaps API v2 (`sodax.api.swaps.*`),
|
|
|
215
217
|
|
|
216
218
|
## Bridge API (`sodax.api.bridge`)
|
|
217
219
|
|
|
218
|
-
Typed React Query wrappers over the backend Bridge API
|
|
220
|
+
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
221
|
|
|
220
222
|
| Hook | Type / Polling |
|
|
221
223
|
|---|---|
|
|
@@ -225,7 +227,7 @@ Typed React Query wrappers over the backend Bridge API v2 (`sodax.api.bridge.*`)
|
|
|
225
227
|
| `useBridgeApiFee` | Query; `{ fee }` partner fee for an amount (per-request `partnerFee` override or configured default) |
|
|
226
228
|
| `useBridgeApiBridgeableAmount` | Query; `{ limit }` deposit capacity / withdrawal liquidity for a pair |
|
|
227
229
|
| `useBridgeApiIsBridgeable` | Query; `{ bridgeable }` whether a (from, to) pair is bridgeable |
|
|
228
|
-
| `useBridgeApiSubmitTxStatus` | Query (1s); requires `txHash` + `srcChainKey`; polls until `executed` / `failed` |
|
|
230
|
+
| `useBridgeApiSubmitTxStatus` | Query (1s); requires `txHash` + `srcChainKey`; polls until `executed` / `failed` / `abandonedAt`, or the backend rejects the API key |
|
|
229
231
|
| `useBridgeApiApprove` | Mutation; builds the unsigned approval txs — `{ tx, resetTx? }`, ordering is yours to handle |
|
|
230
232
|
| `useBridgeApiApproveAndBroadcast` | Mutation; builds **and** signs/broadcasts/waits — preferred; `{ approveTxHash, resetTxHash? }`; optional `onProgress` per step |
|
|
231
233
|
| `useBridgeApiCreateBridgeIntent` | Mutation; builds `{ tx, relayData }` (no intent) |
|
|
@@ -233,7 +235,7 @@ Typed React Query wrappers over the backend Bridge API v2 (`sodax.api.bridge.*`)
|
|
|
233
235
|
|
|
234
236
|
## Leverage Yield API (`sodax.api.leverageYield`)
|
|
235
237
|
|
|
236
|
-
Typed React Query wrappers over the backend Leverage Yield API
|
|
238
|
+
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
239
|
|
|
238
240
|
| Hook | Type / Polling |
|
|
239
241
|
|---|---|
|
|
@@ -70,6 +70,8 @@ queryClient.invalidateQueries({ queryKey: ['swap', 'allowance'] }); // wipe all
|
|
|
70
70
|
queryKey: ['mm', 'allowance', srcChainKey, token, action]
|
|
71
71
|
queryKey: ['swap', 'allowance', srcChainKey, srcAddress, inputToken, inputAmount.toString()]
|
|
72
72
|
queryKey: ['bridge', 'allowance', srcChainKey, srcAddress, srcToken, amount.toString()]
|
|
73
|
+
queryKey: ['bridge', 'detailedStatus', srcChainKey, srcTxHash] // useBridgeDetailedStatus — apiConfig excluded
|
|
74
|
+
queryKey: ['leverageYield', 'detailedStatus', srcChainKey, srcTxHash] // useLeverageYieldDetailedStatus — apiConfig excluded
|
|
73
75
|
queryKey: ['dex', 'allowance', srcChainKey, asset, amount.toString()]
|
|
74
76
|
queryKey: ['staking', 'allowance', srcChainKey, action, srcAddress, amount.toString()]
|
|
75
77
|
// ^^ action is a fixed literal per hook: 'stake' / 'unstake' / 'instantUnstake'
|
|
@@ -157,7 +159,7 @@ Backend read hooks (`useBackendIntentByTxHash`, `useBackendIntentByHash`, `useBa
|
|
|
157
159
|
|
|
158
160
|
### Swaps API (`sodax.api.swaps`)
|
|
159
161
|
|
|
160
|
-
Typed wrappers over `sodax.api.swaps.*` (one per Swaps API
|
|
162
|
+
Typed wrappers over `sodax.api.swaps.*` (one per Swaps API endpoint), all keyed `['swapsApi', action, ...]`.
|
|
161
163
|
|
|
162
164
|
| Key | Hook |
|
|
163
165
|
|---|---|
|
|
@@ -186,7 +188,7 @@ Typed wrappers over `sodax.api.swaps.*` (one per Swaps API v2 endpoint), all key
|
|
|
186
188
|
|
|
187
189
|
### Bridge API (`sodax.api.bridge`)
|
|
188
190
|
|
|
189
|
-
Typed wrappers over `sodax.api.bridge.*` (one per Bridge API
|
|
191
|
+
Typed wrappers over `sodax.api.bridge.*` (one per Bridge API endpoint), all keyed `['bridgeApi', action, ...]`.
|
|
190
192
|
|
|
191
193
|
| Key | Hook |
|
|
192
194
|
|---|---|
|
|
@@ -204,7 +206,7 @@ Typed wrappers over `sodax.api.bridge.*` (one per Bridge API v2 endpoint), all k
|
|
|
204
206
|
|
|
205
207
|
### Leverage Yield API (`sodax.api.leverageYield`)
|
|
206
208
|
|
|
207
|
-
Typed wrappers over `sodax.api.leverageYield.*` (one per Leverage Yield API
|
|
209
|
+
Typed wrappers over `sodax.api.leverageYield.*` (one per Leverage Yield API endpoint), all keyed `['leverageYieldApi', action, ...]`.
|
|
208
210
|
|
|
209
211
|
| Key | Hook |
|
|
210
212
|
|---|---|
|