Skip to content

Swap: Feat - Rango Exchange cross-chain swaps - #2462

Draft
JohnathanWhite wants to merge 13 commits into
bitpay:developfrom
JohnathanWhite:feat/swap-rango
Draft

JohnathanWhite wants to merge 13 commits into
bitpay:developfrom
JohnathanWhite:feat/swap-rango

Conversation

@JohnathanWhite

@JohnathanWhite JohnathanWhite commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Draft — not ready to merge. Requires the BWS side: bitpay/bitcore#4272. Neither PR does anything alone.

Execution is implemented and verified end-to-end on mainnet. It ships behind a single flag, RANGO_EXECUTION_ENABLED, currently false — flip it once a production Rango API key is provisioned.

Why

Swap is currently a single-vendor, fully custodial product. Production config has thorswap: {disabled: true, removed: true}, leaving Changelly as the only live route — and Changelly classic takes custody for the duration of every swap. Thorswap was the only genuinely non-custodial, cross-chain path we had.

Rango returns unsigned transactions the wallet signs itself — the same trust model Thorswap had, on broader coverage.

Verified on mainnet

A real cross-chain swap settled through this code: 52.51 USDC on Arbitrum → SOL on Solana.

0x7e59d90642b0f358badf0356befaa004980c43bd3292306f082d300ff816319a

That transaction calls RangoDiamond directly and confirms the parts that could not be tested any other way: createTxProposal accepts a Rango proposal, the ERC20 approval clears, and the swap is signed and broadcast through the existing publishAndSign path with no provider-specific signing code.

