Skip to content

feat(swap): place CoW swaps through the backend orders API - #3201

Open
mgrabina wants to merge 13 commits into
feat/configurable-backend-urlfrom
swaps-via-backend
Open

mgrabina wants to merge 13 commits into
feat/configurable-backend-urlfrom
swaps-via-backend

Conversation

@mgrabina

@mgrabina mgrabina commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Context: the v3 UI places CoW orders in the browser with cow-sdk. The backend now does it through its v3 orders API. Stacked on #3192.

Now: every CoW swap and position flow quotes and places through the v3 SDK. Leverage on a supplied position comes the same way and replaces #3102 and #3134. ParaSwap stays as the fallback. +2,426 / -3,334, mostly deleted CoW code.

Decisions:

Checked: tsc and eslint clean. weETH/USDC at 2x on localhost against origin staging quotes and asks for the credit delegation signature; a rejection leaves the modal retryable.

No API or DB schema changes.

Merge waits for prod api.v3.aave.com to serve the order ops, every CoW market provisioned, fee parity and the published SDK, which CI needs.

Review in order:

  1. useSwapQuote.ts, useSwapOrderAmounts.ts: backend quotes.
  2. SwapActionsViaBackend.tsx: token market and limit orders.
  3. PositionSwapActionsViaBackend.tsx: position orders and leverage.
  4. LeverageModalContent.tsx, LeverageMultiplierSelector.tsx, LeverageDetails.tsx.
  5. useSwapOrdersTracking.tsx, SwapResultView.tsx, useTransactionHistory.tsx: status via orderStatus.
  6. Skim: deleted *ViaCoW* actions, helpers/cow, generated src/locales/*.

Part of SDK-1119

The swap modals used cow-sdk's WRAPPED_NATIVE_CURRENCIES only to show
wrapped positions with the native symbol and to hide native <-> wrapped
pairs. Read the same tokens from the Aave address book so these modals
no longer depend on cow-sdk, which goes away when swaps move to the
backend. Same chain set as before; on Sepolia the Aave test WETH replaces
canonical WETH9.
Token swaps routed to CoW (market orders and native sells) now quote and
execute through the Aave backend's v3 orders API via the SDK, instead of
talking to CoW from the browser.

- useSwapQuote fetches tokenSwapQuote for token swaps and normalizes it
  into a new BackendRatesType; user slippage is sent as selectedSlippage
  so the executed quote matches the one shown. USD values still come from
  CoW's price feed because the backend leaves wallet legs unpriced.
- SwapActionsViaBackend executes the shown quote with fromQuote through
  useTokenSwapOrder: approvals and permits come from the quote, then the
  order is signed, or sent as a transaction for native sells.
- Order amounts and the costs breakdown read the backend's final amounts
  and costs.
- The result view and the order toasts poll orderStatus for backend order
  ids; position flows keep polling CoW.
- Limit orders and position flows stay on the CoW path for now. The
  eth-flow branch and its helpers lost their last caller and are removed.
Token swap limit orders now go through the same backend action as market
orders. On submit the action asks tokenSwapQuote.limit for the user's
amounts, kind and expiry, then runs the approvals and signs the order
through useTokenSwapOrder. The market quote stays as the price reference
while the limit inputs are open, without a selected slippage.

Native sells stay blocked for limit orders. The native limit guard in the
CoW action is removed because only aToken sellers reach it now.
The backend folds every cost of a quote into the sell token, but the
costs breakdown still showed the partner fee of a sell order in the buy
token and priced the flash-loan fee from CoW's adapter math. For backend
quotes the network, partner and flash-loan fees are now shown and priced
in the sell token, the flash-loan fee comes from the quote's costs, and
the partner fee bps is taken against the sell amount.
…backend

Collateral swaps and withdraw and swap routed to CoW now quote and execute
through the backend's v3 orders API via the SDK, instead of building and
posting CoW orders from the browser.

- useSwapQuote asks supplySwapQuote or withdrawSwapQuote for the user's
  positions, named by the SDK id builders, and normalizes the quote into
  BackendRatesType. Order amounts and costs read the backend's final
  amounts and costs, flash-loan fee included.
- The backend runs every collateral swap on the flash-loan adapter, so
  CoW collateral swaps now always take the flash-loan flow (health factor,
  flash-loan guard and routing list), with or without a low health factor.
- PositionSwapActionsViaBackend places market orders from the quote shown
  and limit orders at the user's price through useSupplySwapOrder and
  useWithdrawSwapOrder; the SDK runs the aToken permit or approval and the
  adapter signature or transaction through one handler.
- A stale quote (the flash-loan fee moved, "quote again") refetches the
  quote and shows a notice instead of a dead end. A market the backend does
  not provision shows that the swap is not available there.
- Adapter-owned orders never show in the CoW owner query, so collateral
  swaps are written to the local swap history under the backend order id,
  polled through orderStatus, and get their explorer link from it. They
  have no cancel until the backend cancel lands. Withdraw and swap orders
  are owned by the user and keep showing through the owner query.
- The result view and toasts read the traded amounts of position orders.
- SwapActionsViaCoW, CollateralSwapActionsViaCoWAdapters and
  WithdrawAndSwapActionsViaCoW lost their last caller and are removed.
…ackend

Debt swaps and repays with collateral routed to CoW now quote and execute
through the backend's v3 orders API via the SDK. With them, no flow builds
or posts CoW orders from the browser any more.

- useSwapQuote asks borrowSwapQuote or repayWithSupplyQuote (REPAY or
  SUPPLY, from the leg the user typed) and flips the quote legs back to the
  UI's orientation, since these orders sell the destination leg.
- PositionSwapActionsViaBackend places them through useBorrowSwapOrder and
  useRepayWithSupplyOrder, market from the quote shown, limit at the
  user's price, and writes them to the local swap history like collateral
  swaps.
- Amounts are always explicit; the backend rejects the max sentinel. A
  full repay or a full debt swap sends the debt balance, and the backend
  adds the same 3 bps interest pad the CoW flows applied when the amount
  is within 10 bps of the whole debt, so the client no longer pads.
- The flash-loan fee comes from the quote, so the on-chain flash borrower
  check and the CoW adapter math are gone.
- Removed without callers: DebtSwapActionsViaCoW,
  RepayWithCollateralActionsViaCoW, the CoW adapter, rates and trading
  helpers, CowProtocolRatesType, useFlashLoanFeeBps, and the hook adapter,
  dust and app-data constants. The CoW order book reads, explorer links,
  adapter factory and cancel helpers stay for orders placed before the
  cutover.
Token swaps catch thrown SDK errors and re-quote on a stale quote, like
position swaps, through one shared handler. A refetched backend quote with
a new id always reaches state, so the order uses the slippage shown. A
permit is skipped while an open order sells the same token. Token quotes
fetch USD prices in parallel, the result view stops its poll on unmount,
local history entries only join the first page, and limit position
previews include the flash-loan fee the backend charges.
@vercel

vercel Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
interface Error Error Nov 27, 2026 5:45pm UTC

Request Review

@mgrabina

Copy link
Copy Markdown
Contributor Author

@codex review

@linear-code

linear-code Bot commented Nov 25, 2026

Copy link
Copy Markdown

SDK-1119

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T17:34:30.473865Z 58fa06e Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 78fcbb5a29

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +540 to +545
const selectedSlippage =
provider === SwapProvider.COW_PROTOCOL &&
state.orderType === OrderType.MARKET &&
state.autoSlippage &&
state.slippage !== state.autoSlippage
? state.slippage

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Allow re-quoting after subsequent custom slippage edits

After a user selects a custom slippage and then changes it again (including returning to Auto), SwapInputs.setSlippage sets quoteRefreshPaused: true because the previous slippage differs from autoSlippage. That disables this quote query, and the quote-to-state effect also discards responses while paused. Previously slippage was applied locally when constructing the order, but the new market-order actions submit only backendQuote.quoteId, so the order still uses the earlier quote's slippage despite the UI showing the new selection. Update the pause behavior for backend quotes so every slippage change obtains and applies a matching quote before submission.

Useful? React with 👍 / 👎.

The backend fixes the slippage inside the quote id, so pausing the refresh
after a second slippage edit left the order on the previous quote.
…n error

The SDK returns AmountTooSmallError, InsufficientLiquidityError and
InsufficientBalanceError as a ValidationError named after the backend type,
which matched no message and fell through to the generic support error.
Map them by type, with the wording aave-pro uses, at quote time and when
the order is placed.
Adds a Leverage flow from the supplied-position menu: the user picks a debt asset and a target
multiplier, the backend quotes the order (range from minMultiplier and maxSafeMultiplier) and
useLeverage places it from the shown quote id. Ports the leverage UI from the in-browser CoW
branch without its CoW code, so every position order now goes through the Aave backend.
…s picked

The first leverage quote is sized at a multiplier the backend picks, only to report the range.
Its amounts, rate, details and warnings now stay hidden until a quote priced at the user's
multiplier arrives, as aave-pro does.
@mgrabina

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 58fa06ef5a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +612 to +614
state.slippage !== state.autoSlippage
? state.slippage
: undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Convert custom slippage to a fraction before requesting a quote

When a user selects custom slippage, state.slippage is a percentage (for example, 0.50 means 0.5%), but this value is passed unchanged through bigDecimal(selectedSlippage) to all three backend quote paths. The response handling uses the opposite convention: quoteToState multiplies selectedSlippage.value by 100 to obtain the UI percentage. Consequently, a 0.5% selection requests 50% slippage, potentially producing an excessively permissive executable quote or a backend rejection. Divide the UI value by 100 before sending it to the backend so custom selections round-trip consistently.

Useful? React with 👍 / 👎.

Comment on lines +285 to +287
const traded = tradedAmountsOf(order.operation);
if (order.__typename === 'OrderFulfilled' && traded) {
onFilled(traded.sell, traded.buy);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle fulfilled leverage orders without traded amounts

For a leverage order, tradedAmountsOf explicitly returns undefined, so even an OrderFulfilled response never enters this success branch. The result modal remains pending and continues polling indefinitely after the leverage has settled, although the background tracker can already report success. Handle fulfillment independently of whether traded amounts are available, and either obtain leverage amounts separately or omit the surplus calculation for that operation.

Useful? React with 👍 / 👎.

@mgrabina
mgrabina marked this pull request as ready for review November 27, 2026 17:31

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 58fa06ef5a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

),
},
}
: { fromQuote: { market, quoteId: quote.quoteId } }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Block submission until the quote matches the edited inputs

After a market quote has loaded, changing the input amount leaves state.swapRate intact while SwapInputs.handleInputChange resets actionsLoading to false. The action remains enabled during both the 400 ms debounce and the subsequent quote request because fetchingData only checks actionsLoading, not ratesLoading or quote/input agreement. Clicking Swap during that window submits the previous quote ID, so reducing the amount can still sell the larger, previously quoted amount. Invalidate the executable quote on input changes and block submission until a matching quote has been applied; the position-order action needs the same protection.

Useful? React with 👍 / 👎.

The result view and history now read a fulfilled leverage's traded amounts (debt sold, collateral
bought), so the modal leaves the pending state. Leverage counts the borrow cap of the debt it
draws, cap and liquidity checks skip the backend's own pre-pick quote, and that quote is not
refetched once it returned a range. The Leverage menu only shows on CoW chains, Sepolia excluded,
and the collateral guard stays mounted until it clears its own block.
…ited amount

After an amount edit the shown quote id still priced the old amount during the debounce and the
re-quote, so a click placed the old amount. Token and position market orders now wait in the
fetching state until the quote for the typed amount is applied.

This branch had an error being deployed

1 failed deployment
Preview — f1b2f584 Deployed Nov 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant