@sodax/skills 2.2.0-rc.6 → 2.2.0-rc.8
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/integration/knowledge/features/auxiliary-services.md +12 -9
- package/skills/sodax-dapp-kit/integration/knowledge/features/bridge.md +3 -0
- package/skills/sodax-dapp-kit/integration/knowledge/features/leverage-yield.md +9 -2
- package/skills/sodax-dapp-kit/integration/knowledge/features/swap.md +2 -1
- package/skills/sodax-dapp-kit/integration/knowledge/recipes/leverage-yield.md +1 -1
- package/skills/sodax-dapp-kit/integration/knowledge/reference/hooks-index.md +4 -2
- package/skills/sodax-dapp-kit/integration/knowledge/reference/querykey-conventions.md +2 -0
- package/skills/sodax-sdk/integration/knowledge/features/bridge.md +4 -0
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield-api.md +12 -7
- package/skills/sodax-sdk/integration/knowledge/features/leverage-yield.md +18 -2
- package/skills/sodax-sdk/integration/knowledge/features/sponsoring.md +3 -1
- package/skills/sodax-sdk/integration/knowledge/features/swap.md +23 -4
- package/skills/sodax-sdk/integration/knowledge/features/swaps-api.md +5 -0
- package/skills/sodax-sdk/integration/knowledge/recipes/README.md +1 -0
- package/skills/sodax-sdk/integration/knowledge/recipes/initialize-sodax.md +1 -1
- package/skills/sodax-sdk/integration/knowledge/recipes/manual-submit-tx-with-fallback.md +184 -0
- package/skills/sodax-sdk/swap/SKILL.md +1 -0
package/package.json
CHANGED
|
@@ -100,7 +100,9 @@ See the `sodax-sdk` skill (integration mode), `swaps-api.md` § `partnerFee`.
|
|
|
100
100
|
|
|
101
101
|
The backend guards `POST /swaps/*` with an API-key check. There is ONE instance-wide key: configure it
|
|
102
102
|
once on the provider config — `<SodaxProvider config={{ apiKey }}>` — and every `sodax.api.*` call these
|
|
103
|
-
hooks make carries it.
|
|
103
|
+
hooks make carries it. `SodaxProvider` runs in the browser, so a key passed there (or read from
|
|
104
|
+
`NEXT_PUBLIC_*` / `VITE_*`) is public. To keep it private, leave `apiKey` out, point `api.baseURL` and
|
|
105
|
+
`solver.solverApiEndpoint` at the app's own backend proxy, and attach the key there: https://docs.sodax.com/developers/how-to/api-key-good-practices. Override per request via the hooks' existing `apiConfig` param
|
|
104
106
|
(`RequestOverrideConfig`), which also accepts `apiKey`:
|
|
105
107
|
|
|
106
108
|
```ts
|
|
@@ -115,9 +117,10 @@ surface with `context.status` `401`/`403` — nothing but a corrected key fixes
|
|
|
115
117
|
terminal in your UI; the transient verification `503` is retried by the wire client. See the
|
|
116
118
|
`sodax-sdk` skill (integration mode), `swaps-api.md` § API key, for the precedence order.
|
|
117
119
|
|
|
118
|
-
Every retrying `useSwapsApi*` hook already handles this: its
|
|
119
|
-
(exported from `@sodax/dapp-kit`), which retries transport
|
|
120
|
-
401/403. `useSwapsApiStatus
|
|
120
|
+
Every retrying `useSwapsApi*`, `useLeverageYieldApi*` and `useBridgeApi*` hook already handles this: its
|
|
121
|
+
default `retry` is `retryUnlessAuthFailure` (exported from `@sodax/dapp-kit`), which retries transport
|
|
122
|
+
blips up to 3 times but never replays a 401/403. `useSwapsApiStatus`, `useSwapsApiSubmitTxStatus`,
|
|
123
|
+
`useLeverageYieldApiSubmitTxStatus` and `useBridgeApiSubmitTxStatus` additionally stop their 1s poll on a
|
|
121
124
|
rejected key, instead of re-requesting forever. So an invalid key surfaces once, fast, on `error`.
|
|
122
125
|
|
|
123
126
|
Override or compose it through `queryOptions` / `mutationOptions` when you want different behaviour:
|
|
@@ -172,7 +175,7 @@ const { mutateAsync: submitBridgeTx } = useBridgeApiSubmitTx();
|
|
|
172
175
|
await submitBridgeTx({ request, apiConfig: { baseURL: 'https://...' } });
|
|
173
176
|
```
|
|
174
177
|
|
|
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.
|
|
178
|
+
`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
179
|
|
|
177
180
|
> 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
181
|
|
|
@@ -428,10 +431,10 @@ rather than on the HTTP status.
|
|
|
428
431
|
When the server rate-limits a key it also supplies `error.context.retryAfterSeconds`; render "try again
|
|
429
432
|
in Ns" instead of a generic "try later". The SDK never auto-retries a rate limit.
|
|
430
433
|
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
434
|
+
Sponsoring needs its own sponsoring-specific key, issued by the SODAX team — a partner portal key is
|
|
435
|
+
rejected there. Set it on `api.sponsoringApiConfig.apiKey`; it wins wherever the slice points. Without it,
|
|
436
|
+
the instance-wide key from `<SodaxProvider config={{ apiKey }}>` is sent to sponsoring whenever the call
|
|
437
|
+
targets a SODAX gateway root, and a portal key sent there fails. An api key
|
|
435
438
|
in a browser bundle is public by nature; the service's per-key quotas, fleet cap, per-IP throttle,
|
|
436
439
|
and origin gating are the real controls. Proxy through your own backend if that is not acceptable.
|
|
437
440
|
|
|
@@ -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
|
```
|
|
@@ -17,6 +17,7 @@ useLeverageYieldVaultSwap({ mutationOptions }); // EXECUTE the built payload en
|
|
|
17
17
|
useLeverageYieldNotifySolver({ mutationOptions }); // manual-flow: notify the solver after a self-driven relay
|
|
18
18
|
|
|
19
19
|
// Reads
|
|
20
|
+
useLeverageYieldDetailedStatus({ params, queryOptions }); // track a vault swap from its SOURCE tx (3s)
|
|
20
21
|
useLeverageYieldQuote({ params, queryOptions }); // vault deposit/withdraw quote (3s) — NOT useQuote
|
|
21
22
|
useLeverageYieldEffectiveApr({ params, queryOptions }); // AAVE + LSD effective net APR (60s)
|
|
22
23
|
useLeverageYieldPosition({ params, queryOptions }); // collateral/debt/ltv/healthFactor/idle (30s)
|
|
@@ -25,7 +26,7 @@ useLeverageYieldPreviewRedeem({ params, queryOptions }); // assets for N shares;
|
|
|
25
26
|
useLeverageYieldShareBalances({ params, queryOptions }); // per-chain share balances via useQueries (15s)
|
|
26
27
|
```
|
|
27
28
|
|
|
28
|
-
`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).
|
|
29
30
|
|
|
30
31
|
`use*Approve` is unchanged and still resolves to one transaction hash, but the SDK may send **two**
|
|
31
32
|
transactions on a token that rejects a non-zero to non-zero allowance change (Ethereum USDT today) —
|
|
@@ -93,13 +94,19 @@ Leverage-yield has **no dedicated approve hook**. A deposit is a swap-style inte
|
|
|
93
94
|
|
|
94
95
|
## Return shapes
|
|
95
96
|
|
|
96
|
-
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.
|
|
97
103
|
|
|
98
104
|
| Hook | Returns |
|
|
99
105
|
|---|---|
|
|
100
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`) |
|
|
101
107
|
| `useLeverageYieldDeposit` / `useLeverageYieldWithdraw` | `SafeUseMutationResult<LeverageYieldSwapPayload, Error, …>` (builder — `data` is the payload to spread into `useLeverageYieldVaultSwap`) |
|
|
102
108
|
| `useLeverageYieldVaultSwap` | `SafeUseMutationResult<VaultSwapResponse, Error, …>` (`{ solverExecutionResponse, intent, intentDeliveryInfo }`) |
|
|
109
|
+
| `useLeverageYieldDetailedStatus` | `UseQueryResult<Result<DetailedLeverageYieldStatus, LeverageYieldDetailedStatusError> \| undefined>` — Result-wrapped, narrow the value on `source` (`'backend'` \| `'solver'`) |
|
|
103
110
|
| `useLeverageYieldNotifySolver` | `SafeUseMutationResult<SolverExecutionResponse, Error, …>` (`{ answer: 'OK', intent_hash }`) |
|
|
104
111
|
| `useLeverageYieldEffectiveApr` | `UseQueryResult<LeverageYieldEffectiveApr, Error>` |
|
|
105
112
|
| `useLeverageYieldPosition` | `UseQueryResult<LeverageYieldPosition, Error>` |
|
|
@@ -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
|
|
|
@@ -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
|
|
@@ -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) |
|
|
@@ -225,7 +227,7 @@ Typed React Query wrappers over the backend Bridge API (`sodax.api.bridge.*`). D
|
|
|
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) |
|
|
@@ -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'
|
|
@@ -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:
|
|
@@ -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
|
|
|
@@ -6,7 +6,7 @@ Access: `sodax.leverageYield`. Service class: `LeverageYieldService`. Feature ta
|
|
|
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
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).
|
|
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 } })`.
|
|
10
10
|
|
|
11
11
|
## How it works
|
|
12
12
|
|
|
@@ -34,6 +34,12 @@ sodax.leverageYield.vaultSwap<K>(params: VaultSwapActionParams<K, false>): Promi
|
|
|
34
34
|
sodax.leverageYield.notifySolver(request: { intent_tx_hash: string }): Promise<Result<SolverExecutionResponse, SodaxError>>;
|
|
35
35
|
// notifySolver is PUBLIC — call it to finish a manual createVaultIntent → relay → notify flow
|
|
36
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
|
+
|
|
37
43
|
// Sonic-direct allowance for the vault's underlying asset (the swap-style deposit handles its own approvals)
|
|
38
44
|
sodax.leverageYield.approve<R>(params: LeverageYieldApproveParams<R>): Promise<Result<TxReturnType<HubChainKey, R>, SodaxError>>;
|
|
39
45
|
sodax.leverageYield.isAllowanceValid(params: LeverageYieldAllowanceParams): Promise<Result<boolean, SodaxError>>;
|
|
@@ -90,10 +96,20 @@ type LeverageYieldSwapWithdrawParams = {
|
|
|
90
96
|
|
|
91
97
|
// The execute-mode wrapper (createVaultIntent / vaultSwap). The two vault execution modifiers
|
|
92
98
|
// live HERE, never on the generic swap surface:
|
|
93
|
-
type VaultSwapActionParams<K, Raw> = SpokeExecActionParams<K, Raw, CreateIntentParams<K
|
|
99
|
+
type VaultSwapActionParams<K, Raw> = SpokeExecActionParams<K, Raw, CreateIntentParams<K>, LeverageYieldExtras> & {
|
|
94
100
|
hubWalletSwap?: boolean; // withdraw: inputToken is hub-wallet lsoda*, authorise via Connection.sendMessage
|
|
95
101
|
partnerFee?: PartnerFee; // beats config.leverageYield.partnerFee for this intent only
|
|
96
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.
|
|
97
113
|
```
|
|
98
114
|
|
|
99
115
|
## Common call shapes
|
|
@@ -152,13 +152,15 @@ routes at its bare origin is reached with `baseURL: 'http://localhost:3011'`.
|
|
|
152
152
|
|
|
153
153
|
`apiKey` is folded into `x-api-key`. An api key in a browser bundle is public by nature: the service's
|
|
154
154
|
per-key quotas, fleet-wide daily cap, per-IP throttle, and origin gating are the real controls. Proxy
|
|
155
|
-
through your own backend if that is not acceptable.
|
|
155
|
+
through your own backend if that is not acceptable: https://docs.sodax.com/developers/how-to/api-key-good-practices.
|
|
156
156
|
|
|
157
157
|
The instance-wide `new Sodax({ apiKey })` is **gated** here, unlike every other backend service: it is
|
|
158
158
|
inherited only when the call targets a SODAX gateway (the packaged sponsoring default or the resolved
|
|
159
159
|
shared root), and the check runs per request against the effective target, so a per-call `baseURL`
|
|
160
160
|
override cannot carry it off-gateway. A custom sponsoring origin never receives it. The slice `apiKey`
|
|
161
161
|
above is the credential for independently hosted sponsoring and wins wherever the slice points.
|
|
162
|
+
Sponsoring keys come from their own registry (issued by the SODAX team, not the partner portal), so a
|
|
163
|
+
portal key that reaches sponsoring through inheritance is rejected — always set the slice `apiKey`.
|
|
162
164
|
|
|
163
165
|
## Cross-references
|
|
164
166
|
|
|
@@ -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".
|
|
@@ -107,9 +107,14 @@ instance-wide key, `new Sodax({ apiKey })`, sent on every backend request — th
|
|
|
107
107
|
`RequestOverrideConfig`:
|
|
108
108
|
|
|
109
109
|
```ts
|
|
110
|
+
// Server-side only — a key in a browser bundle is public
|
|
110
111
|
await sodax.api.swaps.createIntent(body, { apiKey: 'per-request-key' });
|
|
111
112
|
```
|
|
112
113
|
|
|
114
|
+
The key belongs on a server. Never read it from `NEXT_PUBLIC_*` / `VITE_*` / `REACT_APP_*` — those are
|
|
115
|
+
inlined into the client bundle. When the SDK runs in a browser, point `api.baseURL` and
|
|
116
|
+
`solver.solverApiEndpoint` at the app's own backend proxy and attach the key there: https://docs.sodax.com/developers/how-to/api-key-good-practices.
|
|
117
|
+
|
|
113
118
|
Precedence, highest first: per-call `headers['x-api-key']` (any casing) → per-call `apiKey` → a
|
|
114
119
|
configured explicit `x-api-key` header (`api.headers` / `setHeaders`) → the configured `apiKey`. That
|
|
115
120
|
full order is what the data, swaps, and bridge transports resolve; sponsoring's tier 3 is its own
|
|
@@ -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
|
|
|
@@ -18,7 +18,7 @@ const result = sodax.config.isValidSpokeChainKey(ChainKeys.ARBITRUM_MAINNET);
|
|
|
18
18
|
import { Sodax, ChainKeys, type SodaxOptions } from '@sodax/sdk';
|
|
19
19
|
|
|
20
20
|
// `SodaxOptions` = `DeepPartial<SodaxDefaultConfig>` (the data override) plus the client-side options:
|
|
21
|
-
// `logger`, the global `fee`, the global `apiKey` (one instance-wide key, sent as `x-api-key` on every backend request; override per request via `RequestOverrideConfig.apiKey
|
|
21
|
+
// `logger`, the global `fee`, the global `apiKey` (one instance-wide key, sent as `x-api-key` on every backend request; override per request via `RequestOverrideConfig.apiKey`; server-side only — in a browser, proxy instead, see https://docs.sodax.com/developers/how-to/api-key-good-practices), and per-feature options on `swaps` / `bridge` (e.g. `{ useBackendSubmitTx: false }` — opt out of the default-on backend 2-step flow).
|
|
22
22
|
const config: SodaxOptions = {
|
|
23
23
|
// Per-chain overrides — merged with packaged defaults at the field level.
|
|
24
24
|
chains: {
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# Manual submit-tx with client-side fallback
|
|
2
|
+
|
|
3
|
+
`sodax.swaps.swap()` already does this internally: it creates the intent, tries the backend submit-tx path, and on **any** non-success falls back to the client-side relay. Prefer `swap()` unless the consumer must own each step (a bot that persists every transition, a backend with its own signing boundary, a UI that reports phases).
|
|
4
|
+
|
|
5
|
+
When they do own the steps, reproduce **both** paths. The orchestration helpers behind `swap()` are package-internal — `SwapService.submitTx` and `SwapService.fallbackSwapSteps` are private, and the attempt budget and poll loop are not exported — so the loop is hand-written from the public pieces below.
|
|
6
|
+
|
|
7
|
+
Bindings shared by every step below:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import type { IEvmWalletProvider, SpokeChainKey } from '@sodax/sdk';
|
|
11
|
+
|
|
12
|
+
declare const evmWallet: IEvmWalletProvider;
|
|
13
|
+
declare const srcChainKey: SpokeChainKey; // === params.srcChainKey
|
|
14
|
+
declare const timeoutMs: number; // per-attempt budget, e.g. DEFAULT_RELAY_TX_TIMEOUT
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## 1. Create the intent, keep all three values
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
const created = await sodax.swaps.createIntent({ params, walletProvider: evmWallet });
|
|
21
|
+
if (!created.ok) return created;
|
|
22
|
+
|
|
23
|
+
const { tx: spokeTxHash, intent, relayData } = created.value;
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## 2. Build the request
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import type { SubmitTxRequestV2 } from '@sodax/sdk';
|
|
30
|
+
|
|
31
|
+
const request: SubmitTxRequestV2 = {
|
|
32
|
+
txHash: spokeTxHash as string,
|
|
33
|
+
srcChainKey: params.srcChainKey,
|
|
34
|
+
walletAddress: params.srcAddress, // the SOURCE address that signed, not the destination
|
|
35
|
+
intent, // passes straight through from createIntent
|
|
36
|
+
relayData: relayData.payload, // the hex STRING, not the { address, payload } object
|
|
37
|
+
};
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Persist `request` **before** submitting. Re-submitting the same `(txHash, srcChainKey)` is idempotent (`data.status: 'duplicate'`); never sign a second deposit to recover.
|
|
41
|
+
|
|
42
|
+
`request.intent` carries `bigint` fields (`intentId`, `inputAmount`, `minOutputAmount`, `deadline`, `srcChain`, `dstChain`), so plain `JSON.stringify(request)` THROWS — in the exact crash window this step exists to survive. Serialize them, and coerce them back on resume:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
const serialized = JSON.stringify(request, (_k, v) => (typeof v === 'bigint' ? v.toString() : v));
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Passing `intent` straight to `submitTx` still needs no conversion — the wire client serializes internally. Only your own storage does.
|
|
49
|
+
|
|
50
|
+
## 3. Open the attempt budget, then submit
|
|
51
|
+
|
|
52
|
+
The attempt starts **before** the POST — the submit draws on the same budget as the poll, so a stalled POST costs the attempt instead of silently extending it. Cap every request at the budget left, never above the service's own timeout.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const serviceTimeoutMs = sodax.api.swaps.getTimeout();
|
|
56
|
+
const attemptDeadline = Date.now() + timeoutMs;
|
|
57
|
+
|
|
58
|
+
const remaining = () => Math.max(0, attemptDeadline - Date.now());
|
|
59
|
+
const requestTimeout = (): number | null => {
|
|
60
|
+
const capped = Math.min(remaining(), serviceTimeoutMs);
|
|
61
|
+
return capped > 0 ? capped : null; // null → issue no request at all
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const submitBudget = requestTimeout();
|
|
65
|
+
if (submitBudget === null) return fallback();
|
|
66
|
+
|
|
67
|
+
const submitted = await sodax.api.swaps.submitTx(request, { timeout: submitBudget });
|
|
68
|
+
|
|
69
|
+
// Two distinct arms — the reason lives in a different place on each.
|
|
70
|
+
if (!submitted.ok) return fallback(); // transport: submitted.error.code
|
|
71
|
+
if (!submitted.value.success) return fallback(); // 200 not queued: submitted.value.data.message
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Do **not** call `verifyTxHash` before this. The backend verifies itself, so a client-side confirmation wait only delays every backend success. Verification belongs to the fallback.
|
|
75
|
+
|
|
76
|
+
## 4. Poll until `solved`
|
|
77
|
+
|
|
78
|
+
Same budget, same cap per request, and no sleep the attempt cannot outlast — that wait only delays the fallback.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import { isAuthFailure } from '@sodax/sdk';
|
|
82
|
+
import type { Result, SubmitTxStatusQueryV2, SwapResponse } from '@sodax/sdk';
|
|
83
|
+
|
|
84
|
+
const query: SubmitTxStatusQueryV2 = { txHash: spokeTxHash as string, srcChainKey };
|
|
85
|
+
const intervalMs = 1_000;
|
|
86
|
+
|
|
87
|
+
for (let budget = requestTimeout(); budget !== null; budget = requestTimeout()) {
|
|
88
|
+
const snapshot = await sodax.api.swaps.getSubmitTxStatus(query, { timeout: budget });
|
|
89
|
+
|
|
90
|
+
if (snapshot.ok) {
|
|
91
|
+
const { status, result, abandonedAt } = snapshot.value.data;
|
|
92
|
+
// Terminal success needs BOTH fields.
|
|
93
|
+
if (status === 'solved' && result?.dstIntentTxHash && result.intent_hash) {
|
|
94
|
+
const value: SwapResponse = {
|
|
95
|
+
solverExecutionResponse: { answer: 'OK', intent_hash: result.intent_hash as `0x${string}` },
|
|
96
|
+
intent,
|
|
97
|
+
intentDeliveryInfo: {
|
|
98
|
+
srcChainKey,
|
|
99
|
+
srcTxHash: spokeTxHash as string,
|
|
100
|
+
srcAddress: params.srcAddress,
|
|
101
|
+
dstChainKey: params.dstChainKey,
|
|
102
|
+
dstTxHash: result.dstIntentTxHash,
|
|
103
|
+
dstAddress: params.dstAddress,
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
return { ok: true, value } satisfies Result<SwapResponse>;
|
|
107
|
+
}
|
|
108
|
+
if (status === 'failed' || abandonedAt) break; // terminal failure
|
|
109
|
+
// pending | relaying | relayed | posting_execution | posted_execution → keep polling
|
|
110
|
+
} else if (isAuthFailure(snapshot.error)) {
|
|
111
|
+
break; // a rejected API key cannot become success by waiting
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (remaining() <= intervalMs) break;
|
|
115
|
+
await new Promise(r => setTimeout(r, intervalMs));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return fallback(); // every exit other than `solved` is a non-success
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## 5. Fallback — the client-side relay
|
|
122
|
+
|
|
123
|
+
Returns the **same** `SwapResponse` as the backend path, so callers handle completion through one contract whichever path ran — as `swap()` does.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { relayTxAndWaitPacket, RELAY_FALLBACK_FLOOR_MS, isHubChainKeyType } from '@sodax/sdk';
|
|
127
|
+
import type { Result, SwapResponse } from '@sodax/sdk';
|
|
128
|
+
|
|
129
|
+
async function fallback(): Promise<Result<SwapResponse>> {
|
|
130
|
+
const verified = await sodax.spoke.verifyTxHash({ txHash: spokeTxHash as string, chainKey: srcChainKey });
|
|
131
|
+
if (!verified.ok) return verified;
|
|
132
|
+
|
|
133
|
+
let hubTxHash: string;
|
|
134
|
+
if (isHubChainKeyType(srcChainKey)) {
|
|
135
|
+
hubTxHash = spokeTxHash as string; // source IS the hub — nothing to relay
|
|
136
|
+
} else {
|
|
137
|
+
const packet = await relayTxAndWaitPacket({
|
|
138
|
+
srcTxHash: spokeTxHash as string,
|
|
139
|
+
data: relayData, // the OBJECT here, not the payload string
|
|
140
|
+
chainKey: srcChainKey,
|
|
141
|
+
relayerApiEndpoint: sodax.swaps.relayerApiEndpoint,
|
|
142
|
+
timeout: Math.max(timeoutMs, RELAY_FALLBACK_FLOOR_MS), // a FRESH budget
|
|
143
|
+
});
|
|
144
|
+
if (!packet.ok) return packet;
|
|
145
|
+
hubTxHash = packet.value.dst_tx_hash;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const posted = await sodax.swaps.postExecution({ intent_tx_hash: hubTxHash as `0x${string}` });
|
|
149
|
+
if (!posted.ok) return posted;
|
|
150
|
+
|
|
151
|
+
return {
|
|
152
|
+
ok: true,
|
|
153
|
+
value: {
|
|
154
|
+
solverExecutionResponse: posted.value,
|
|
155
|
+
intent,
|
|
156
|
+
intentDeliveryInfo: {
|
|
157
|
+
srcChainKey,
|
|
158
|
+
srcTxHash: spokeTxHash as string,
|
|
159
|
+
srcAddress: params.srcAddress,
|
|
160
|
+
dstChainKey: params.dstChainKey,
|
|
161
|
+
dstTxHash: hubTxHash,
|
|
162
|
+
dstAddress: params.dstAddress,
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Rules
|
|
170
|
+
|
|
171
|
+
- **Two budgets, never one.** The backend attempt gets a timeout; the fallback relay gets a *fresh* one. A single shared deadline leaves the fallback only what the backend did not spend — that is how a relay that needs longer ends in a timeout.
|
|
172
|
+
- **Falling back is safe.** Re-relaying and re-posting an already-processed swap is idempotent: the relay deduplicates and returns the existing `executed` packet, and the solver re-affirms the intent rather than filling twice. It is also load-bearing — the backend keeps processing after the poll gives up, so the two relays can race.
|
|
173
|
+
- **Solana / Bitcoin need the exact `relayData` bytes** — those deposits commit only a hash of the payload on-chain. If the runtime value is gone, recover it with `sodax.swaps.getIntentSubmitTxExtraData({ txHash })`, where `txHash` is the **hub-chain** tx hash (it reads the intent off the hub) — not the source-chain `spokeTxHash` used elsewhere here. From an `Intent` you already hold, `sodax.swaps.reconstructRelayData(intent)` derives the same bytes offline.
|
|
174
|
+
- **Read status with `getDetailedStatus`**, which routes between the backend record and the solver — do not hand-roll that fallback too.
|
|
175
|
+
- Opting out entirely is a config flag, not hand-written code: `new Sodax({ swaps: { useBackendSubmitTx: false } })` makes `swap()` take the client-side path only.
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## Cross-references
|
|
180
|
+
|
|
181
|
+
- [`README.md`](README.md) — recipe index.
|
|
182
|
+
- [`../features/swap.md`](../features/swap.md) — `SwapService` surface, action params, error codes.
|
|
183
|
+
- [`result-and-errors.md`](result-and-errors.md) — branching on `result.ok` and `(feature, code)`.
|
|
184
|
+
- [`backend-server-init.md`](backend-server-init.md) — bot / partner-backend setup around this flow.
|
|
@@ -23,6 +23,7 @@ Swap has materially different code paths depending on the answers. Don't skip:
|
|
|
23
23
|
- Unsigned → `raw: true`, you handle relay yourself.
|
|
24
24
|
3. **One-shot `swap()` or step-by-step (`createIntent` → backend submit → `postExecution`)?**
|
|
25
25
|
- One-shot is the default for frontends. Step-by-step is for backends that already have a relay/orchestration layer.
|
|
26
|
+
- Step-by-step code must reproduce BOTH paths `swap()` runs internally — the backend submit-tx attempt *and* the client-side relay fallback on any non-success. The helpers behind `swap()` are package-internal, so the loop is hand-written: [`../integration/knowledge/recipes/manual-submit-tx-with-fallback.md`](../integration/knowledge/recipes/manual-submit-tx-with-fallback.md).
|
|
26
27
|
4. **Market order or limit order?** Limit orders use a different params shape — `deadline` becomes optional (forced to `0n` internally), not required.
|
|
27
28
|
|
|
28
29
|
## Integration workflow (writing new v2 swap code)
|