Tested against a local BWS with Rango's documented public test key, with the device's real wallets served from production — a split proxy routes only /v1/service/rango/* locally so the integration runs against real funds without a staging environment.

What is here

rango.models.ts Typed Basic API surface, including the transaction shapes the wallet can sign
effects/rango/rango.ts BWS-proxied calls; report-failure is best-effort and never surfaces to the user
rango-tx.ts Pure proposal builder — no React, no wallet state, so the part that decides where funds go is directly testable
rango-checkout.effects.ts Checkout orchestration; deliberately stops short of signing
rango-utils.ts Chain-code mapping, asset notation, route usability, status colours
store slice Order history, actions, reducer
RangoSettings.tsx / RangoDetails.tsx History list and order detail, with pull-to-refresh

The signable transaction types map onto plumbing this app already has:

  • EVM — contract call plus optional ERC20 approval → SwapCryptoApproveErc20 already handles this shape
  • TRANSFER — UTXO send with the memo written as an OP_RETURN output → the exact pattern the Thorswap integration shipped

That reuse is most of the argument for Rango over rebuilding: the hard parts were already solved and dormant.

Solana is a destination, not a source

The mainnet swap above delivers to Solana, and that works. Solana as a source does not: Rango returns a pre-serialised Solana transaction the BWS proposal pipeline has no way to carry.

Rango's support is therefore asymmetric, and the gate is on the source side only (isPairSupported). Offering a SOL-source quote would produce a route that always fails at checkout. XRP is omitted entirely for the same reason — Rango supports XRPL, but it returns a transaction type we do not sign.

The response is not trusted

Rango decides where funds go and how many move. Nothing downstream re-checked that against the confirm screen, so the builder now takes the authorisation — source amount, sending address, expected chain — as a required argument. A new call site that forgets it is a compile error, not a silent gap.

Refused rather than turned into a signable proposal:

  • a native value or UTXO deposit above the authorised amount
  • a transaction built for another chain (the proposal is forced onto the wallet's chain regardless of what the response says, so an ETH transaction returned for a Polygon wallet would be broadcast on Polygon)
  • a transaction built for another sending address
  • approval calldata that is not approve(address,uint256), is aimed at a contract other than the token being swapped, or would grant an allowance larger than the swap

That last one matters past the swap: an allowance survives the route being abandoned.

The ERC20 spender is read from the calldata, not from approveTo. approveTo is the token contract the approve call is sent to; the address being granted the allowance is the first argument inside the call. Checking approveTo against ERC20_SPENDER_APPROVAL_WHITELIST checks the token, not who can spend — so the verified badge could never have matched.

Memo encoding must be stated. An absent memoType used to mean UTF8, which writes a hex memo as its ASCII characters: the vault is paid, the swap cannot be attributed, and the funds are not recoverable.

Rate protection

/basic/swap re-quotes, so the guaranteed minimum can come back below the one on the confirm screen. acceptedOutputAmountMin is already the slippage-protected floor, so it is compared directly — subtracting slippage from it again would permit delivery below the figure the user was shown.

A lower minimum is put to the user rather than silently accepted or silently aborted, and a missing or unparseable minimum fails closed.

Upgrade safety

redux-persist is configured with autoMergeLevel2, so the new rango slice is taken from initialState when a user's persisted SWAP_CRYPTO blob predates it. No migration needed, and no Object.values(undefined) crash on existing installs — the usual way a new state slice breaks upgrades.

Verification

  • 79 tests across the Rango suites, covering the memo encodings, exact-amount arithmetic past MAX_SAFE_INTEGER, every refusal above, and the checkout orchestration
  • Full app suite: 3089 passing, 2 skipped, 0 failing
  • tsc --noEmit: zero new errors, confirmed by diffing the full error set against baseline
  • prettier and eslint clean on new files

Review notes

  • Rango returns HTTP 200 with an error field for business failures — rangoIsRouteUsable() exists because a successful call is not a successful quote
  • EVM values are kept as exact decimal strings. A wei value routinely exceeds Number.MAX_SAFE_INTEGER, where 0x3635c9adc5dea00001 parses to 1e21 and loses its last digit, and JSON.stringify emits '1e+21', which BWS cannot read
  • RANGO_SUPPORTED_BLOCKCHAINS is deduped: both matic and pol map to POLYGON
  • Adding a provider currently requires touching five separate registration points plus the RBF exclusion list and the history navigation switch, none of which fail at compile time. Each was found by enabling the feature and watching something not happen. A Record<SwapCryptoExchangeKey, …> over the provider maps would make the next one a type error — worth doing, but out of scope here
  • The icon is the official mark from rango-exchange/assets (branding/icons/icon.svg), the same repo Rango's API serves swapper logos from. Path data and all 15 gradient stops transcribed verbatim and diff-verified. Two conversion fixes: dropped a trailing <rect stroke="#070707"> Illustrator artboard artifact that would have drawn a visible border, and namespaced the gradient ids, since the export ships SVGID_1_ and ThorswapLogo already defines that id — both render in the same offer list

Jira: RN-3108

Adds the app side of a Rango Exchange swap integration, behind a gate.
Rango is a cross-chain aggregator that returns unsigned transactions the
wallet signs itself, so it restores the non-custodial swap path the app
lost when Thorswap was removed. Changelly, the only live provider today,
takes custody for the duration of every swap.

This change stops at the data layer. The offer is registered but hidden,
and no swap can be executed yet — signing and broadcast land next.

What is here:
- rango.models.ts   typed Basic API surface, including the three
                    transaction shapes the wallet can sign: EVM (contract
                    call plus optional ERC20 approval), TRANSFER (UTXO
                    send with the memo as an OP_RETURN output) and SOLANA
- effects/rango     BWS-proxied calls; report-failure is best effort and
                    never surfaces to the user
- rango-utils.ts    BitPay chain code <-> Rango blockchain name mapping,
                    asset notation, route usability checks
- store slice       rango order history, actions and reducer
- RangoSettings     order history screen; rows are not tappable until the
                    detail screen lands with execution

Chain mapping verified against GET /basic/meta/blockchains: Rango covers
all 11 chains the wallet custodies. XRP is deliberately omitted from the
map — Rango supports XRPL, but returns an XRPL transaction type we do not
sign yet, and a route we cannot sign is worse than no route.

isCoinSupportedToSwap deliberately does not consult Rango yet. That
function gates the Swap entry point, so including a provider that cannot
execute would advertise a swap the user cannot finish.

Existing installs are safe: redux-persist uses autoMergeLevel2, so the
new rango slice is taken from initialState when the persisted blob
predates it. No migration needed.

Still open before this can be enabled: Rango generates the ERC20 approval
spender per quote for some bridges, which does not compose with the
static whitelist behind the verified contract badge in
SwapCryptoApproveErc20. That needs a security decision, not a code fix.
Replaces the hand-drawn placeholder with the official mark from
rango-exchange/assets (branding/icons/icon.svg), which is the same
repository Rango's own API serves swapper logos from.

Path data and all 15 gradient stops are transcribed verbatim; verified by
normalising whitespace and diffing against the source.

Two changes were needed for the conversion:

- Dropped the trailing <rect stroke="#070707"> — an Illustrator artboard
  artifact that would have drawn a visible border around the icon.
- Namespaced the gradient ids to rangoGrad1..3. The export ships them as
  SVGID_1_ and friends, and ThorswapLogo already defines SVGID_1_; both
  logos render in the same offer list, where duplicate ids collide.

The mark carries its own white disc so it reads on both light and dark
grounds, which is why this takes no theme prop.
Adds the layer between a Rango route and a signable transaction, plus
fixes for several problems found reviewing the first pass.

rango-tx.ts builds BitPay transaction proposals from Rango's unsigned
transactions. It is free of React and wallet state so the mapping can be
tested directly — this is where a mistake silently sends funds to the
wrong place. 37 tests cover it, using fixtures taken verbatim from live
/basic/swap responses so they fail if Rango changes a shape, not only if
we change code.

  EVM      contract call carrying Rango's calldata, with the per-quote
           ERC20 spender read from the response rather than cached
  TRANSFER send to the deposit address plus an OP_RETURN carrying the memo

Two things the live API does that the docs do not spell out:

memoType is route-dependent on the same pair. Thorchain returns UTF8 text
('=:e:0x...'); TeleSwap returns SCRIPT, where memo is already a complete
output script ('6a4c4d...'). Wrapping a SCRIPT memo in a second OP_RETURN
produces a deposit the destination network cannot attribute, and the funds
are not recoverable. The builder now uses SCRIPT memos verbatim, wraps
text ones, and refuses an unrecognised memoType rather than guessing.

tx.amount is already net of Rango's fee — a swap requested for 5000000
sat returns 4995000. Sending the requested figure overpays the route.

Amounts convert with string arithmetic. (0.1).toFixed(18) is
'0.100000000000000006', so the obvious conversion reintroduces exactly the
float error it is meant to avoid; a test covers it.

Review fixes:
- The reducer had no cases for the Rango actions, so saving an order was
  a silent no-op and history would always have been empty.
- showOffer:false was not a gate. The offer selector recomputes showOffer
  for every exchange in SwapCryptoSupportedExchanges and overwrote it, so
  a Rango card rendered for native-to-native pairs. Replaced with an
  explicit RANGO_EXECUTION_ENABLED flag checked after that loop.
- isCoinSupportedByRango treated coin === chain as "native", which is
  false for ETH on Arbitrum and for POL on the chain we call matic. It no
  longer claims support without the live token list.
- getRangoAsset emitted ETH.USDC for a token with no contract address,
  which Rango rejects as "Incorrect native token".
- Dropped a helper whose coin_chain keys did not match the convention the
  rest of the swap module uses; it had no callers and would have been
  wrong once wired.
- Rango's support URL 404s; points at the docs site instead.

Solana stays excluded alongside XRP: Rango returns a pre-serialised
Solana transaction and the BWS proposal pipeline has no way to carry one.
EVM values were parsed to a JS Number, which breaks twice for wei:

  0x3635c9adc5dea00001 (1e21 + 1) parses to 1e21 — the last digit is
  silently dropped, so the user would sign a different amount than the
  one Rango quoted.

  JSON.stringify(1e21) is '1e+21', so the amount reaches BWS in
  exponential notation rather than as digits. This is the same problem
  parseAmountToStringIfBN exists to solve in the Changelly, Moonpay-sell
  and Ramp-sell checkouts.

Amounts now convert through BigInt to an exact decimal string, on both
the EVM and UTXO paths. gasLimit stays a Number — gas limits are ~1e6,
well inside the safe range.

Two regression tests cover it: one asserts the extra wei survives, the
other asserts no serialised field matches /e\+/.
Second review pass. The first finding is a fund-loss bug on the route
Rango is serving right now.

HEX memos decoded to nothing. Buffer.from(str, 'hex') does not throw on
bad input — it stops at the first invalid character, so '0xdead' decodes
to zero bytes and buildDataOut returns the empty OP_RETURN '6a00'. That
passed the old startsWith('6a') check and passes BWS validation, so the
deposit would go to the vault carrying no memo and be unrecoverable. Odd
length truncates the same way: 'abc' decodes to one byte. This matters
today: BTC->ETH currently routes through Chainflip with memoType HEX, and
the SCRIPT branch already strips a '0x' prefix that the HEX branch did
not. Hex is now validated, the 0x prefix accepted, and the decoded byte
count asserted against the input.

Memo scripts are validated properly rather than by prefix. Parsed with
the chain's Script.fromHex and required to be isDataOut() with a declared
push length matching the bytes present — a script declaring OP_PUSHDATA1
77 bytes while carrying 37 parses leniently in bitcore, signs fine, and
is then rejected at broadcast as non-standard, leaving a stuck signed
swap. The SCRIPT fixture in the tests was itself such a truncated script,
so the test was proving round-tripping of an invalid one; replaced with a
complete script built from the live Chainflip payload. Added the 83-byte
(223 on BCH) standardness cap.

A UTXO route with no memo is now refused. For Thorchain, Chainflip and
TeleSwap the memo is the swap; building the plain send the old code built
produces an unattributable deposit. The test that asserted that behaviour
is inverted.

Route amounts are converted out of machine units. outputAmount is in the
destination asset's smallest unit ('121026', not '0.00121026'), so the
offer card read "121026 BTC" and Rango would have won every best-offer
comparison by 10^decimals. amountRestriction is converted with the source
asset's decimals.

Also: finishedRango is reset on all three reset paths, so a stale quote
cannot resurface "no offers" against an emptied amount field; BCH
recipients are normalised to prefix-less cashaddr the way the Changelly
checkout does, since BWS rejects anything else; and the now-unused
client-side referrerFee is dropped from the quote request.

54 tests, including the empty-OP_RETURN regression and a round-trip
between the two unit converters.
Audit against the doc pages the first pass skipped, plus the published
TypeScript types.

Records why this uses the Basic (single-step) API rather than the Main
multi-step one, with the measurement behind it: Main returns a one-step
route for the same pairs Basic serves on our chains (BTC->ETH,
BTC->POLYGON.USDC), and BCH->ETH is NO_ROUTE on both tiers, so that gap
is liquidity rather than API choice. Basic cannot return routes of two or
more steps at all, and Rango's integration checklist names a "+2 step
swap" as a launch scenario, so the note says to re-measure across the
full pair matrix before enabling.

Prerequisites are modelled as the discriminated union rango-types uses
(Stellar/XRPL trustlines, EVM/Tron approvals) instead of an untyped blob,
and the reason the builder refuses rather than handles them is written
down: none can arise for the chains we custody, and the docs warn
explicitly that a trustline prerequisite can belong to the DESTINATION
chain rather than the source.

UTXO swap requests now send disableEstimate. fromAddress is a single HD
address there, not the wallet's balance, so Rango's own check reports a
false insufficient-funds; the app validates spendable balance itself.

PSBT carries inputsToSign, matching the published type.

Not adopting rango-sdk-basic. Its client takes the API key in the
constructor, which cannot work in an app whose provider calls proxy
through BWS precisely to keep credentials server-side, and BWS uses
`request` across every other external service. Worth noting the published
types would not have prevented this integration's worst bug either:
rango-types@0.6.0 declares the UTXO transfer memo as `memo: string | null`
with no memoType field anywhere, which is the incomplete picture that
produced the double-wrapped OP_RETURN.
Rango renders its checkout inline in SwapCryptoRoot like Changelly does,
rather than in a dedicated screen. sell-crypto has a screen per provider
because selling navigates from quote to checkout; swap does not — the
only navigation in the swap flow is to the shared ERC20 approve screen,
and Changelly's checkout is the lower half of SwapCryptoRoot. A pushed
screen for Rango would make picking a Rango offer visibly different from
picking a Changelly one, which is the opposite of the intent.

This commit adds the orchestration so the screen wiring stays small:

  rangoCreateCheckoutTx  final quote, unsigned tx, transaction proposal,
                         and whether an approval is needed first
  saveRangoTx            records the order at broadcast
  rangoTrackSwap         follows it to completion

Signing stays in the screen. publishAndSign owns password prompts,
hardware-wallet pairing and TSS, none of which should be duplicated per
provider.

Two things carried over from review rather than deferred again:

The swap endpoint re-quotes, and Rango pins no rate the way Changelly's
fixed-rate id does, so the returned outputAmountMin is compared against
the one the user accepted and the swap is abandoned if it fell. Without
that, the amount shown and the amount signed are different promises.

The order is persisted before any polling, with status 'running'. If the
app is killed mid-swap it stays in history and can be refreshed from the
settings screen, which is how Changelly behaves. Polling now takes a
cancelled() hook so a screen can drop it on unmount instead of leaving a
timer running, and the timeout path documents that an absent or 'running'
status means still-pending, never failed — iOS suspends JS timers in the
background, so a resumed app usually lands there.

SwapCryptoApproveErc20 needed only its spenderKey type widened: it was
already provider-agnostic through offerKey, so Rango reuses it as-is.
Completes the flow. Selecting a Rango offer now builds a proposal,
signs, broadcasts, records the order and tracks it to completion — in
the same screen, with the same controls, as a Changelly swap.

Rango renders inline rather than in its own screen because that is what
makes the two feel identical. Changelly's checkout is the lower half of
this screen; a pushed screen for Rango would have made the provider the
most visible thing about the choice.

The pieces are deliberately small because the orchestration already
lives in rango-checkout.effects:

- createRangoTransaction mirrors createChangellyTransaction and hangs off
  the same selectedOffer switch
- canContinue holds the swipe until the proposal exists, the way it holds
  for Changelly until there is an exchangeTxId
- makePayment branches only at the end, to save and to pick which
  provider's history to land on

ERC20 approvals reuse SwapCryptoApproveErc20, which was already
provider-agnostic through offerKey. The screen is reached the same way
Thorswap reached it, and the checkout re-runs afterwards so the proposal
is built against the new allowance rather than a stale one.

broadcastedTx is hoisted out of the else branch so the hardware-wallet
path yields a txid too; without it a Ledger swap would have been
broadcast and never recorded.

The status poll is cancelled on unmount via a mounted ref, so navigating
away does not leave a 15-minute timer running.

Verified: tsc at baseline, 3056 tests passing (+54 from the Rango
suite), and eslint on this file reports 17 errors against a baseline of
18 — all pre-existing, one fewer than before.
The orchestration had no tests. These cover the decisions that protect
the user rather than the happy path, with the HTTP layer and the wallet's
proposal builder both mocked — no network, no credentials.

- a rate that moved below the accepted minimum aborts, builds nothing,
  and releases the route reservation
- a rate that improved proceeds
- a missing allowance returns the approval WITHOUT building a proposal,
  so the proposal cannot be built against a stale allowance
- a route the wallet cannot sign, and an unusable route, are both refused
  rather than built from a null transaction
- a failed createTxProposal releases the reservation
- the order is recorded as running and keyed on requestId BEFORE any
  polling, which is what makes a swap survive the app being killed
- polling stops without asking once when the caller has cancelled, and
  survives a transient status failure rather than abandoning a swap that
  is already broadcast

14 tests. Total 3070 passing, up from 3056.
UI review against the Changelly path. Two of these made the feature
completely non-functional; the inline checkout's rows and gates are
written against Changelly's txData shape and the Rango path only
populated part of it.

The swipe button could never enable. canContinue requires amountTo > 0
and setAmountTo was only ever called on the two Changelly paths, so the
user picked an offer, watched the rows fill in, and found "Slide to swap"
permanently greyed out. amountTo now comes from the swap-time route,
along with a refreshed amountReceiving/amountReceivingFiat — the swap
call re-quotes, so the card was still showing the earlier preview.

The Network Fee row threw during render. It calls FormatAmountStr on
txData.minerFee unconditionally, and that throws Error('Nan') rather than
rendering blank — isNaN(undefined) is true. A red box appeared the moment
the proposal was ready. minerFee and minerFeeFiat are now computed the
same way Changelly computes them.

The Exchange Fee row showed USD labelled as the destination coin, e.g.
"1.230000 ETH" for a $1.23 fee, because Rango reports feeUsd. The row now
gets the fee in the destination asset and the USD figure is carried as
the fiat string.

Every order was stuck on "Running". makePayment resets the navigator to
the history screen immediately, unmounting this screen, so tying the
status poll to the mount ref killed it on every successful swap. The poll
is deliberately not tied to screen lifetime now — the order is already
persisted, so a late status update is the worst case.

A stale Changelly countdown leaked onto Rango offers. remainingTimeStr
and paymentExpired were never reset on offer change, so switching from an
expired Changelly quote to Rango left paymentExpired true and hid the
swipe button entirely. Both reset when the offer changes, and the Expires
row is hidden rather than left shimmering, since Rango pins no rate.

The approve flow pushed the user to the approve screen twice. Re-running
the checkout immediately re-reads an allowance that has not confirmed, so
Rango returns approveData again — and the user pays for a second approval
if they sign it. It now waits on rangoAwaitApproval before rebuilding,
and a dismissal with no transaction returns to offer selection instead of
leaving dead rows and a disabled button.

createTxProposal rejects with an object holding a Wallet and a function,
so JSON.stringify on it was either a wall of text in the modal or a
circular-structure throw inside the catch. Errors route through
handleCreateTxProposalError like Changelly's, with the same goBack and
fireAnalytics.

Also adds the Requested/Successful Swap Crypto analytics Changelly fires,
collapses duplicated state resets left by a scripted edit, and removes a
now-unused mount ref and a sleep copied from a path that shows a modal.
Found by running the integration against a real device and a local BWS
rather than by reading it. Every one of these was dead code while the
feature was gated off, which is why neither review pass caught them.

Adding a provider to this module means touching five places, none of
which the compiler checks:

1. RANGO_EXECUTION_ENABLED, the documented switch
2. showOffer in swapCryptoExchangesDefault — enabledExchanges filters on
   it, so flipping the switch alone did nothing at all
3. getCurrenciesPromiseByExchange — no case meant Promise.resolve([]),
   an empty coin list, and "Swap Crypto feature is not available"
4. the supportedCoins assignment switch — Rango's 49 coins reached
   allSupportedCoins but never the exchange, so the offer was skipped
5. isCoinSupportedToSwap, which gates the Swap entry point

Three of those are switch statements with a silent default. A
Record<SwapCryptoExchangeKey, ...> for the per-exchange handlers would
make the next provider a compile error instead of a silent no-op; worth
doing before anyone adds a sixth.

Also fixes, all observed on device:

The approve transaction succeeded on-chain while leaving the allowance
at zero. isApproved reported txStatus success, currentApprovedAmount
0.000000, requiredApprovedAmount 52.510000. The approve screen rebuilds
the calldata locally, but Rango generates the approval target per quote
and its docs require using the approveData it returns. The screen now
accepts provider-supplied calldata and Rango passes its own through.

The offer card rendered "undefined" where Changelly shows a value:
getRangoQuote set amountReceiving but never amountReceivingFiat, rate or
rateFiat. Computed now the same way Thorswap computes them.

isCoinSupportedByRango returned false whenever no live token list was
supplied, and isCoinSupportedBy never supplies one, so it answered no to
everything. It now answers statically for native assets — Rango lists the
native of every chain we map — and defers tokens to the live list, the
same shape as Changelly's static natives plus per-chain token lists.

Verified on device against a local BWS: 49 coins mapped from Rango's
token list, the offer resolved for a USDC-on-Arbitrum wallet, and a real
quote returned through the proxy (5 USDC to ~0.00205 ETH via Across).
The gate ships false, as before.
Verified on device against mainnet: 52.51 USDC on Arbitrum swapped to SOL on
Solana, tx 0x7e59d90642b0f358badf0356befaa004980c43bd3292306f082d300ff816319a.

Quote and swap now route through the same swapper. getRangoQuote called
/basic/quote without wallet addresses while /basic/swap was called with them,
so Rango picked a different swapper for each and the two outputAmountMin
values never matched. The rate guard then aborted every attempt before the
approval check could run, which is why the approve screen was never reached.

The guard itself was also too strict. It required the swap-time minimum to be
no lower than the quoted one; variance between the two calls is ordinary, so
it now allows the slippage the user already accepted.

The ERC20 spender was read from the wrong field. approveTo is the token
contract the approve call is sent to, not the address being granted the
allowance - that is the first argument inside approve(address,uint256). We
were checking the token against ERC20_SPENDER_APPROVAL_WHITELIST and building
the proposal against the wrong destination, so an approval could never show as
verified. The spender is now parsed out of the calldata.

A reverted or short approval no longer spins for the full three minutes:
txStatus is carried through /basic/is-approved and a failed or under-funded
allowance throws instead of polling to the deadline.

Two display bugs on the checkout screen: Expires keyed on a field Rango never
sets, so it shimmered indefinitely; and Exchange Fee showed
outputAmount - outputAmountMin, which is the slippage allowance rather than a
fee. It now reads Rango's itemised route.fee entry.
Review of the execution path found that Rango's response decided both the
destination and the amount, with nothing comparing it against what the user
agreed to on the confirm screen.

buildRangoTxProposal now takes the authorisation - source amount, sending
address and expected chain - as a required argument, so a new call site cannot
skip the check. A native value or UTXO deposit above the authorised amount, a
transaction built for another chain, and one built for another sending address
are all refused instead of becoming signable proposals.

Approval calldata was previously forwarded verbatim after checking only that
two strings were present, and the spender was sliced out at a fixed offset
without confirming the bytes were an approve call at all. It is now validated:
the approve(address,uint256) selector, the argument length and encoding, that
approveTo is the token actually being swapped, and that the allowance does not
exceed the swap amount. An unlimited approval survives the swap being
abandoned, so this one keeps costing after the fact.

The rate guard subtracted slippage from acceptedOutputAmountMin, which is
already the slippage-protected floor - double-counting it permitted delivery
below the figure the confirm screen guaranteed. It now compares directly, fails
closed when either value is missing or unparseable rather than swallowing the
error, and asks the user to accept a lower minimum instead of silently aborting
on ordinary re-quote variance.

An absent memoType used to fall through to UTF8. A hex memo would then be
written as its ASCII characters: the vault is paid, the swap cannot be
attributed, and the funds are not recoverable. The encoding must now be stated.
The BCH SCRIPT path also only inspected the first push, while isDataOut()
accepts any push-only sequence.

Also fixed, from the same review:

- Solana was offered as a swap source but has no proposal builder, so those
  quotes always failed at checkout. Rango's support is asymmetric here - it can
  deliver to a chain it cannot spend from - so the gate is on the source side
  only and Solana remains a valid destination.
- A Rango deposit on BTC was offered RBF acceleration. Bumping rewrites the
  txid Rango tracks the swap by.
- The swap-history header opened the general selector instead of Rango history.
- A failed currency fetch left Rango advertised, because it has a static
  native-asset fallback.
- totalExchangeFee was storing route.feeUsd in a field that means coin units
  everywhere else; the USD figure now has its own field.
- A transient quote error set showOffer = false, which is sticky, so one
  timeout removed Rango from the comparison for the rest of the session and hid
  the error explaining why.
- Checkout showed raw Axios and Rango strings to users; they are logged and a
  translated message is shown, matching the other providers.
- Added the missing Failed Swap Crypto event and aligned the Requested Swap
  Crypto payload to coinFrom/chainFrom, which the dashboards are keyed on.

New RangoDetails screen, mirroring ChangellyDetails. Rango history rows were
not tappable and there was no detail screen, which also meant no way to refresh
a status by hand: rangoTrackSwap polls once after broadcast and gives up after
fifteen minutes, so an app that was killed or backgrounded left an order
reading "running" permanently. Pull to refresh fixes that, and the screen
exposes the txid, the filling swapper and the Rango request ID that support
asks for. Status now carries a colour, so a failed swap no longer looks
identical to a successful one.

Tests: 79 across the Rango suites, up from 69.
@JohnathanWhite JohnathanWhite changed the title Swap: Feat - Rango Exchange provider plumbing Swap: Feat - Rango Exchange cross-chain swaps Oct 17, 2026
@Gamboster

Copy link
Copy Markdown
Collaborator

Needs rebase

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.

2 participants