@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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-dapp-kit-leverage-yield
|
|
3
|
-
description: 'Granular skill for the @sodax/dapp-kit v2 leverage-yield feature only
|
|
3
|
+
description: 'Granular skill for the @sodax/dapp-kit v2 leverage-yield feature only, covering BOTH products: (1) React Query hooks for leveraged-yield ERC-4626 VAULTS on Sonic — useLeverageYieldDeposit and useLeverageYieldWithdraw (build a swap payload), useLeverageYieldVaultSwap (execute it end-to-end), plus reads useLeverageYieldEffectiveApr, useLeverageYieldPosition, useLeverageYieldTotalAssets, useLeverageYieldPreviewRedeem, useLeverageYieldShareBalances; and (2) LEVERAGE POSITIONS — one owner-controlled AAVE account per position, via useOpenLeveragePosition, useSubmitLeveragePositionIntent, useRunLeveragePositionOperation, useApproveLeveragePositionFunding, and the reads useLeveragePositions, useLeveragePositionsForUser, useLeveragePositionInfo, useLeveragePositionAccount, useLeveragePositionCollateral, useLeveragePositionPending, useLeveragePositionPayoutAddress, useLeveragePositionFundingAllowance. Use when a React dapp task is leverage-yield vaults (e.g. "deposit into a leverage vault with dapp-kit", "useLeverageYieldVaultSwap hook", "render vault APR / TVL", "lsoda share balances across chains") OR leverage positions (e.g. "open a leverage position in React", "useOpenLeveragePosition hook", "adjust / increase / decrease leverage", "close a leveraged position", "render position health factor / LTV", "list a user''s leverage positions"). New in v2 — integration only, no v1 migration path. Links into the parent sodax-dapp-kit knowledge tree. For backend/Node, use the sodax-sdk skill.'
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
6
|
version: '0.0.1'
|
|
@@ -13,11 +13,19 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
13
13
|
|
|
14
14
|
## Step 1 — Clarify with user before coding
|
|
15
15
|
|
|
16
|
+
0. **Vault or leverage position?** Ask first — they share the `leverageYield` key namespace and nothing else. A **vault** is one pooled ERC-4626 position at a single target LTV (`useLeverageYield*`). A **leverage position** is the user's own AAVE account, cloned per position (`useLeveragePosition*`, `useOpenLeveragePosition`). `useLeverageYieldPosition` is the **vault's** snapshot — it is not a leverage position. If the answer is positions, jump to Step 1b.
|
|
16
17
|
1. **Deposit or withdraw?** Deposit = any token → `lsoda*` shares (lands in the hub wallet). Withdraw = `lsoda*` shares → any token on any chain.
|
|
17
18
|
2. **Build vs execute.** `useLeverageYieldDeposit` / `useLeverageYieldWithdraw` only *build* a `LeverageYieldSwapPayload`; `useLeverageYieldVaultSwap` *executes* it (create → relay → notify solver). You always need both.
|
|
18
19
|
3. **Approval?** Deposit approves the spoke `inputToken` via the swap-domain `useSwapApprove` / `useSwapAllowance` (no leverage-yield-specific approve hook). Withdraw needs no approval (`hubWalletSwap: true`).
|
|
19
20
|
4. **Which reads?** `useLeverageYieldEffectiveApr` (headline APR), `useLeverageYieldPosition` (LTV/health), `useLeverageYieldTotalAssets` (TVL), `useLeverageYieldPreviewRedeem` (price-per-share), `useLeverageYieldShareBalances` (per-chain balances — returns an array).
|
|
20
21
|
|
|
22
|
+
### Step 1b — leverage positions
|
|
23
|
+
|
|
24
|
+
1. **Which mutation?** Decided by the operation, not by preference. Open → `useOpenLeveragePosition`. Leverage change (`buildAddLeverage` / `buildDecreaseLeverage`) → `useSubmitLeveragePositionIntent`. Withdraw / settle / cancel → `useRunLeveragePositionOperation`. The first two report the intent; the third has nothing to report, and routing a leverage change through it leaves an intent nothing will fill. TypeScript enforces this via the `PositionIntentCall` / `PositionDirectCall` brands.
|
|
25
|
+
2. **Approval?** Gate on `useLeveragePositionFundingAllowance`, approve with `useApproveLeveragePositionFunding` — the spender differs per chain and the SDK resolves it. Nothing is ever approved to the factory.
|
|
26
|
+
3. **Sized the leg?** `borrowAmount` / `minCollateralOut` come from `sizeLeverageBorrow` → `getPositionLegQuote` → `projectLeverageLeg`, never oracle parity. Read `ltv` / `liquidationThreshold` from `useEModes` when the position sets an `eModeCategory`.
|
|
27
|
+
4. **Which reads?** `useLeveragePositions` / `useLeveragePositionsForUser` (discovery), `useLeveragePositionAccount` (health/LTV), `useLeveragePositionCollateral` (sizes an exit), `useLeveragePositionPending` (is an intent live), `useLeveragePositionInfo` (this position's own `feeBps`), `useLeveragePositionPayoutAddress` (where a withdrawal can pay — **not a query**, returns synchronously).
|
|
28
|
+
|
|
21
29
|
## Integration workflow (new v2 code)
|
|
22
30
|
|
|
23
31
|
1. [`../integration/knowledge/ai-rules.md`](../integration/knowledge/ai-rules.md) — DO / DO NOT (read first).
|
|
@@ -34,6 +42,17 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
34
42
|
- **Reaching for a `useLeverageYieldApprove` hook.** It doesn't exist — the deposit approves the spoke asset manager, so use the swap-domain hooks.
|
|
35
43
|
- **Quoting on the pre-fee amount.** A deposit's per-intent `partnerFee` is deducted from `inputAmount` before the swap — quote on the post-fee amount or `minOutputAmount` is unfillable.
|
|
36
44
|
|
|
45
|
+
### Leverage-position anti-patterns (dapp-kit)
|
|
46
|
+
|
|
47
|
+
- **Reading `useLeverageYieldPosition` for a leverage position.** That is the **vault's** snapshot. A leverage position's live account is `useLeveragePositionAccount`.
|
|
48
|
+
- **Treating a resolved `useOpenLeveragePosition` as an open position.** It resolves when the intent is LIVE. The hook unwraps the SDK `Result`, so check **`result.notified`** on `mutateAsync`'s value (not `result.value.notified`); `false` means nothing will fill it before it expires. Do not retry on it — that opens a second position.
|
|
49
|
+
- **Routing a leverage change through `useRunLeveragePositionOperation`.** It does not notify. Leverage changes go through `useSubmitLeveragePositionIntent`; the brands refuse the mistake at compile time, so never cast past them.
|
|
50
|
+
- **Calling `notifySolver` yourself after `useSubmitLeveragePositionIntent`.** The hook already reports the intent — read `notified` on its result instead.
|
|
51
|
+
- **Awaiting `useLeveragePositionPayoutAddress` like a query.** It is synchronous: `Address | undefined`, no `data` / `isLoading`. Off the hub a withdrawal pays to a hub address that is **not** the signer, which is exactly what it resolves.
|
|
52
|
+
- **Sizing an exit from `totalCollateralBase`.** Display-only. Use `useLeveragePositionCollateral` — an over-sized `decreaseLeverage` reverts at fill time and the intent silently expires.
|
|
53
|
+
- **Charging an existing position the configured fee.** Read `feeBps` from `useLeveragePositionInfo`; `getEffectivePositionFee()` is what a NEW position would carry.
|
|
54
|
+
- **Treating the mutation receipt as completion.** A solver fills a leverage change afterwards — poll `useLeveragePositionPending`.
|
|
55
|
+
|
|
37
56
|
## Verification
|
|
38
57
|
|
|
39
58
|
1. `pnpm tsc --noEmit` clean.
|
|
@@ -41,6 +60,8 @@ Granular skill for the leverage-yield hooks of `@sodax/dapp-kit` v2. queryKey/mu
|
|
|
41
60
|
3. `useLeverageYieldShareBalances` consumers treat `data` as an array and aggregate.
|
|
42
61
|
4. Withdraw flows do not gate on `useSwapAllowance`.
|
|
43
62
|
5. Mutation flows use `mutateAsyncSafe` and branch on `result.ok`; reads read `data` directly (no `.ok`/`.value`).
|
|
63
|
+
6. Positions: leverage changes use `useSubmitLeveragePositionIntent` (never `useRunLeveragePositionOperation`), `notified` is checked on every open and leverage change, and exits are sized from `useLeveragePositionCollateral` with the fee from `useLeveragePositionInfo`.
|
|
64
|
+
7. Positions: funding is gated on `useLeveragePositionFundingAllowance` + `useApproveLeveragePositionFunding`, and `borrowAmount` / `minCollateralOut` trace back to `sizeLeverageBorrow` + `projectLeverageLeg`.
|
|
44
65
|
|
|
45
66
|
## Related granular skills (same family)
|
|
46
67
|
|
|
@@ -53,7 +53,7 @@ Read-only. No `walletProvider` involved. Convert to single-object query shape.
|
|
|
53
53
|
+ await submit({ request: swapPayload, apiConfig: { baseURL: 'https://...' } }); // v2: per-call config
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
-
`useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTxStatus`) now requires **both** `txHash` and `srcChainKey` (the
|
|
56
|
+
`useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTxStatus`) now requires **both** `txHash` and `srcChainKey` (the status endpoint needs the source chain key) — a v1 call that passed only a tx hash won't run until `srcChainKey` is supplied. The full Swaps API surface is now wrapped as `useSwapsApi*` hooks (see the integration `hooks-index`).
|
|
57
57
|
|
|
58
58
|
## Shared utilities
|
|
59
59
|
|
|
@@ -52,7 +52,7 @@ These keep their name but their TypeScript signature is different. Usually requi
|
|
|
52
52
|
| `useRequestTrustline` → `useEstablishTrustline` | Canonical mutation hook: `{ mutationOptions }` in, `SafeUseMutationResult` out, vars `{ token, amount, srcChainKey, walletProvider }`. `useRequestTrustline` remains as a deprecated wrapper with its 2.0.0 shape — positional `(token: string \| undefined)` (ignored) and `{ requestTrustline, isLoading, isRequested, error, data }` — and is removed in the next major. |
|
|
53
53
|
| `useBackendOrderbook` / `useBackendAllMoneyMarketBorrowers` | Pagination MUST be nested under `params`: `{ params: { pagination: { offset, limit } } }`. |
|
|
54
54
|
| `useBackendUserIntents` | Data is `UserIntentsResponse = { items: IntentResponse[], total, offset, limit }` — NOT a bare array. Access `data?.items`. |
|
|
55
|
-
| `useSwapsApiSubmitTx` / `useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTx` / `useBackendSubmitSwapTxStatus`) | Renamed + moved to the `swapsApi/` namespace (keys now `['swapsApi', …]`). Mutation `apiConfig` moved from hook init to `mutate(vars)`; the status query now requires `srcChainKey`. The rest of the Swaps API
|
|
55
|
+
| `useSwapsApiSubmitTx` / `useSwapsApiSubmitTxStatus` (v1: `useBackendSubmitSwapTx` / `useBackendSubmitSwapTxStatus`) | Renamed + moved to the `swapsApi/` namespace (keys now `['swapsApi', …]`). Mutation `apiConfig` moved from hook init to `mutate(vars)`; the status query now requires `srcChainKey`. The rest of the Swaps API is newly wrapped as `useSwapsApi*` hooks. |
|
|
56
56
|
| All migration hooks | **NEW**: 6 per-action hooks replacing v1's single `useMigrate`. See [`deleted-hooks.md`](deleted-hooks.md). |
|
|
57
57
|
| `useMigrationAllowance` | Query params nest under `params` with inner field literally named `params` (NOT `payload`): `{ params: { params: <migration-params>, action: 'migrate' \| 'revert' } }`. |
|
|
58
58
|
| `BalnMigrateParams` (used by `useMigrateBaln`) | NEW required field `stake: boolean`. `lockupPeriod` is the `LockupPeriod` enum (5 members; values in seconds, not months). |
|
|
@@ -35,9 +35,9 @@ If the user has already picked a single feature, load the matching granular skil
|
|
|
35
35
|
| Stuck-asset recovery | [`./recovery/SKILL.md`](./recovery/SKILL.md) | "recover stuck assets on Sonic", "RecoveryService", "withdrawHubAsset" |
|
|
36
36
|
| Sponsored Stellar account activation | [`./sponsoring/SKILL.md`](./sponsoring/SKILL.md) | "activate a Stellar account", "user has no XLM", "sponsor base reserve", "sodax.sponsoring" |
|
|
37
37
|
| Backend HTTP client (intents, orderbook, MM reads) | [`./backend-api/SKILL.md`](./backend-api/SKILL.md) | "getIntentByHash", "Sodax backend API", "orderbook", "custom IConfigApiV1" |
|
|
38
|
-
| Swaps API
|
|
39
|
-
| Leverage Yield API
|
|
40
|
-
| Bridge API
|
|
38
|
+
| Swaps API client (quote, create-intent, submit-tx, fees) | [`./swaps-api/SKILL.md`](./swaps-api/SKILL.md) | "sodax.api.swaps", "swap quote from backend", "submit swap tx", "swaps API v2" |
|
|
39
|
+
| Leverage Yield API client (vault reads, APR, deposit/withdraw quote + intents) | [`./leverage-yield-api/SKILL.md`](./leverage-yield-api/SKILL.md) | "sodax.api.leverageYield", "vault APR from backend", "vault position from API", "leverage-yield API v2" |
|
|
40
|
+
| Bridge API client (allowance/approve, create-intent, submit-tx, tokens, fee/bridgeable discovery) | [`./bridge-api/SKILL.md`](./bridge-api/SKILL.md) | "sodax.api.bridge", "createBridgeIntent via backend", "submit bridge tx", "bridge API v2" |
|
|
41
41
|
|
|
42
42
|
Load this broad skill (keep reading below) when:
|
|
43
43
|
|
|
@@ -52,7 +52,7 @@ Granular skill for `BackendApiService` — `sodax.backendApi`. HTTP client used
|
|
|
52
52
|
## Related granular skills (same family)
|
|
53
53
|
|
|
54
54
|
- [`../swap/SKILL.md`](../swap/SKILL.md) — `sodax.api.swaps.submitTx` is the backend half of the step-by-step swap flow.
|
|
55
|
-
- [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the full typed Swaps API
|
|
55
|
+
- [`../swaps-api/SKILL.md`](../swaps-api/SKILL.md) — the full typed Swaps API client (`sodax.api.swaps`): quote, create-intent, submit-tx, fees, status.
|
|
56
56
|
- [`../money-market/SKILL.md`](../money-market/SKILL.md) — `BackendApiService` is the canonical source of MM position reads.
|
|
57
57
|
- [`../partner/SKILL.md`](../partner/SKILL.md), [`../recovery/SKILL.md`](../recovery/SKILL.md) — diagnostics for failures via intent / tx lookups.
|
|
58
58
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sodax-sdk-bridge-api
|
|
3
|
-
description: 'Granular skill for the @sodax/sdk v2 Bridge API client — `sodax.api.bridge` (class BridgeApiService), a typed HTTP client for the backend Bridge API
|
|
3
|
+
description: 'Granular skill for the @sodax/sdk v2 Bridge API client — `sodax.api.bridge` (class BridgeApiService), a typed HTTP client for the backend Bridge API (`/bridge/*`: tokens, allowance/approve, create-bridge-intent, submit-tx + status, fee/bridgeable-amount/bridgeable discovery). Every method returns Promise<Result<T>>, never throws, and validates the response. Use when the task calls the bridge backend directly (e.g. "sodax.api.bridge", "createBridgeIntent via the backend API", "submit bridge tx", "poll bridge submit-tx status", "bridge API v2", "point bridge at a custom endpoint", "bridge.useBackendSubmitTx"). For the higher-level end-to-end bridge orchestrator use the `bridge` skill instead. Skill links into the parent sodax-sdk knowledge tree.'
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Bridge API (Core SDK granular skill)
|
|
7
7
|
|
|
8
8
|
Granular skill for `sodax.api.bridge` (class `BridgeApiService`) — the typed HTTP client for the backend
|
|
9
|
-
**Bridge API
|
|
9
|
+
**Bridge API** (`/bridge/*`). `sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the bridge
|
|
10
10
|
client. One method per endpoint; every method returns `Promise<Result<T>>` (never throws) and
|
|
11
11
|
validates the response. Errors carry `feature: 'backend'`, `context.api: 'bridge'`, `context.endpoint`.
|
|
12
12
|
|
|
@@ -138,7 +138,7 @@ Sodax
|
|
|
138
138
|
├── partners — PartnerService (partner fee claiming)
|
|
139
139
|
├── recovery — RecoveryService (withdraw stuck hub-wallet assets)
|
|
140
140
|
├── backendApi — BackendApiService (intent lookup, orderbook, money-market reads, config fetching)
|
|
141
|
-
├── api — alias for backendApi; `api.swaps` is SwapsApiService (typed Swaps API
|
|
141
|
+
├── api — alias for backendApi; `api.swaps` is SwapsApiService (typed Swaps API client)
|
|
142
142
|
├── config — ConfigService (dynamic config; see § 4)
|
|
143
143
|
├── hubProvider — HubProvider (hub contract interactions; concrete impl `EvmHubProvider`)
|
|
144
144
|
└── spoke — SpokeService (per-chain-family router; see § 2)
|
|
@@ -15,9 +15,9 @@ One file per feature service. Each file documents the v2 API surface, common cal
|
|
|
15
15
|
| [`recovery.md`](recovery.md) | `RecoveryService` | Withdraw stuck hub-wallet assets back to a spoke chain. |
|
|
16
16
|
| [`backend-api.md`](backend-api.md) | `BackendApiService` | HTTP client for backend services: swap-tx submission, intent / orderbook lookups, money-market reads. |
|
|
17
17
|
| [`sponsoring.md`](sponsoring.md) | `SponsoringService` | Stellar account activation via sponsored reserves. The sponsor pays the base reserve; the user's wallet signs. |
|
|
18
|
-
| [`swaps-api.md`](swaps-api.md) | `SwapsApiService` | Typed HTTP client for the backend Swaps API
|
|
19
|
-
| [`bridge-api.md`](bridge-api.md) | `BridgeApiService` | Typed HTTP client for the backend Bridge API
|
|
20
|
-
| [`leverage-yield-api.md`](leverage-yield-api.md) | `LeverageYieldApiService` | Typed HTTP client for the backend Leverage Yield API
|
|
18
|
+
| [`swaps-api.md`](swaps-api.md) | `SwapsApiService` | Typed HTTP client for the backend Swaps API (`sodax.api.swaps`, `/swaps/*`). Quote, create-intent, submit-tx + status, fees. |
|
|
19
|
+
| [`bridge-api.md`](bridge-api.md) | `BridgeApiService` | Typed HTTP client for the backend Bridge API (`sodax.api.bridge`, `/bridge/*`). Allowance/approve/create-intent, submit-tx + status, tokens. |
|
|
20
|
+
| [`leverage-yield-api.md`](leverage-yield-api.md) | `LeverageYieldApiService` | Typed HTTP client for the backend Leverage Yield API (`sodax.api.leverageYield`, `/leverage-yield/*`). Vault registry + reads, deposit/withdraw quote + intents, submit-tx + status, fees. |
|
|
21
21
|
|
|
22
22
|
All feature services are constructed and wired by the `Sodax` facade. You don't instantiate them directly — access them via `sodax.swaps`, `sodax.moneyMarket`, etc. See [`../architecture.md`](../architecture.md) for the service graph.
|
|
23
23
|
|
|
@@ -103,7 +103,7 @@ The `IConfigApiV1` interface itself still matters for both patterns — every me
|
|
|
103
103
|
|
|
104
104
|
- v1 → v2 migration of `BackendApiService` (the load-bearing change: every method now returns `Promise<Result<T>>`): [`features/backend-api.md`](../../../migration-v1-to-v2/knowledge/features/backend-api.md).
|
|
105
105
|
- The full submit-tx flow with `createIntent` upstream: [`./swap.md`](swap.md) § "Backend submit-tx flow".
|
|
106
|
-
- The full typed Swaps API
|
|
106
|
+
- The full typed Swaps API client (`sodax.api.swaps`, 21 endpoints — quote, create-intent, submit-tx, fees, status, …): [`./swaps-api.md`](swaps-api.md).
|
|
107
107
|
- Partner-fee handling (separate service): [`./partner.md`](partner.md).
|
|
108
108
|
- Stuck-asset recovery (separate service): [`./recovery.md`](recovery.md).
|
|
109
109
|
- Error model context fields (`error.context.api`, `error.context.method`): [`../reference/`](../reference/) § 3.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Bridge API — `BridgeApiService`
|
|
2
2
|
|
|
3
|
-
Typed HTTP client for the backend **Bridge API
|
|
3
|
+
Typed HTTP client for the backend **Bridge API** (`/bridge/*`). Reachable as `sodax.api.bridge`
|
|
4
4
|
(`sodax.api` is an alias for `sodax.backendApi`; `.bridge` is the `BridgeApiService` instance). One method
|
|
5
5
|
per endpoint. Every method returns `Promise<Result<T>>` — it **never throws** — and every
|
|
6
6
|
response is validated at runtime against a valibot schema, so a backend contract drift surfaces as
|
|
@@ -8,8 +8,15 @@ response is validated at runtime against a valibot schema, so a backend contract
|
|
|
8
8
|
|
|
9
9
|
Access: `sodax.api.bridge`. Service class: `BridgeApiService`. **Errors:** every failure (network, timeout,
|
|
10
10
|
non-2xx HTTP, or response-shape mismatch) returns `Result<T, SodaxError<'EXTERNAL_API_ERROR'>>` with
|
|
11
|
-
`feature: 'backend'`, `context.api: 'bridge'`, and `context.endpoint` (the path)
|
|
12
|
-
is on `error.cause
|
|
11
|
+
`feature: 'backend'`, `context.api: 'bridge'`, and `context.endpoint` (the path). The underlying failure
|
|
12
|
+
is preserved on `error.cause` — a `BridgeApiError` from the `@sodax/bridge-api` client this service wraps
|
|
13
|
+
(read its `code`: `NETWORK_ERROR` | `TIMEOUT_ERROR` | `HTTP_ERROR` | `PARSE_ERROR` | `VALIDATION_ERROR`;
|
|
14
|
+
the same code is mirrored on `error.context.code`, and both `BridgeApiError` and the `BridgeApiErrorCode`
|
|
15
|
+
union are re-exported from `@sodax/sdk`). Idempotent
|
|
16
|
+
reads/polls (and pure-compute POSTs like `getFee`) retry transient failures; mutating calls do not —
|
|
17
|
+
except the apiguard's transient key-verification `503`, which the wire client replays for every call
|
|
18
|
+
(the guard rejects before the handler runs). A `401`/`403` is terminal until the consumer fixes the key.
|
|
19
|
+
Like `sodax.api.swaps`, the bridge **HTTP client** is uniformly `feature: 'backend'`
|
|
13
20
|
(with a per-service `context.api` tag — `'bridge'`).
|
|
14
21
|
|
|
15
22
|
> Lower-level than `sodax.bridge` (the `BridgeService` orchestrator that deposits + relays end-to-end).
|
|
@@ -20,6 +20,10 @@ sodax.bridge.approve<K, Raw>(args): Promise<Result<TxReturnType<K, Raw>, SodaxEr
|
|
|
20
20
|
sodax.bridge.buildApproveTxs<K>(action: BridgeParams<K, true>): Promise<Result<ApprovalTxs<K>, SodaxError>>;
|
|
21
21
|
sodax.bridge.isAllowanceValid<K, Raw>(args): Promise<Result<boolean, SodaxError>>;
|
|
22
22
|
|
|
23
|
+
// Routes from the source tx to whichever source can answer — the backend record while it is in
|
|
24
|
+
// play, else the delivered relay packet. Covers a bridge the client-side fallback completed.
|
|
25
|
+
sodax.bridge.getDetailedStatus({ srcChainKey, srcTxHash }, config?): Promise<Result<DetailedBridgeStatus, SodaxError>>;
|
|
26
|
+
|
|
23
27
|
sodax.bridge.getBridgeableAmount(from: XToken, to: XToken): Promise<Result<BridgeLimit, SodaxError>>;
|
|
24
28
|
sodax.bridge.getBridgeableTokens(from: SpokeChainKey, to: SpokeChainKey, token: string): Result<XToken[], SodaxError>;
|
|
25
29
|
// Plus the sync helpers:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Leverage Yield API — `LeverageYieldApiService`
|
|
2
2
|
|
|
3
|
-
Typed HTTP client for the backend **Leverage Yield API
|
|
3
|
+
Typed HTTP client for the backend **Leverage Yield API** (`/leverage-yield/*`). Reachable as
|
|
4
4
|
`sodax.api.leverageYield` (`sodax.api` is an alias for `sodax.backendApi`; `.leverageYield` is the
|
|
5
5
|
`LeverageYieldApiService` instance). One method per endpoint (33 total). Every method returns
|
|
6
6
|
`Promise<Result<T>>` — it **never throws** — and every response is validated at runtime against a valibot
|
|
@@ -204,13 +204,18 @@ To send a single leverage-yield call elsewhere, use the per-call `RequestOverrid
|
|
|
204
204
|
|
|
205
205
|
## Backend submit-tx flow (SDK option)
|
|
206
206
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
207
|
+
`sodax.leverageYield.vaultSwap` routes through this client's `submitTx` + `getSubmitTxStatus` (relay +
|
|
208
|
+
post-execution server-side) **by default**, polling until `'solved'` and falling back to the client-side
|
|
209
|
+
relay on any non-success — the leverage-yield mirror of `swaps.useBackendSubmitTx`, defaulting on the same
|
|
210
|
+
way. Opt out with `new Sodax({ leverageYield: { useBackendSubmitTx: false } })`; read the effective value
|
|
211
|
+
on `sodax.config.leverageYieldUseBackendSubmitTx`. `timeout` is a per-attempt budget: the backend attempt
|
|
212
|
+
gets it and the fallback relay gets a fresh one.
|
|
213
|
+
|
|
214
|
+
`POST /leverage-yield/submit-tx` declares an API-key scope (`swaps:write`) where
|
|
215
|
+
`GET /leverage-yield/submit-tx/status` declares none. Enforcement is per-deployment, so a keyless submit
|
|
216
|
+
is not necessarily rejected; where it is, the caller spends one rejected attempt per vault swap before the
|
|
217
|
+
fallback completes it. Configure `apiKey`, pass `extras.apiKey` per call, or opt out. `swaps/submit-tx`
|
|
218
|
+
declares the same scope — this is not specific to leverage yield. See [`leverage-yield.md`](leverage-yield.md).
|
|
214
219
|
|
|
215
220
|
## Error handling
|
|
216
221
|
|
|
@@ -4,7 +4,9 @@ Leveraged-yield ERC-4626 vaults on the Sonic hub. A vault loops supply → borro
|
|
|
4
4
|
|
|
5
5
|
Access: `sodax.leverageYield`. Service class: `LeverageYieldService`. Feature tag for errors: `'leverageYield'`.
|
|
6
6
|
|
|
7
|
-
> **
|
|
7
|
+
> **Two products on one service.** Everything above the "Leverage positions" section is the **vault** — one shared ERC-4626 position at a single target LTV, entered and exited as an intent swap. A **leverage position** is the unpooled counterpart: one owner-controlled AAVE account per position, cloned by `LeveragePositionFactory`, with its own eMode category and leverage tier. They share the service and nothing else — vault methods take a `vault` address, position methods take a `position` address or open a new clone.
|
|
8
|
+
|
|
9
|
+
> **Backend HTTP client:** for the typed `sodax.api.leverageYield` client that calls the backend Leverage Yield API directly (vault reads, deposit/withdraw quotes + intents, submit-tx), see [`leverage-yield-api.md`](leverage-yield-api.md). `vaultSwap` routes through that client's submit-tx flow **by default** (with client-side fallback); opt out with `new Sodax({ leverageYield: { useBackendSubmitTx: false } })`.
|
|
8
10
|
|
|
9
11
|
## How it works
|
|
10
12
|
|
|
@@ -32,6 +34,12 @@ sodax.leverageYield.vaultSwap<K>(params: VaultSwapActionParams<K, false>): Promi
|
|
|
32
34
|
sodax.leverageYield.notifySolver(request: { intent_tx_hash: string }): Promise<Result<SolverExecutionResponse, SodaxError>>;
|
|
33
35
|
// notifySolver is PUBLIC — call it to finish a manual createVaultIntent → relay → notify flow
|
|
34
36
|
|
|
37
|
+
// Status. getDetailedStatus takes the SOURCE tx (what you hold after vaultSwap) and routes to whichever
|
|
38
|
+
// source can answer; getIntentStatus takes the HUB tx and asks the solver directly.
|
|
39
|
+
sodax.leverageYield.getDetailedStatus(key: { srcChainKey, srcTxHash }, config?: RequestOverrideConfig):
|
|
40
|
+
Promise<Result<DetailedLeverageYieldStatus, SodaxError>>;
|
|
41
|
+
sodax.leverageYield.getIntentStatus(request: { intent_tx_hash: string }): Promise<Result<SolverIntentStatusResponse, SodaxError>>;
|
|
42
|
+
|
|
35
43
|
// Sonic-direct allowance for the vault's underlying asset (the swap-style deposit handles its own approvals)
|
|
36
44
|
sodax.leverageYield.approve<R>(params: LeverageYieldApproveParams<R>): Promise<Result<TxReturnType<HubChainKey, R>, SodaxError>>;
|
|
37
45
|
sodax.leverageYield.isAllowanceValid(params: LeverageYieldAllowanceParams): Promise<Result<boolean, SodaxError>>;
|
|
@@ -88,10 +96,20 @@ type LeverageYieldSwapWithdrawParams = {
|
|
|
88
96
|
|
|
89
97
|
// The execute-mode wrapper (createVaultIntent / vaultSwap). The two vault execution modifiers
|
|
90
98
|
// live HERE, never on the generic swap surface:
|
|
91
|
-
type VaultSwapActionParams<K, Raw> = SpokeExecActionParams<K, Raw, CreateIntentParams<K
|
|
99
|
+
type VaultSwapActionParams<K, Raw> = SpokeExecActionParams<K, Raw, CreateIntentParams<K>, LeverageYieldExtras> & {
|
|
92
100
|
hubWalletSwap?: boolean; // withdraw: inputToken is hub-wallet lsoda*, authorise via Connection.sendMessage
|
|
93
101
|
partnerFee?: PartnerFee; // beats config.leverageYield.partnerFee for this intent only
|
|
94
102
|
};
|
|
103
|
+
type LeverageYieldExtras = { apiKey?: string }; // per-action key for the backend submit-tx leg only
|
|
104
|
+
|
|
105
|
+
// getDetailedStatus — discriminated on `source`, no guards needed. Arms are swap's, not bridge's:
|
|
106
|
+
// a vault swap IS a solver intent, so the second source is the solver, not a terminal relay packet.
|
|
107
|
+
type DetailedLeverageYieldStatus =
|
|
108
|
+
| { source: 'backend'; data: SubmitTxStatusDataV2 }
|
|
109
|
+
| { source: 'solver'; dstTxHash: Hex; data: SolverIntentStatusResponse };
|
|
110
|
+
// On failure: LOOKUP_FAILED. A rejected key stops there with context.status set (isAuthFailure) —
|
|
111
|
+
// never routed on. Otherwise branch on error.context.reason: DETAILED_STATUS_NOT_DELIVERED is the one
|
|
112
|
+
// ambiguous miss a caller should bound with a retry budget; anything else is a live dependency failure.
|
|
95
113
|
```
|
|
96
114
|
|
|
97
115
|
## Common call shapes
|
|
@@ -169,7 +187,7 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
|
|
|
169
187
|
|
|
170
188
|
## Error codes
|
|
171
189
|
|
|
172
|
-
`feature: 'leverageYield'`. Action discriminator on `context.action`: `'deposit' | 'withdraw' | 'approve' | 'allowanceCheck' | 'vaultSwap'`. Read methods partition on `context.method`.
|
|
190
|
+
`feature: 'leverageYield'`. Action discriminator on `context.action`: `'deposit' | 'withdraw' | 'approve' | 'allowanceCheck' | 'vaultSwap' | 'openPosition' | 'openPositionFromDebtToken' | 'operatePosition' | 'openLeveragePosition' | 'submitLeveragePositionIntent' | 'runLeveragePositionOperation' | 'getPositionLegQuote'`. Read methods partition on `context.method`.
|
|
173
191
|
|
|
174
192
|
| Method | Narrow code union |
|
|
175
193
|
|---|---|
|
|
@@ -181,9 +199,182 @@ approval can take two transactions" in [`architecture.md`](../architecture.md).
|
|
|
181
199
|
| `approve` | `VALIDATION_FAILED \| APPROVE_FAILED \| UNKNOWN` |
|
|
182
200
|
| `isAllowanceValid` | `VALIDATION_FAILED \| ALLOWANCE_CHECK_FAILED \| UNKNOWN` (action `'allowanceCheck'`) |
|
|
183
201
|
| Read methods | `VALIDATION_FAILED \| LOOKUP_FAILED \| UNKNOWN` (with `method` discriminator) |
|
|
202
|
+
| `openPosition`, `openPositionFromDebtToken`, `openLeveragePosition` | `LeverageYieldSwapError \| LeverageYieldLookupError` — the swap subset plus `LOOKUP_FAILED` (hub-wallet / factory resolution). `VALIDATION_FAILED` with `field: 'srcChainKey'` is the Bitcoin refusal |
|
|
203
|
+
| `operatePosition`, `submitLeveragePositionIntent`, `runLeveragePositionOperation` | `LeverageYieldSwapError` |
|
|
204
|
+
| `getPositionLegQuote` | same as `getQuote` — a `SolverErrorResponse` arm plus the lookup subset; guard with `isSodaxError` |
|
|
205
|
+
| `isPositionFundingAllowanceValid` / `approvePositionFunding` | `ALLOWANCE_CHECK_FAILED` / `APPROVE_FAILED` subsets (actions `'allowanceCheck'` / `'approve'`) |
|
|
206
|
+
| Position reads + `getEffectivePositionFee` | `VALIDATION_FAILED \| LOOKUP_FAILED \| UNKNOWN`. A blanked `positionFactory` fails closed here |
|
|
184
207
|
|
|
185
208
|
Relay/tx-verification codes appear **only** on `vaultSwap` — `createVaultIntent` alone stays within the create-intent subset. `notifySolver` (public, for manual orchestration) emits the post-execution subset, which `vaultSwap` also surfaces.
|
|
186
209
|
|
|
210
|
+
## Leverage positions
|
|
211
|
+
|
|
212
|
+
One AAVE account per position, cloned by `LeveragePositionFactory`. AAVE allows one eMode category per address, so a vault forces every depositor into one category and one leverage tier while an owner can hold several positions at different tiers at once. There is **no static registry** — discovery goes through the factory.
|
|
213
|
+
|
|
214
|
+
The factory ships as a packaged default, so `new Sodax()` drives positions with no configuration. Override only to point at a fork or staging deployment (`new Sodax({ leverageYield: { positionFactory: '0x…' } })`). Blanking it deliberately is honoured and factory-backed methods then fail closed with `LOOKUP_FAILED` rather than guessing an address. Position-only reads (`getPositionInfo`, `getPositionAccount`, `getPositionCollateralBalance`, `getPositionPendingState`) target the position directly and never need the factory.
|
|
215
|
+
|
|
216
|
+
> **`@experimental` off the hub.** Proven end to end on Sonic only. From a spoke the inbound half is verified by a fork replay of a real relayed message; the outbound half (an exit or cancel delivering the underlying back to the source chain) has never run on mainnet. **Bitcoin is refused outright** — in TRADING mode the deposit is pulled from the Bound trading wallet and these paths do not derive the hub wallet from it, so a Bitcoin `srcChainKey` returns `VALIDATION_FAILED` (`field: 'srcChainKey'`) instead of funding the wrong wallet.
|
|
217
|
+
|
|
218
|
+
### Reads
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
sodax.leverageYield.listPositions(owner: Address): Promise<Result<readonly Address[], LeverageYieldLookupError>>;
|
|
222
|
+
sodax.leverageYield.listPositionsForUser(srcChainKey, srcAddress): Promise<Result<readonly Address[], …>>; // POSITIONAL args, not an object
|
|
223
|
+
sodax.leverageYield.getPositionInfo(position: Address): Promise<Result<LeveragePosition, …>>;
|
|
224
|
+
sodax.leverageYield.getPositionAccount(position: Address): Promise<Result<LeveragePositionAccount, …>>;
|
|
225
|
+
sodax.leverageYield.getPositionCollateralBalance(position, collateral?): Promise<Result<LeveragePositionCollateral, …>>;
|
|
226
|
+
sodax.leverageYield.getPositionPendingState(position: Address): Promise<Result<LeveragePositionPendingState, …>>;
|
|
227
|
+
sodax.leverageYield.predictPosition(creator, owner, positionId?): Promise<Result<Address, …>>; // defaults to the next id
|
|
228
|
+
sodax.leverageYield.getEffectivePositionFee(override?): Result<{ feeReceiver: Address; feeBps: number }, …>; // SYNCHRONOUS
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
| Type | Fields |
|
|
232
|
+
|---|---|
|
|
233
|
+
| `LeveragePosition` | `{ address, owner, collateral, borrowToken, eModeCategory, feeBps, feeReceiver }` — static descriptor, fee fixed at creation |
|
|
234
|
+
| `LeveragePositionAccount` | `{ totalCollateralBase, totalDebtBase, availableBorrowsBase, currentLiquidationThreshold, ltv, healthFactor }` — all bigint |
|
|
235
|
+
| `LeveragePositionCollateral` | `{ aToken, balance }` — exact aToken balance in the collateral reserve's decimals |
|
|
236
|
+
| `LeveragePositionPendingState` | `{ kind: number, isLive: boolean, needsSettle: boolean }` |
|
|
237
|
+
|
|
238
|
+
`getPositionAccount` reads `getUserAccountData` on the pool, not the position contract (which keeps no accounting). `healthFactor` is WAD (1e18); the `*Base` figures use the pool oracle's 8-decimal base unit and are **display-only**. Any amount going into a transaction comes from `getPositionCollateralBalance` — dividing base currency back out by a price lands only *near* the balance, and a `decreaseLeverage` asking for more collateral than the position holds does not fail on submission: the hook's `transferFrom` reverts at fill time and the intent silently expires.
|
|
239
|
+
|
|
240
|
+
### Writes — use the high-level calls
|
|
241
|
+
|
|
242
|
+
`openPosition`, `openPositionFromDebtToken` and `operatePosition` only **post** the intent. Reporting it is a separate `notifySolver` call, and an unreported intent expires unfilled — the owner ends up funded with leverage that never arrives and nothing said so. Three methods pair the two steps, and which one to use is decided by the operation, not by preference:
|
|
243
|
+
|
|
244
|
+
| operation | method | notifies |
|
|
245
|
+
|---|---|---|
|
|
246
|
+
| open, either side | `openLeveragePosition({ side?, params, walletProvider })` | yes |
|
|
247
|
+
| `buildAddLeverage` / `buildDecreaseLeverage` | `submitLeveragePositionIntent({ params: { srcChainKey, srcAddress, calls }, walletProvider })` | yes |
|
|
248
|
+
| `buildPositionWithdraw` / `buildSettlePosition` / `buildCancelPositionOperation` | `runLeveragePositionOperation(…)` | no |
|
|
249
|
+
|
|
250
|
+
`withdraw`, `settle` and `cancel` are synchronous on the hub and need no notification. **The compiler enforces the rows:** `buildAddLeverage` / `buildDecreaseLeverage` return `PositionIntentCall`, the other three return `PositionDirectCall`, and each method accepts only its own. The brands are type-only and erased at runtime. A direct call may ride along in a reporting batch (`[buildSettlePosition, buildAddLeverage]` is the sequence batching exists for); an intent call on the route-only path is refused.
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
sodax.leverageYield.openLeveragePosition<K>(params:
|
|
254
|
+
| ({ side?: 'collateral' } & SpokeExecActionParams<K, false, OpenPositionParams<K>>)
|
|
255
|
+
| ({ side: 'debt' } & SpokeExecActionParams<K, false, OpenPositionFromDebtTokenParams<K>>)
|
|
256
|
+
): Promise<Result<LeveragePositionIntentResult, LeverageYieldSwapError | LeverageYieldLookupError>>;
|
|
257
|
+
|
|
258
|
+
sodax.leverageYield.submitLeveragePositionIntent<K>(
|
|
259
|
+
params: SpokeExecActionParams<K, false, PositionOperationParams<K, PositionBatchCall>>
|
|
260
|
+
): Promise<Result<LeveragePositionIntentResult, LeverageYieldSwapError>>;
|
|
261
|
+
|
|
262
|
+
sodax.leverageYield.runLeveragePositionOperation<K>(
|
|
263
|
+
params: SpokeExecActionParams<K, false, PositionOperationParams<K, PositionDirectCall>>
|
|
264
|
+
): Promise<Result<TxHashPair, LeverageYieldSwapError>>;
|
|
265
|
+
|
|
266
|
+
// LeveragePositionIntentResult = { txHashes: TxHashPair; notified: boolean; notifyError?: string }
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
**A failed notification is `ok: true`, deliberately.** The money has already moved and the intent is live on the hub; returning a failure would tell the caller nothing happened, and a caller that retries on failure would open a second position. Read `notified` on the value — `false` means nothing will fill the intent before it expires.
|
|
270
|
+
|
|
271
|
+
### Params shape
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
type PositionFundingParams<K> = {
|
|
275
|
+
srcChainKey: K;
|
|
276
|
+
srcAddress: string; // funds come from here; a failed intent refunds here
|
|
277
|
+
token: string; // token on srcChainKey to fund with
|
|
278
|
+
amount: bigint; // in `token`'s OWN decimals — wrapping to the 18-dp hub reserve happens in the batch
|
|
279
|
+
eModeCategory?: number; // fixed for the life of the position; defaults to 0
|
|
280
|
+
minCollateralOut: bigint; // slippage floor on what the solver must deliver
|
|
281
|
+
partnerFee?: PartnerFee; // percentage variant only; FIXED AT CREATION, capped (see `MAX_POSITION_FEE_BPS` in `packages/sdk/src/leverageYield/LeverageYieldService.ts`); rate and receiver must be set together or not at all; defaults to leverageYield.partnerFee
|
|
282
|
+
};
|
|
283
|
+
type OpenPositionParams<K> = PositionFundingParams<K> & { borrowToken: Address; borrowAmount: bigint };
|
|
284
|
+
type OpenPositionFromDebtTokenParams<K> = PositionFundingParams<K> & { collateral: Address; totalInput: bigint };
|
|
285
|
+
type PositionOperationParams<K, C> = { srcChainKey: K; srcAddress: string; calls: readonly C[] };
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
There is **no `owner`**: the factory requires `cfg.owner == msg.sender` and the caller is always the funder's own hub wallet. That binding is what makes the refund address safe — `originAddress` decides where a cancelled operation's funds go, and past a deadline anyone may trigger that cancel. To fund someone else, supply into a position they already own: `pool.supply(collateral, amount, position, 0)`.
|
|
289
|
+
|
|
290
|
+
### Funding approval
|
|
291
|
+
|
|
292
|
+
**Nothing is ever approved to the factory** — it pulls from nobody. Funding is a transfer to `predictPosition(...)` and the clone supplies whatever it finds, batched with the create so a stale prediction reverts and takes the transfer with it rather than stranding tokens. Do not open two positions for one owner concurrently: the owner's own second open is the only thing that can advance the id, and off the hub the deposit has already reached the hub wallet when the batch reverts — recover it with `sodax.recovery`. The one approval that does exist has a spender that **differs by chain** — the user's own hub wallet on the hub (the pull happens inside the routed batch), the spoke asset manager elsewhere:
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
sodax.leverageYield.isPositionFundingAllowanceValid({ srcChainKey, srcAddress, token, amount }): Promise<Result<boolean, …>>;
|
|
296
|
+
sodax.leverageYield.approvePositionFunding({ srcChainKey, srcAddress, token, amount, walletProvider? }): Promise<Result<TxReturnType<K, false>, …>>;
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
`approvePositionFunding` waits for the approve to land before resolving — `verifyTxHash` returns `{ ok: true }` for EVM without waiting, which is why hand-rolled callers were asking users to approve twice.
|
|
300
|
+
|
|
301
|
+
### Sizing the leg — do not skip
|
|
302
|
+
|
|
303
|
+
`borrowAmount` / `minCollateralOut` are yours to supply and **computing them from oracle prices does not work**. Leverage is bought through the solver and the two legs do not trade at their oracle ratio: `LeverageHook` supplies whatever the solver actually paid and only *then* borrows against it, so the pool sees `deposit + solver output`, never `deposit × leverage`. Parity sizing gets the borrow rejected with Aave `'36'` (COLLATERAL_CANNOT_COVER_NEW_BORROW) *after* the solver has filled, unwinding the whole fill. It happened twice on mainnet — once at 11.03x where parity predicted 84% LTV against a real 92.06% and a 91% cap.
|
|
304
|
+
|
|
305
|
+
```ts
|
|
306
|
+
import { sizeLeverageBorrow, projectLeverageLeg, type LeverageLegRequest } from '@sodax/sdk';
|
|
307
|
+
|
|
308
|
+
// LeverageLegRequest = { side, deposit, depositDecimals, collateralPriceUsd, borrowPriceUsd,
|
|
309
|
+
// borrowDecimals, leverage, feeBps? }
|
|
310
|
+
// 1. Oracle-sized, because there is nothing else yet.
|
|
311
|
+
const { borrowAmount, intentInput } = sizeLeverageBorrow(request);
|
|
312
|
+
// LeverageBorrowSizing = { borrowAmount, intentInput, depositUsd, borrowUsd, feeAmount }
|
|
313
|
+
|
|
314
|
+
// 2. Quote `intentInput`, NOT `borrowAmount` — on a debt-side open the user's contribution goes to
|
|
315
|
+
// the solver too. Use getPositionLegQuote: it names the hub reserves the intent actually swaps
|
|
316
|
+
// and quotes gross, the two details a hand-rolled getQuote gets wrong.
|
|
317
|
+
const leg = await sodax.leverageYield.getPositionLegQuote({
|
|
318
|
+
inputHubToken: borrowReserve.underlyingAsset, // the hub RESERVE ADDRESS, not the reserve object
|
|
319
|
+
outputHubToken: collateralReserve.underlyingAsset,
|
|
320
|
+
amount: intentInput,
|
|
321
|
+
});
|
|
322
|
+
if (!leg.ok) throw leg.error; // PositionLegQuote = { quotedAmount }
|
|
323
|
+
|
|
324
|
+
// 3. Now the honest numbers, from the quote.
|
|
325
|
+
const p = projectLeverageLeg(
|
|
326
|
+
request,
|
|
327
|
+
{ quotedCollateral: leg.value.quotedAmount, collateralDecimals }, // LeverageLegQuote
|
|
328
|
+
{ ltv, liquidationThreshold }, // ReserveRiskParams (numbers, not bps)
|
|
329
|
+
slippagePct,
|
|
330
|
+
);
|
|
331
|
+
if (p.exceedsMaxLtv) throw new Error(`max ~${p.usableMaxLeverage.toFixed(2)}x at this price`);
|
|
332
|
+
// open with { borrowAmount, minCollateralOut: p.minCollateralOut }
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
`LeverageLegProjection = { minCollateralOut, collateralUsd, debtUsd, ltv, healthFactor, exceedsMaxLtv, usableMaxLeverage, haircut, inputUsd, costUsd, exposureLeverage }`. Four things about it:
|
|
336
|
+
|
|
337
|
+
- **`exceedsMaxLtv` is a hard gate, not a warning.** Post through it and the intent is accepted, then fails at fill.
|
|
338
|
+
- **`usableMaxLeverage` is the real ceiling, strictly below `1 / (1 - ltv)`.** At `ltv` 91% with the solver returning 98.77% of parity it is 9.88x — so an 11.03x that looked fine against parity was never available.
|
|
339
|
+
- **Everything is projected from the FLOOR, not the quote** — the floor is the worst fill the intent permits, so if the floor is safe every fill is. `haircut` and `costUsd` are the exception: expected cost measured from the quote, which is what a payback period should use.
|
|
340
|
+
- **`leverage` is a multiple of the DEPOSIT and the open position reports more.** The borrow is booked in full while the collateral arrives short by the haircut, leaving `deposit × (1 - (L-1)h)` of equity. Always higher, never lower: 2.00x requested at a 4.657% haircut reports **2.0488x**. Display `exposureLeverage`, not the number the user chose.
|
|
341
|
+
|
|
342
|
+
Read `ltv` / `liquidationThreshold` from the eMode category whenever the position sets one — a category's LTV replaces the reserve's own. **On a debt-side open the deposit is not collateral**: it is handed to the solver as part of the input, so the only collateral the position ends up with is what the solver delivers. Counting it on both sides is the other half of that 84%-vs-92% miss; `side: 'debt'` handles it.
|
|
343
|
+
|
|
344
|
+
### Fees — read them from the POSITION, not from config
|
|
345
|
+
|
|
346
|
+
`getEffectivePositionFee()` answers what a position created *now* would carry, which is what an **open** needs. An existing position's fee was fixed at creation, so config changes and per-call overrides make the two disagree — `getPositionInfo` returns that position's own `feeBps` / `feeReceiver`, and an adjust or exit has to charge those. The fee is given up **on top of** what the solver is paid, so at a non-zero fee an exit sized at the whole collateral balance leaves nothing for it and cannot settle: the input is `balance × 10_000 / (10_000 + feeBps)`.
|
|
347
|
+
|
|
348
|
+
### Low-level builders
|
|
349
|
+
|
|
350
|
+
Builders return an `EvmRawTransaction` for the caller to run as the hub wallet. Every position write is `onlyOwner` and the owner is the hub wallet, so a builder's transaction sent from the signing address reverts — setting `from` does not help, an address cannot send as another address. Reach for the three high-level methods above; these are the unit they carry.
|
|
351
|
+
|
|
352
|
+
| Builder | Effect |
|
|
353
|
+
|---|---|
|
|
354
|
+
| `buildCreatePositionAndLeverage(…)` | Clone and lever in one tx. `initialAssets` must ALREADY be at the position's address |
|
|
355
|
+
| `buildCreatePositionFromDebtToken(…)` | Open from the **debt** token with no collateral of your own |
|
|
356
|
+
| `buildAddLeverage(…)` | Borrow and swap into more collateral → `PositionIntentCall` |
|
|
357
|
+
| `buildDecreaseLeverage(…)` | Give up collateral to repay debt; with the whole balance this is a close into the debt token → `PositionIntentCall` |
|
|
358
|
+
| `buildPositionWithdraw(…)` | Withdraw collateral out, to any address → `PositionDirectCall` |
|
|
359
|
+
| `buildSettlePosition(…)` | Clear a resolved operation and sweep loose funds to the owner. Permissionless → `PositionDirectCall` |
|
|
360
|
+
| `buildCancelPositionOperation(…)` | Cancel the in-flight operation → `PositionDirectCall` |
|
|
361
|
+
|
|
362
|
+
The two create builders return a `Result` (they need the factory address); the rest target the position directly and return the transaction unwrapped. `encodePositionCalls(txs)` gives the hub-wallet payload if you want to drive `spoke.deposit` / `spoke.sendMessage` yourself.
|
|
363
|
+
|
|
364
|
+
Three behaviours to design around:
|
|
365
|
+
|
|
366
|
+
- **Leverage changes are asynchronous.** `addLeverage` / `decreaseLeverage` only post an intent; poll `getPositionPendingState` instead of treating the receipt as completion. A position refuses a second operation while one is in flight.
|
|
367
|
+
- **Which hash to report.** `TxHashPair` returns both. `srcChainTxHash` is what the user signed; **`dstChainTxHash`** is the hub transaction the intent exists in, and that is the one `notifySolver` needs. On the hub they are the same transaction; from a spoke they are not.
|
|
368
|
+
- **Cancelling returns nothing, because nothing was escrowed.** Posting a position intent moves no funds; cancelling revokes the grant and clears the pending slot.
|
|
369
|
+
|
|
370
|
+
### Closing a position
|
|
371
|
+
|
|
372
|
+
Two exits, differing in what the owner ends up holding. **Into the collateral:** sell only as much collateral as the debt is worth (`buildDecreaseLeverage`), wait for the fill, then `buildPositionWithdraw` the remainder — two operations, and the withdrawal can pay out to any address. Overshoot the debt slightly; it accrues between quoting and filling, and dust debt left behind blocks the withdrawal entirely. **Into the debt token:** sell the collateral balance in one `buildDecreaseLeverage` (net of `feeBps`, see above); the solver delivers more debt token than is owed, the hook repays and leaves the surplus for `buildSettlePosition` to sweep to the position's `owner` — not to whoever signed.
|
|
373
|
+
|
|
374
|
+
A full exit cannot half-happen: were the delivered amount short of the debt, the hook's withdrawal would leave debt against no collateral and the pool's health-factor check rejects it, reverting the whole fill. Quote the full amount and check the floor covers the debt before posting.
|
|
375
|
+
|
|
376
|
+
Collateral top-ups and debt repayment need no SDK call — AAVE accepts both against an arbitrary account (`pool.supply(collateral, amount, position, 0)`, `pool.repay(borrowToken, amount, 2, position)`), so defending a position never waits on a solver fill.
|
|
377
|
+
|
|
187
378
|
## Cross-references
|
|
188
379
|
|
|
189
380
|
- ERC-4626 share-as-token model, APR math, and the deliberate swap-domain duplication: SDK source `packages/sdk/docs/LEVERAGE_YIELD.md`.
|
|
@@ -50,7 +50,7 @@ sodax.swaps.isAllowanceValid<K, Raw>(/* … */): Promise<Result<boolean, SodaxEr
|
|
|
50
50
|
sodax.swaps.getSwapSpeedTier(params: { srcToken: XToken; dstToken: XToken }): SwapSpeedTierResult;
|
|
51
51
|
// Synchronous, offline, no Result wrapper — estimates settlement speed from SDK config alone
|
|
52
52
|
// (no network / on-chain / backend call). SwapSpeedTierResult = { tier: 'fast'|'normal'|'slow', estimatedSeconds }.
|
|
53
|
-
// A token
|
|
53
|
+
// A token whose `vault` is a money-market reserve (sodaAsset) settles faster; an Ethereum leg adds a fixed penalty.
|
|
54
54
|
// Safe to call synchronously while rendering a quote (e.g. an ETA badge next to the output amount).
|
|
55
55
|
|
|
56
56
|
sodax.swaps.getStatus(
|
|
@@ -83,7 +83,7 @@ if (status.source === 'backend') status.data.processingAttempts;
|
|
|
83
83
|
|
|
84
84
|
Routing: backend record while it is in play (`success: true` and not abandoned) → `source: 'backend'`. **Any** unusable backend response — 404, `success: false`, transport/server error, or a record the backend gave up on (`failed` or `abandonedAt`) — resolves the hub tx hash and asks the solver → `source: 'solver'`. On the default path the abandoned-record branch is the common one, not the 404: the record usually exists, and abandonment is what signals the client-side fallback ran.
|
|
85
85
|
|
|
86
|
-
The only error is `LOOKUP_FAILED`, meaning no source could answer — usually the relay has not delivered the packet, so there is no hub tx hash. When polling, branch on `error.context.reason`: `DETAILED_STATUS_NOT_DELIVERED` is the ambiguous miss (indistinguishable from "still in flight" — bound it with a retry budget), set only when the backend also answered. Anything else, including a relay miss behind a backend outage, is a dependency failing right now and should be retried until it recovers. Point-in-time — poll it yourself, or use dapp-kit's `useDetailedStatus`.
|
|
86
|
+
The only error is `LOOKUP_FAILED`, meaning no source could answer — usually the relay has not delivered the packet, so there is no hub tx hash. When polling, branch on `error.context.reason`: `DETAILED_STATUS_NOT_DELIVERED` is the ambiguous miss (indistinguishable from "still in flight" — bound it with a retry budget), set only when the backend also answered. Anything else, including a relay miss behind a backend outage, is a dependency failing right now and should be retried until it recovers. A 401/403 from the backend does not route on at all — it surfaces directly with `context.status` lifted, so `isAuthFailure(error)` is true and polling should stop; only a corrected key changes the answer. Point-in-time — poll it yourself, or use dapp-kit's `useDetailedStatus`.
|
|
87
87
|
|
|
88
88
|
## Action params shape
|
|
89
89
|
|
|
@@ -280,21 +280,39 @@ const { tx: spokeTxHash, intent, relayData } = result.value;
|
|
|
280
280
|
|
|
281
281
|
### Backend submit-tx flow
|
|
282
282
|
|
|
283
|
+
Submitting is only the first half. `swap()` also polls to a terminal status and falls back to the client-side relay on any non-success — code that drives the steps itself must do both. Full recipe: [`../recipes/manual-submit-tx-with-fallback.md`](../recipes/manual-submit-tx-with-fallback.md).
|
|
284
|
+
|
|
283
285
|
```ts
|
|
284
286
|
const submitResult = await sodax.api.swaps.submitTx({
|
|
285
287
|
txHash: spokeTxHash as string,
|
|
286
288
|
srcChainKey: ChainKeys.ARBITRUM_MAINNET,
|
|
287
|
-
walletAddress: '0x…',
|
|
289
|
+
walletAddress: '0x…', // the SOURCE address that signed
|
|
288
290
|
intent, // IntentRequestV2 — CreateIntentResult.value.intent passes through
|
|
289
291
|
relayData: relayData.payload, // string (not the object)
|
|
290
292
|
});
|
|
291
293
|
|
|
294
|
+
// Two distinct failure arms — the reason lives in a different place on each.
|
|
292
295
|
if (!submitResult.ok) {
|
|
293
|
-
// submitResult.error.code
|
|
294
|
-
|
|
296
|
+
// Transport / HTTP / validation: submitResult.error.code is 'EXTERNAL_API_ERROR'
|
|
297
|
+
// with context.api: 'swaps'. There is no `value`.
|
|
298
|
+
return fallbackToClientSideRelay();
|
|
299
|
+
}
|
|
300
|
+
if (!submitResult.value.success) {
|
|
301
|
+
// 200, but the backend did NOT queue it. There is no `error` here — the reason is
|
|
302
|
+
// on the payload: submitResult.value.data.message.
|
|
303
|
+
return fallbackToClientSideRelay();
|
|
295
304
|
}
|
|
305
|
+
|
|
306
|
+
// Then poll `sodax.api.swaps.getSubmitTxStatus({ txHash, srcChainKey })`:
|
|
307
|
+
// status 'solved' AND result.dstIntentTxHash AND result.intent_hash → done
|
|
308
|
+
// status 'failed', or `abandonedAt` set → terminal, fall back
|
|
309
|
+
// 401/403 (isAuthFailure) → stop polling, fall back
|
|
310
|
+
// pending | relaying | relayed | posting_execution | posted_execution → keep polling
|
|
311
|
+
// budget exhausted → fall back
|
|
296
312
|
```
|
|
297
313
|
|
|
314
|
+
Do NOT call `verifyTxHash` before submitting — the backend verifies itself, so a client-side confirmation wait only delays every backend success. Verification belongs to the fallback path. The fallback relay also needs its own FRESH timeout, never the remainder of the backend attempt's.
|
|
315
|
+
|
|
298
316
|
### Raw-tx flow
|
|
299
317
|
|
|
300
318
|
```ts
|
|
@@ -373,6 +391,7 @@ Solver-specific context on `EXTERNAL_API_ERROR`:
|
|
|
373
391
|
|
|
374
392
|
## Cross-references
|
|
375
393
|
|
|
394
|
+
- Driving the steps yourself (backend submit-tx + fallback): [`../recipes/manual-submit-tx-with-fallback.md`](../recipes/manual-submit-tx-with-fallback.md).
|
|
376
395
|
- v1 → v2 swap migration: [`features/swap.md`](../../../migration-v1-to-v2/knowledge/features/swap.md).
|
|
377
396
|
- Error model: [`../architecture.md`](../architecture.md) § 8 and [`../reference/`](../reference/) § 3.
|
|
378
397
|
- Stellar destinations require a trustline first: [`../chain-specifics.md`](../chain-specifics.md) § "Stellar trustline".
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Swaps API — `SwapsApiService`
|
|
2
2
|
|
|
3
|
-
Typed HTTP client for the backend **Swaps API
|
|
3
|
+
Typed HTTP client for the backend **Swaps API** (`/swaps/*`). Reachable as `sodax.api.swaps`
|
|
4
4
|
(`sodax.api` is an alias for `sodax.backendApi`; `.swaps` is the `SwapsApiService` instance). One method
|
|
5
5
|
per endpoint (21 total). Every method returns `Promise<Result<T>>` — it **never throws** — and every
|
|
6
6
|
response is validated at runtime against a valibot schema, so a backend contract drift surfaces as
|
|
@@ -95,7 +95,7 @@ Optional on the type, but no default: the backend does not fill it in, and
|
|
|
95
95
|
`new Sodax({ fee })` / `new Sodax({ swaps: { partnerFee } })` only reach the
|
|
96
96
|
`sodax.swaps` orchestrator — not this wire path. Send the same value on quote and
|
|
97
97
|
create-intent. `checkAllowance` / `approve` inherit the field but ignore it.
|
|
98
|
-
Bridge API
|
|
98
|
+
The Bridge API is different: omitted `partnerFee` falls back to `bridgePartnerFee`.
|
|
99
99
|
|
|
100
100
|
## API key
|
|
101
101
|
|
|
@@ -13,6 +13,7 @@ Copy-pasteable patterns for the most common Core SDK consumer tasks. Each file i
|
|
|
13
13
|
| [`testing.md`](testing.md) | Mocking the `Sodax` instance, stubbing the relay layer, `Result<T>` assertions. |
|
|
14
14
|
| [`gas-estimation.md`](gas-estimation.md) | Pre-flight gas estimation for raw-tx flows. |
|
|
15
15
|
| [`backend-server-init.md`](backend-server-init.md) | Node script / bot / partner backend pattern with `declare const` wallet placeholders. |
|
|
16
|
+
| [`manual-submit-tx-with-fallback.md`](manual-submit-tx-with-fallback.md) | Driving the swap steps yourself instead of `swap()`: backend submit-tx + status poll, with the client-side relay fallback `swap()` does internally. |
|
|
16
17
|
|
|
17
18
|
## Cross-references
|
|
18
19
|
|