Skip to content

UI improvements - iteration 2 - #6

Merged
HashEngineering merged 17 commits into
dashpay:receive-ixfrom
tomasz-ludek:release-4
Apr 1, 2016
Merged

HashEngineering merged 17 commits into
dashpay:receive-ixfrom
tomasz-ludek:release-4

Conversation

@tomasz-ludek

Copy link
Copy Markdown
Collaborator

Hi @HashEngineering,
I apologize for delay, here you can find all the UI changes we talked about on Slack.

tomasz-ludek and others added 17 commits February 27, 2016 14:45
…ibrary

Making use of Support Library. Replacing all common classes from android.app package with equivalents from android.support.v4.app.
…roid Studio

Removed reference to SvgDrawableTask. Moved native libraries (*.so files) to jniLibs folder, default place used by Android Studio.
# Conflicts:
#	wallet/AndroidManifest.xml
#	wallet/build.gradle
#	wallet/res/menu/wallet_options.xml
#	wallet/src/de/schildbach/wallet/ui/WalletBalanceFragment.java
# Conflicts:
#	wallet/build.gradle
#	wallet/res/menu/wallet_options.xml
…content positioning in Activities using toolbar.
@HashEngineering
HashEngineering merged commit 4c405dd into dashpay:receive-ix Apr 1, 2016
@jaydeep82 jaydeep82 mentioned this pull request Jan 18, 2018
HashEngineering added a commit that referenced this pull request Jun 29, 2026
…avior

Document the two-timer model (quote routeId vs deposit window), that SwapKit surfaces no
deposit-expiry field, and the per-provider behavior: MAYACHAIN stale-vault deposits are lost
while NEAR Intents refunds to sourceAddress (~1h). Add Open Question #6 asking SwapKit to
expose a per-swap deposit deadline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
HashEngineering added a commit that referenced this pull request Jul 20, 2026
* fix: remove midgard as a data source

* fix: use the USD pools to determine the USD price of all other currencies

* chore: remove commented code

* fix: add strings-maya to .tx/config

* fix: add new error text

* fix: update documentation and agents

* feat: start SwapKit proof of concept

* fix: repair many things

* fix: add provider information to preview screen, fix other issues

* fix: update the supported currency list to include NEAR supported currencies

* fix: update the supported currency list to include NEAR supported currencies

* fix: udpate portal screen to show the right name and icon

* fix: handle no routes error due to low swap value

* fix: crash from click after search

* fix: put API_KEY into the service.properties file

* fix: remove dead code

* fix: fee calculation

* fix: add swapkit model classes to proguard-rules.pro

* fix: handle errors better and improve the swap call

* fix: add edge-to-edge MayaResultDialog

* fix: exchange rates in other currencies

* feat: hide native Maya entry point on Buy and Sell screen

* fix: compile issues and default args

* fix: rename swapkit to Dash DEX

* feat: use maya API to determine if maya only coins are "chain halted"

* chore: add NEAR Intents protocol summary

* feat: align currency picker screen

* feat: obtain preferred provider

* feat: obtain preferred provider

* feat: add cache for crypto currency picker screen

* feat: add primary source for cryptocurrency icons, first for the crypto picker

* feat: add placeholder icon

* tests: add tests for MayaCryptoCurrency to verify example addresses

* feat: add swap provider to the order preview screen

* refactor: move SearchField to common components and align with Figma designs

* fix: hide debug information about which provider will be used

* fix: prevent changing the numbers after pressing continue

* docs: add Maya liquidity provider information

* fix: update cryptocurrency list to match designs

* fix: refactor the CoinRow in the currency list to use the CoinSelect component

* fix: add the using %s network

* fix: fix many issues from CodeRabbit

* fix: add taproot example addresses

* fix: use SwapKit icon url

* fix: fix merge compile issues

* fix: handle NEAR swaps and avoid crashes

* fix: properly handle NEAR fees (include them) and set max slippage to 2%

* feat: update DashDEX portal screen for buy and sell

* feat: update crypto currency picker screen for buy swaps

* fix: animation, slide-right

* feat: DashDEX buy "Enter amount" screen

Add the buy-flow amount-entry screen (Figma 35200-34693): DEXEnterAmountFragment
+ DEXEnterAmountScreen + DEXEnterAmountViewModel, reusing the shared EnterAmount bar
and NumericKeyboardCompose keypad. Wire the currency picker's BUY branch to navigate
here, replacing the placeholder dialog.

Switching the display currency (fiat / DASH / asset) converts the entered amount via
the Amount model, seeded with DASH and asset fiat prices from the Maya pool list.
Conversions use a high working scale so small results (e.g. 1 USD -> ~0.028 DASH)
aren't rounded to zero.

Also fix EnterAmount's vertical currency picker stretching to fill the row: constrain
it to wrap its content (this is the first caller to enable showCurrencyPicker).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: DashDEX buy "Enter refund address" screen

Add the refund-address step (Figma 35199-9405): DEXRefundAddressFragment +
DEXRefundAddressScreen + DEXRefundAddressViewModel. Heading/description via the shared
TopIntro, a screen-local address field with long-press-to-paste and a QR-scan button
(ScanActivity), and a bottom-pinned Continue.

The refund address is validated against the source currency's rules
(MayaCurrencyList[asset].addressParser.exactMatch); an invalid address shows an inline
error. The amount entered on the previous screen is persisted in the nav-graph-scoped
DEXEnterAmountViewModel and exposed via enteredAmount(); the enter-amount Continue now
navigates here. Downstream quote/preview is still a TODO.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: add DashDEX home-screen shortcut

Add a shortcut button that navigates directly into the DashDEX (Maya)
portal. Uses the SwapKit emblem recoloured to Dash brand blue.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: add common AddressField component, use it in DEX refund screen

Add a reusable design-system AddressField (Figma 7961:1052 / states 7961:1062): label +
crypto-address field + optional message, with focus/content/error-driven visuals (default,
pressed, entered, filled, error) and an automatic QR-scan / clear trailing icon. Split into
a focus-owning wrapper + a stateless content so previews can render all six example states.

Replace the screen-local DEXAddressField in DEXRefundAddressScreen with it.

Strengthen AddressParser.exactMatch to also verify the address (not just regex-match), so
refund-address validation rejects well-formed-but-invalid addresses.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: DashDEX buy "Send to this address" receive screen

Add the deposit-address step (Figma 35042-51682): DEXReceiveFragment +
DEXReceiveScreen + DEXReceiveViewModel. Shows "Send {COIN} to this address" with a
shadowed card holding a 200dp QR (via Qr.qrBitmap) and the deposit URI with a
copy-to-clipboard button.

The refund screen's Continue now navigates here, passing asset, currency and the
validated refund address. The real deposit address comes from a SwapKit buy swap that
isn't built yet, so loadDepositAddress() holds a detailed TODO and the screen stays in a
loading state (no fabricated address).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: SwapKit buy backend — resolve deposit address for the receive screen

Add SwapProvider.createBuyOrder (crypto -> DASH): SwapKitApiAggregator runs /v3/quote +
/v3/swap with the direction flipped vs getSwapInfo — sellAsset = the chosen crypto,
buyAsset = DASH, sourceAddress = the refund address, destinationAddress = the wallet's
DASH receive address — and returns the inbound deposit address (+ memo) as a new BuyOrder
model. Default interface impl returns failure (native Maya has no buy); DispatchingSwapProvider
delegates to the active backend.

Wire DEXReceiveViewModel to call it (injecting SwapProvider + WalletDataProvider) and
populate the address/uri or an error; DEXReceiveFragment passes the entered crypto amount
as the sell amount; the screen now surfaces errorMessage instead of spinning forever on
failure.

The deposit URI is still the plain address (per-currency BIP-21 scheme + memo remain a
TODO in buildUri). Not yet exercised against a live SwapKit buy route.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: crisp DEX receive QR + tag buy receive address for tax metadata

Render the deposit QR with FilterQuality.None so upscaling the raw module grid to 200dp
stays crisp instead of bilinear-blurred (Compose equivalent of Qr.themeAwareDrawable's
isFilterBitmap = false).

Tag the wallet's DASH receive address used for a buy as Swapkit income via
TransactionMetadataProvider (new ServiceName.Swapkit) so the incoming DASH is categorised
correctly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf: buy swaps route exclusively via NEAR; skip Maya signals on buy picker

Make the SwapProvider direction-aware (setSwapDirection, propagated from MayaViewModel).
On BUY the SwapKit aggregator now skips the mayanode /inbound_addresses halt query and the
Maya-vs-NEAR preferred-route quotes: the buy picker excludes Maya-only assets and routes
everything via NEAR, so neither signal affects any buy-eligible asset. The Maya-only
classification still runs (needed to know which assets to exclude). Both-provider assets are
labelled "NEAR" statically on the buy picker instead of "Multiple networks".

Pin createBuyOrder's quote to providers=[NEAR] so a both-provider asset can never resolve to
a Maya route — Maya can't buy DASH and would refund to the inbound tx VIN0, ignoring the
refund address we collect for NEAR Intents' refund-to-sourceAddress semantics.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: build BIP-21 deposit URI for the DEX receive QR

buildUri now produces "<scheme>:<address>?amount=<amount>" using the chosen asset's
payment parser uriPrefix (e.g. bitcoin:, litecoin:), falling back to the bare address when
no processor is registered or the amount is blank.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs: SwapKit deposit-address/QR validity and per-provider refund behavior

Document the two-timer model (quote routeId vs deposit window), that SwapKit surfaces no
deposit-expiry field, and the per-provider behavior: MAYACHAIN stale-vault deposits are lost
while NEAR Intents refunds to sourceAddress (~1h). Add Open Question #6 asking SwapKit to
expose a per-swap deposit deadline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: prevent maya from appearing on the buy list

* fix: attempt to improve animations for the first two screens in the flow

* fix: update TopIntroSend

* fix: update QR code URI for DEX receive

* fix: validate the entered amount on buy swaps

* fix: address coderabbitai feedback

* fix: address issues related to failure to process coin cache on release builds

* feat: update receive screen

* docs: remove extra v

* fix: include network on the receive screen

* fix: improve enter amount screen

* tests: update tests

* fix: address more coderabbit feedback

* fix: improve refund address screen

* fix: add missing cache code for buy

* fix: route memo-bearing swaps through the OP_RETURN builder to prevent fund loss

commitSwapTransaction chose the memo-less deposit path purely on a 'MAYA'
substring match of the joined provider string (routeName defaults to "").
If SwapKit returned a Maya-settling best route with an empty/absent providers
list — or a provider not literally named 'MAYA' — the swap sent DASH to the
Asgard vault with no OP_RETURN memo, which cannot be matched to a swap and
strands the funds.

Make the presence of a memo the authoritative signal: route through the Maya
OP_RETURN builder whenever the route is classified Maya OR a memo is present.
Maya routes always carry a memo; NEAR deposits never do, so legitimate NEAR
swaps are unaffected, and any mislabelled memo-bearing route now fails loudly
(80-byte guard) instead of losing funds.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: keep separate buy/sell snapshot caches and refresh on direction switch

Wire the SwapKitApiAggregator to the per-direction snapshot keys (the BUY key
was added previously): hydrateFromSnapshot/persistSnapshot now read and write
the cache for the active swapDirection, so a leaner BUY refresh never clobbers
the richer SELL snapshot (preferred routes + Maya halt status) and vice versa.
reset() clears both keys.

On a direction switch, drop the now-wrong in-memory list and re-hydrate the new
direction's snapshot. Because observePoolList (which normally triggers the
background refresh) is not re-invoked on a direction change, setSwapDirection
now kicks the refresh itself using the last fiat rate seen by observePoolList —
otherwise the buy coin list would show only a spinner with an empty buy cache.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(dex): cap enter-amount at protocol maximum to match common EnterAmount

DEXEnterAmountViewModel accepted arbitrarily large amounts, while the common
EnterAmountFragment rejects any keystroke whose DASH-equivalent exceeds
Constants.MAX_MONEY. Add the same guard in onKeyInput: reject the key and
restore the previous value when the resulting DASH amount would exceed the
protocol maximum. Uses the Amount model's own conversion so the cap applies
whether the user is typing in fiat, DASH, or the asset currency.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(dex): distinguish above-maximum from below-minimum route error

Map the noRoutesFound validation failure to a "higher than the allowed
maximum" message when the entered amount is large, keeping the existing
"below the allowed minimum" message otherwise. Add the corresponding
maya_error_below_allowed_maximum string.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* style(maya): apply ktlint formatting

Import ordering, remove unused imports, wrap long argument lists and log
statements, and add missing trailing newlines across the maya module.
No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(dex): friendlier buy-swap errors and preserve entered amount

The buy flow surfaced SwapKit's raw error codes (e.g. "validation_error")
to the user. The root cause of that particular error was the entered amount
being lost: DEXEnterAmountViewModel.setArguments runs on every onCreateView
(including back-navigation) and reset the shared, nav-graph-scoped amount to
zero, so the receive step sent a zero sell amount that SwapKit rejects.

- DEXEnterAmountViewModel: don't re-seed (and wipe) the committed amount when
  re-entering the same asset; only seed for a genuinely new entry.
- DEXReceiveViewModel: reject a non-positive sellAmount before calling the API,
  and map SwapKit failures to friendly, localized @stringres messages.
- SwapKitErrors: new Context-free mapper from SwapKit error codes to message
  resources, reusable across swap surfaces.
- DEXEnterAmountScreen: replace the unreliable min/max guess (which compared the
  raw selected-currency string to a fixed threshold) with one neutral,
  amount-focused message.
- strings: add dex_error_* messages; reword dex_enter_amount_invalid.
- Remove the now-unused onToggleBalance.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(dex): persist entered data and handle offline in the buy flow

Two robustness improvements across the DashDEX buy screens (enter-amount,
refund-address, receive):

1. Survive process death. The enter-amount and refund-address ViewModels now
   persist the user's input to SavedStateHandle (the entered Amount — @parcelize,
   rates + anchor included — and the refund address), asset-gated, and restore it
   when the screen is recreated. The amount is also restored in the enter-amount
   ViewModel's init so downstream steps (refund / receive) read a correct
   enteredAmount() even when the OS relaunches straight onto their screen.

2. Handle no network connectivity (mirroring the coin picker). Each ViewModel
   injects NetworkStateInt and mirrors connectivity into its UI state; each screen
   shows a non-dismissable no-connection toast while offline and disables all
   interaction: the numeric keypad is dimmed and inert (new `enabled` param on the
   shared NumericKeyboardCompose), the refund address field is disabled, and the
   Continue buttons are disabled. The ViewModels also guard their input/continue
   handlers on isOnline as defense-in-depth.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(dex): create the buy order on the refund step, not the receive screen

Pressing Continue on the refund-address screen now validates the swap end-to-end
with SwapKit (createBuyOrder) and passes the resolved deposit address forward,
instead of the receive screen calling createBuyOrder again.

- DEXRefundAddressViewModel.submitOrder: validate the address, mark the DASH
  destination as income, then create the buy order; on success emit onOrderCreated
  (deposit address + sell amount), on failure surface a friendly SwapKitErrors
  message inline. Shows a submitting state.
- DEXRefundAddressScreen: Continue shows a spinner and is disabled while
  submitting; the address field is locked during submission; SwapKit order errors
  render inline, distinct from the address-format error.
- nav: dexReceiveFragment args change from refundAddress to sellAmount +
  depositAddress.
- DEXReceiveViewModel/Fragment: now purely presentational — dropped SwapProvider,
  WalletDataProvider, TransactionMetadataProvider and the loadDepositAddress /
  createBuyOrder path; setArguments just displays the passed-in deposit address and
  builds the QR/URI. Removes the dependency on the shared enter-amount ViewModel.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(maya): toast instead of dialog on zero DASH balance, disable Continue

When the wallet has no DASH to convert (userDashAccountEmptyError), the convert
screen popped a blocking dialog while Continue could still be enabled by typing
any non-zero amount (checkTheUserEnteredValue only checked non-zero, not balance).

- MayaConvertCryptoFragment: show a Toast instead of the AdaptiveDialog, and lock
  Continue via fragment.setInputEnabled(false).
- ConvertViewFragment: add an inputEnabled gate + public setInputEnabled(); every
  continueBtn.isEnabled assignment now respects it, so Continue stays disabled
  regardless of the entered amount. Buffered until the view exists.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(dex): backend-mapped swap errors shown inline, retry default quote when too low

Add errorMessageRes()/isAmountTooLowError() to SwapProvider so each backend
owns its own error vocabulary (Maya via getMayaErrorString, SwapKit via
SwapKitErrors) and DispatchingSwapProvider delegates to the active one.
Screens (address input, convert crypto, DEX refund) no longer reference a
specific backend's error mapping.

The sell address-input screen now surfaces quote errors inline under the
field instead of a blocking dialog, and AddressInputFragment restores the
address-format error text after a subclass replaced it with a swap error.

The bootstrap quote on that screen (1 DASH) can sit below a route's minimum;
on an amount-too-low error the amount is doubled and retried, at most twice
(2 then 4 DASH), before the error is surfaced.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(maya): per-session generated example addresses via getNewExampleAddress()

Add MayaCryptoCurrency.getNewExampleAddress(): every chain class derives a
format-valid address (checksummed wherever the format defines one) from a
single per-session ECKey, so within a session each chain's generated address
is stable. Key-derived for real where the chain's derivation is available
(BTC/LTC segwit, DASH/DOGE/TRON/BCH/ZEC Base58Check, Cosmos-family bech32,
XRP ripple Base58Check); otherwise deterministic bytes expanded from the
session pubkey (EVM hex, Solana, NEAR, SUI, Starknet, TON with CRC16,
Cardano and Radix bech32). Encoders live in the new AddressGenerator object.

Use it for the placeholder addresses sent to providers: validateBuyOrder's
refund address (DEXEnterAmountViewModel) and the legacy Maya no-destination
default quote (MayaWebApi), instead of the well-known hardcoded examples.

Also fix MayaDashCryptoCurrency, which inherited the Bitcoin-params address
parser and rejected Dash addresses (latent — DASH isn't in MayaCurrencyList).

Unit tests cover every override: parser exact-match, session stability, and
checksum round-trips through real decoders where available.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): apply low-severity cleanups L1-L7 from agent code review

Changes generated by the kotlin-master-engineer agent review of this
branch (see claude-fable-5-review.md):

- L1: derive the receive address off the main thread (Dispatchers.IO)
  in DEXRefundAddressViewModel.submitOrder
- L2: replace validationError: String? with validationFailed: Boolean;
  the screen only ever shows a fixed localized message and the raw
  provider message is already logged
- L3: unify both getDefaultSwapQuote defaults on a shared
  DEFAULT_QUOTE_DUFFS (10 DASH) constant; the 1->10 bump was deliberate
  (52a04fb) and all two-arg callers pass value explicitly
- L4: collapse dead aggregator-type branches in isTradingActive();
  unwrap DispatchingSwapProvider.active once
- L5: drop stale "buy flow not built yet" TODO in MayaPortalFragment
- L6: delete DEBUG_FORCE_MAYA_ONLY_HALT test scaffolding and the
  forcedHalt branch in SwapKitApiAggregator
- L7: BigDecimal.valueOf for double USD prices; document the
  outbound-fee-as-total display estimate in mapToSwapQuote

L8 (negative bad-checksum fixtures) deferred: blocked on the H1/H2
address-validation hardening.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): apply medium-severity fixes M1-M6 from agent code review

Changes generated by the kotlin-master-engineer agent review of this
branch (see claude-fable-5-review.md):

- M1: block amount input (keypad + currency switch) while the buy
  validation quote is in flight, so a Success can never navigate with
  an amount other than the one validated; keypad dims like offline
- M2: tag the receive address with the Income tax category only after
  createBuyOrder succeeds, not before the attempt
- M3: BTC deposit URI now validates base58 or bech32 addresses and
  always emits proper BIP-21 (?amount=); previously bech32 deposits
  (what SwapKit/NEAR return) got a malformed &amount= fallback that
  scanning wallets drop
- M4: DispatchingSwapProvider init no longer clobbers an explicit
  setBackend that races the persisted-value load (lock + flag)
- M5: Starknet parser requires 50-64 hex chars and rejects the zero
  felt; 0x0 / truncated felts are burn destinations
- M6: NEAR named-account grammar per account-id rules (labels can't
  lead/trail with -/_, no double separators) and 64-char overall cap

Parser tests updated: 0xdeadbeef now invalid, new negative cases for
zero felt, short felts, and malformed NEAR account ids.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): surface the buy-order deposit memo on the receive screen (C1)

Critical fix from the kotlin-master-engineer agent review (see
claude-fable-5-review.md): SwapKit's BuyOrder.memo was captured but
dropped before the receive screen — a deposit sent without a required
chain memo/tag (XRP destination tag, TON comment, Cosmos-style memo)
cannot be attributed to the swap and the funds are lost.

Buys are NEAR Intents-pinned, whose SIMPLE deposit mode issues a unique
address with no memo, so the common case is unaffected — but the 1Click
spec returns depositMemo when "the chain requires it", and this now
reaches the user instead of being silently discarded:

- DEXRefundOrderResult carries memo; submitOrder passes it through
- new nav arg memo (default "") on dexReceiveFragment
- DEXReceiveViewModel puts the trimmed memo in the UI state
- receive screen shows a copyable "Memo / Tag" row (UriRow generalized
  to LabeledCopyRow) plus a red warning that transfers without the
  memo will be lost; preview added for the XRP tag case

The memo is deliberately NOT encoded into the QR/payment URI: there is
no cross-chain URI standard for memos, and a misparsed URI is worse
than a clearly displayed field (the exchange-deposit UX).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): verify address checksums for XRP, TRON, Cardano and TON (H1/H2, L8)

High-severity fixes from the kotlin-master-engineer agent review (see
claude-fable-5-review.md): these four parsers accepted any string of
the right shape, so a single-character typo in a sell destination or
buy refund address passed the client and relied entirely on
server-side rejection. All four formats are checksummed; the checksums
are now verified in verifyAddress overrides:

- XRP: ripple-alphabet Base58Check decode (new
  AddressGenerator.rippleBase58Decode, inverse of the existing
  encoder), 0x00 account version byte, double-SHA256 checksum
- TRON: Base58.decodeChecked + 0x41 mainnet version byte
- Cardano: Shelley bech32 checksum with hrp "addr" (Bech32.decode
  gained a max-length overload — Shelley's ~103 chars exceed
  BIP-173's 90-char cap); Byron via minimal CBOR parse of
  [tag24(payload), crc32] with the CRC32 verified
- TON: base64url decode, CRC16-XMODEM check (crc16Xmodem now shared
  from AddressGenerator), testnet tag bit rejected (only 0x11/0x51
  accepted), workchain must be 0 or -1

The hardcoded Cardano exampleAddress turned out to be fabricated (its
bech32 checksum is invalid) — replaced with the CIP-19 mainnet test
vector; the fabricated address is kept as a negative test fixture.

L8: negative bad-checksum fixtures added for all four chains, each
pre-verified computationally: single-char typos (checksum fails), a
testnet-flagged TON address with a valid CRC (exercises the tag
check), and an unknown-workchain raw TON form.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): rethrow cancellation in swap tx builder, concurrent price cache (H3/H4)

Remaining high-severity fixes from the kotlin-master-engineer agent
review (see claude-fable-5-review.md):

- H3: buildAndSendSwapTx caught CancellationException in its broad
  catch (Exception) and converted it to ResponseResource.Failure. If
  the coroutine was cancelled after sendTransaction() had already
  broadcast the DASH swap tx, the caller saw "swap failed" and could
  retry — a double swap. CancellationException is now rethrown ahead
  of the generic handler; both Maya and SwapKit commit paths route
  through this function.

- H4: usdPriceCache was a plain HashMap written on responseScope
  (pool refresh / snapshot hydration / reset) while read on the main
  dispatcher via applyPoolPrices — torn reads or a resize spin were
  possible. Now a ConcurrentHashMap; all call sites unchanged.

This completes the review: C1, H1-H4, M1-M6 and L1-L8 are all
addressed.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): clear the entered buy amount when leaving the flow backwards

The enter-amount ViewModel is nav-graph scoped, so backing out to the
coin picker (or exiting via "Back home" on the receive screen) kept the
committed amount and its SavedStateHandle copy alive, restoring a stale
amount on the next entry into the buy flow. Clear both when the
enter-amount fragment is popped off the back stack; isRemoving keeps
config changes and process-death restore intact.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): mention transient route outages in no-route error copy

SwapKit reports both an out-of-range amount and a temporarily
unavailable provider route as noRoutesFound; the messages on the
enter-amount and refund screens only suggested changing the amount.
Add a "try again shortly" hint, since NEAR route outages observed in
testing recovered within a minute.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): consistent copy for shared swap errors, document per-screen display

Two inconsistencies: the validation_error message mentioned a refund
address on the sell address-input screen (where the user enters a
destination), and SwapKit's ambiguous noRoutesFound showed "amount too
low" on the sell enter-amount banner but neutral no-route copy
elsewhere. Make the validation message address-neutral and feed the
banner from the active backend's errorMessageRes (Maya's genuine
amount-too-low keeps its minimum copy).

Document the full flow/screen/code/text matrix in SWAPKIT_PROTOCOL.md.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): avoid nav-graph ViewModel crash when leaving buy flow to Home

DEXEnterAmountFragment.onDestroy() forced the nav-graph-scoped viewModel
lazy to resolve, which re-runs getBackStackEntry(nav_maya). When the whole
flow is popped to Home ("Back home" on the receive screen), that graph is
already off the back stack, so resolution threw IllegalArgumentException.

Capture the ViewModel in onCreateView (graph guaranteed alive) and clear
the entered amount via that captured instance in onDestroy, never touching
the lazy after teardown.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(dex): resolve post-merge compile fixups from feat/dash-dex merge

- MainViewModel: restore missing comma before swapProvider constructor param
- DEXReceiveScreen / DEXRefundAddressScreen: drop stale modifier/padding args
  on TopIntro left over from the merge

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
HashEngineering added a commit that referenced this pull request Jul 21, 2026
…#1511)

* fix: remove midgard as a data source

* fix: use the USD pools to determine the USD price of all other currencies

* chore: remove commented code

* fix: add strings-maya to .tx/config

* fix: add new error text

* fix: update documentation and agents

* feat: start SwapKit proof of concept

* fix: repair many things

* fix: add provider information to preview screen, fix other issues

* fix: update the supported currency list to include NEAR supported currencies

* fix: update the supported currency list to include NEAR supported currencies

* fix: udpate portal screen to show the right name and icon

* fix: handle no routes error due to low swap value

* fix: crash from click after search

* fix: put API_KEY into the service.properties file

* fix: remove dead code

* fix: fee calculation

* fix: add swapkit model classes to proguard-rules.pro

* fix: handle errors better and improve the swap call

* fix: add edge-to-edge MayaResultDialog

* fix: exchange rates in other currencies

* feat: hide native Maya entry point on Buy and Sell screen

* fix: compile issues and default args

* fix: rename swapkit to Dash DEX

* feat: use maya API to determine if maya only coins are "chain halted"

* chore: add NEAR Intents protocol summary

* feat: align currency picker screen

* feat: obtain preferred provider

* feat: obtain preferred provider

* feat: add cache for crypto currency picker screen

* feat: add primary source for cryptocurrency icons, first for the crypto picker

* feat: add placeholder icon

* tests: add tests for MayaCryptoCurrency to verify example addresses

* feat: add swap provider to the order preview screen

* refactor: move SearchField to common components and align with Figma designs

* fix: hide debug information about which provider will be used

* fix: prevent changing the numbers after pressing continue

* docs: add Maya liquidity provider information

* fix: update cryptocurrency list to match designs

* fix: refactor the CoinRow in the currency list to use the CoinSelect component

* fix: add the using %s network

* fix: fix many issues from CodeRabbit

* fix: add taproot example addresses

* fix: use SwapKit icon url

* fix: fix merge compile issues

* fix: handle NEAR swaps and avoid crashes

* fix: properly handle NEAR fees (include them) and set max slippage to 2%

* feat: update DashDEX portal screen for buy and sell

* feat: update crypto currency picker screen for buy swaps

* fix: animation, slide-right

* feat: DashDEX buy "Enter amount" screen

Add the buy-flow amount-entry screen (Figma 35200-34693): DEXEnterAmountFragment
+ DEXEnterAmountScreen + DEXEnterAmountViewModel, reusing the shared EnterAmount bar
and NumericKeyboardCompose keypad. Wire the currency picker's BUY branch to navigate
here, replacing the placeholder dialog.

Switching the display currency (fiat / DASH / asset) converts the entered amount via
the Amount model, seeded with DASH and asset fiat prices from the Maya pool list.
Conversions use a high working scale so small results (e.g. 1 USD -> ~0.028 DASH)
aren't rounded to zero.

Also fix EnterAmount's vertical currency picker stretching to fill the row: constrain
it to wrap its content (this is the first caller to enable showCurrencyPicker).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: DashDEX buy "Enter refund address" screen

Add the refund-address step (Figma 35199-9405): DEXRefundAddressFragment +
DEXRefundAddressScreen + DEXRefundAddressViewModel. Heading/description via the shared
TopIntro, a screen-local address field with long-press-to-paste and a QR-scan button
(ScanActivity), and a bottom-pinned Continue.

The refund address is validated against the source currency's rules
(MayaCurrencyList[asset].addressParser.exactMatch); an invalid address shows an inline
error. The amount entered on the previous screen is persisted in the nav-graph-scoped
DEXEnterAmountViewModel and exposed via enteredAmount(); the enter-amount Continue now
navigates here. Downstream quote/preview is still a TODO.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: add DashDEX home-screen shortcut

Add a shortcut button that navigates directly into the DashDEX (Maya)
portal. Uses the SwapKit emblem recoloured to Dash brand blue.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: add common AddressField component, use it in DEX refund screen

Add a reusable design-system AddressField (Figma 7961:1052 / states 7961:1062): label +
crypto-address field + optional message, with focus/content/error-driven visuals (default,
pressed, entered, filled, error) and an automatic QR-scan / clear trailing icon. Split into
a focus-owning wrapper + a stateless content so previews can render all six example states.

Replace the screen-local DEXAddressField in DEXRefundAddressScreen with it.

Strengthen AddressParser.exactMatch to also verify the address (not just regex-match), so
refund-address validation rejects well-formed-but-invalid addresses.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: DashDEX buy "Send to this address" receive screen

Add the deposit-address step (Figma 35042-51682): DEXReceiveFragment +
DEXReceiveScreen + DEXReceiveViewModel. Shows "Send {COIN} to this address" with a
shadowed card holding a 200dp QR (via Qr.qrBitmap) and the deposit URI with a
copy-to-clipboard button.

The refund screen's Continue now navigates here, passing asset, currency and the
validated refund address. The real deposit address comes from a SwapKit buy swap that
isn't built yet, so loadDepositAddress() holds a detailed TODO and the screen stays in a
loading state (no fabricated address).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: SwapKit buy backend — resolve deposit address for the receive screen

Add SwapProvider.createBuyOrder (crypto -> DASH): SwapKitApiAggregator runs /v3/quote +
/v3/swap with the direction flipped vs getSwapInfo — sellAsset = the chosen crypto,
buyAsset = DASH, sourceAddress = the refund address, destinationAddress = the wallet's
DASH receive address — and returns the inbound deposit address (+ memo) as a new BuyOrder
model. Default interface impl returns failure (native Maya has no buy); DispatchingSwapProvider
delegates to the active backend.

Wire DEXReceiveViewModel to call it (injecting SwapProvider + WalletDataProvider) and
populate the address/uri or an error; DEXReceiveFragment passes the entered crypto amount
as the sell amount; the screen now surfaces errorMessage instead of spinning forever on
failure.

The deposit URI is still the plain address (per-currency BIP-21 scheme + memo remain a
TODO in buildUri). Not yet exercised against a live SwapKit buy route.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: crisp DEX receive QR + tag buy receive address for tax metadata

Render the deposit QR with FilterQuality.None so upscaling the raw module grid to 200dp
stays crisp instead of bilinear-blurred (Compose equivalent of Qr.themeAwareDrawable's
isFilterBitmap = false).

Tag the wallet's DASH receive address used for a buy as Swapkit income via
TransactionMetadataProvider (new ServiceName.Swapkit) so the incoming DASH is categorised
correctly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf: buy swaps route exclusively via NEAR; skip Maya signals on buy picker

Make the SwapProvider direction-aware (setSwapDirection, propagated from MayaViewModel).
On BUY the SwapKit aggregator now skips the mayanode /inbound_addresses halt query and the
Maya-vs-NEAR preferred-route quotes: the buy picker excludes Maya-only assets and routes
everything via NEAR, so neither signal affects any buy-eligible asset. The Maya-only
classification still runs (needed to know which assets to exclude). Both-provider assets are
labelled "NEAR" statically on the buy picker instead of "Multiple networks".

Pin createBuyOrder's quote to providers=[NEAR] so a both-provider asset can never resolve to
a Maya route — Maya can't buy DASH and would refund to the inbound tx VIN0, ignoring the
refund address we collect for NEAR Intents' refund-to-sourceAddress semantics.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat: build BIP-21 deposit URI for the DEX receive QR

buildUri now produces "<scheme>:<address>?amount=<amount>" using the chosen asset's
payment parser uriPrefix (e.g. bitcoin:, litecoin:), falling back to the bare address when
no processor is registered or the amount is blank.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs: SwapKit deposit-address/QR validity and per-provider refund behavior

Document the two-timer model (quote routeId vs deposit window), that SwapKit surfaces no
deposit-expiry field, and the per-provider behavior: MAYACHAIN stale-vault deposits are lost
while NEAR Intents refunds to sourceAddress (~1h). Add Open Question #6 asking SwapKit to
expose a per-swap deposit deadline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: prevent maya from appearing on the buy list

* fix: attempt to improve animations for the first two screens in the flow

* fix: update TopIntroSend

* fix: update QR code URI for DEX receive

* fix: validate the entered amount on buy swaps

* fix: address coderabbitai feedback

* fix: address issues related to failure to process coin cache on release builds

* feat: update receive screen

* docs: remove extra v

* fix: include network on the receive screen

* fix: improve enter amount screen

* tests: update tests

* fix: address more coderabbit feedback

* fix: improve refund address screen

* fix: add missing cache code for buy

* fix: route memo-bearing swaps through the OP_RETURN builder to prevent fund loss

commitSwapTransaction chose the memo-less deposit path purely on a 'MAYA'
substring match of the joined provider string (routeName defaults to "").
If SwapKit returned a Maya-settling best route with an empty/absent providers
list — or a provider not literally named 'MAYA' — the swap sent DASH to the
Asgard vault with no OP_RETURN memo, which cannot be matched to a swap and
strands the funds.

Make the presence of a memo the authoritative signal: route through the Maya
OP_RETURN builder whenever the route is classified Maya OR a memo is present.
Maya routes always carry a memo; NEAR deposits never do, so legitimate NEAR
swaps are unaffected, and any mislabelled memo-bearing route now fails loudly
(80-byte guard) instead of losing funds.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix: keep separate buy/sell snapshot caches and refresh on direction switch

Wire the SwapKitApiAggregator to the per-direction snapshot keys (the BUY key
was added previously): hydrateFromSnapshot/persistSnapshot now read and write
the cache for the active swapDirection, so a leaner BUY refresh never clobbers
the richer SELL snapshot (preferred routes + Maya halt status) and vice versa.
reset() clears both keys.

On a direction switch, drop the now-wrong in-memory list and re-hydrate the new
direction's snapshot. Because observePoolList (which normally triggers the
background refresh) is not re-invoked on a direction change, setSwapDirection
now kicks the refresh itself using the last fiat rate seen by observePoolList —
otherwise the buy coin list would show only a spinner with an empty buy cache.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(dex): cap enter-amount at protocol maximum to match common EnterAmount

DEXEnterAmountViewModel accepted arbitrarily large amounts, while the common
EnterAmountFragment rejects any keystroke whose DASH-equivalent exceeds
Constants.MAX_MONEY. Add the same guard in onKeyInput: reject the key and
restore the previous value when the resulting DASH amount would exceed the
protocol maximum. Uses the Amount model's own conversion so the cap applies
whether the user is typing in fiat, DASH, or the asset currency.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(dex): distinguish above-maximum from below-minimum route error

Map the noRoutesFound validation failure to a "higher than the allowed
maximum" message when the entered amount is large, keeping the existing
"below the allowed minimum" message otherwise. Add the corresponding
maya_error_below_allowed_maximum string.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* style(maya): apply ktlint formatting

Import ordering, remove unused imports, wrap long argument lists and log
statements, and add missing trailing newlines across the maya module.
No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(dex): friendlier buy-swap errors and preserve entered amount

The buy flow surfaced SwapKit's raw error codes (e.g. "validation_error")
to the user. The root cause of that particular error was the entered amount
being lost: DEXEnterAmountViewModel.setArguments runs on every onCreateView
(including back-navigation) and reset the shared, nav-graph-scoped amount to
zero, so the receive step sent a zero sell amount that SwapKit rejects.

- DEXEnterAmountViewModel: don't re-seed (and wipe) the committed amount when
  re-entering the same asset; only seed for a genuinely new entry.
- DEXReceiveViewModel: reject a non-positive sellAmount before calling the API,
  and map SwapKit failures to friendly, localized @stringres messages.
- SwapKitErrors: new Context-free mapper from SwapKit error codes to message
  resources, reusable across swap surfaces.
- DEXEnterAmountScreen: replace the unreliable min/max guess (which compared the
  raw selected-currency string to a fixed threshold) with one neutral,
  amount-focused message.
- strings: add dex_error_* messages; reword dex_enter_amount_invalid.
- Remove the now-unused onToggleBalance.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(dex): persist entered data and handle offline in the buy flow

Two robustness improvements across the DashDEX buy screens (enter-amount,
refund-address, receive):

1. Survive process death. The enter-amount and refund-address ViewModels now
   persist the user's input to SavedStateHandle (the entered Amount — @parcelize,
   rates + anchor included — and the refund address), asset-gated, and restore it
   when the screen is recreated. The amount is also restored in the enter-amount
   ViewModel's init so downstream steps (refund / receive) read a correct
   enteredAmount() even when the OS relaunches straight onto their screen.

2. Handle no network connectivity (mirroring the coin picker). Each ViewModel
   injects NetworkStateInt and mirrors connectivity into its UI state; each screen
   shows a non-dismissable no-connection toast while offline and disables all
   interaction: the numeric keypad is dimmed and inert (new `enabled` param on the
   shared NumericKeyboardCompose), the refund address field is disabled, and the
   Continue buttons are disabled. The ViewModels also guard their input/continue
   handlers on isOnline as defense-in-depth.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(dex): create the buy order on the refund step, not the receive screen

Pressing Continue on the refund-address screen now validates the swap end-to-end
with SwapKit (createBuyOrder) and passes the resolved deposit address forward,
instead of the receive screen calling createBuyOrder again.

- DEXRefundAddressViewModel.submitOrder: validate the address, mark the DASH
  destination as income, then create the buy order; on success emit onOrderCreated
  (deposit address + sell amount), on failure surface a friendly SwapKitErrors
  message inline. Shows a submitting state.
- DEXRefundAddressScreen: Continue shows a spinner and is disabled while
  submitting; the address field is locked during submission; SwapKit order errors
  render inline, distinct from the address-format error.
- nav: dexReceiveFragment args change from refundAddress to sellAmount +
  depositAddress.
- DEXReceiveViewModel/Fragment: now purely presentational — dropped SwapProvider,
  WalletDataProvider, TransactionMetadataProvider and the loadDepositAddress /
  createBuyOrder path; setArguments just displays the passed-in deposit address and
  builds the QR/URI. Removes the dependency on the shared enter-amount ViewModel.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(maya): toast instead of dialog on zero DASH balance, disable Continue

When the wallet has no DASH to convert (userDashAccountEmptyError), the convert
screen popped a blocking dialog while Continue could still be enabled by typing
any non-zero amount (checkTheUserEnteredValue only checked non-zero, not balance).

- MayaConvertCryptoFragment: show a Toast instead of the AdaptiveDialog, and lock
  Continue via fragment.setInputEnabled(false).
- ConvertViewFragment: add an inputEnabled gate + public setInputEnabled(); every
  continueBtn.isEnabled assignment now respects it, so Continue stays disabled
  regardless of the entered amount. Buffered until the view exists.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(dex): backend-mapped swap errors shown inline, retry default quote when too low

Add errorMessageRes()/isAmountTooLowError() to SwapProvider so each backend
owns its own error vocabulary (Maya via getMayaErrorString, SwapKit via
SwapKitErrors) and DispatchingSwapProvider delegates to the active one.
Screens (address input, convert crypto, DEX refund) no longer reference a
specific backend's error mapping.

The sell address-input screen now surfaces quote errors inline under the
field instead of a blocking dialog, and AddressInputFragment restores the
address-format error text after a subclass replaced it with a swap error.

The bootstrap quote on that screen (1 DASH) can sit below a route's minimum;
on an amount-too-low error the amount is doubled and retried, at most twice
(2 then 4 DASH), before the error is surfaced.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(maya): per-session generated example addresses via getNewExampleAddress()

Add MayaCryptoCurrency.getNewExampleAddress(): every chain class derives a
format-valid address (checksummed wherever the format defines one) from a
single per-session ECKey, so within a session each chain's generated address
is stable. Key-derived for real where the chain's derivation is available
(BTC/LTC segwit, DASH/DOGE/TRON/BCH/ZEC Base58Check, Cosmos-family bech32,
XRP ripple Base58Check); otherwise deterministic bytes expanded from the
session pubkey (EVM hex, Solana, NEAR, SUI, Starknet, TON with CRC16,
Cardano and Radix bech32). Encoders live in the new AddressGenerator object.

Use it for the placeholder addresses sent to providers: validateBuyOrder's
refund address (DEXEnterAmountViewModel) and the legacy Maya no-destination
default quote (MayaWebApi), instead of the well-known hardcoded examples.

Also fix MayaDashCryptoCurrency, which inherited the Bitcoin-params address
parser and rejected Dash addresses (latent — DASH isn't in MayaCurrencyList).

Unit tests cover every override: parser exact-match, session stability, and
checksum round-trips through real decoders where available.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): apply low-severity cleanups L1-L7 from agent code review

Changes generated by the kotlin-master-engineer agent review of this
branch (see claude-fable-5-review.md):

- L1: derive the receive address off the main thread (Dispatchers.IO)
  in DEXRefundAddressViewModel.submitOrder
- L2: replace validationError: String? with validationFailed: Boolean;
  the screen only ever shows a fixed localized message and the raw
  provider message is already logged
- L3: unify both getDefaultSwapQuote defaults on a shared
  DEFAULT_QUOTE_DUFFS (10 DASH) constant; the 1->10 bump was deliberate
  (52a04fb) and all two-arg callers pass value explicitly
- L4: collapse dead aggregator-type branches in isTradingActive();
  unwrap DispatchingSwapProvider.active once
- L5: drop stale "buy flow not built yet" TODO in MayaPortalFragment
- L6: delete DEBUG_FORCE_MAYA_ONLY_HALT test scaffolding and the
  forcedHalt branch in SwapKitApiAggregator
- L7: BigDecimal.valueOf for double USD prices; document the
  outbound-fee-as-total display estimate in mapToSwapQuote

L8 (negative bad-checksum fixtures) deferred: blocked on the H1/H2
address-validation hardening.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): apply medium-severity fixes M1-M6 from agent code review

Changes generated by the kotlin-master-engineer agent review of this
branch (see claude-fable-5-review.md):

- M1: block amount input (keypad + currency switch) while the buy
  validation quote is in flight, so a Success can never navigate with
  an amount other than the one validated; keypad dims like offline
- M2: tag the receive address with the Income tax category only after
  createBuyOrder succeeds, not before the attempt
- M3: BTC deposit URI now validates base58 or bech32 addresses and
  always emits proper BIP-21 (?amount=); previously bech32 deposits
  (what SwapKit/NEAR return) got a malformed &amount= fallback that
  scanning wallets drop
- M4: DispatchingSwapProvider init no longer clobbers an explicit
  setBackend that races the persisted-value load (lock + flag)
- M5: Starknet parser requires 50-64 hex chars and rejects the zero
  felt; 0x0 / truncated felts are burn destinations
- M6: NEAR named-account grammar per account-id rules (labels can't
  lead/trail with -/_, no double separators) and 64-char overall cap

Parser tests updated: 0xdeadbeef now invalid, new negative cases for
zero felt, short felts, and malformed NEAR account ids.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): surface the buy-order deposit memo on the receive screen (C1)

Critical fix from the kotlin-master-engineer agent review (see
claude-fable-5-review.md): SwapKit's BuyOrder.memo was captured but
dropped before the receive screen — a deposit sent without a required
chain memo/tag (XRP destination tag, TON comment, Cosmos-style memo)
cannot be attributed to the swap and the funds are lost.

Buys are NEAR Intents-pinned, whose SIMPLE deposit mode issues a unique
address with no memo, so the common case is unaffected — but the 1Click
spec returns depositMemo when "the chain requires it", and this now
reaches the user instead of being silently discarded:

- DEXRefundOrderResult carries memo; submitOrder passes it through
- new nav arg memo (default "") on dexReceiveFragment
- DEXReceiveViewModel puts the trimmed memo in the UI state
- receive screen shows a copyable "Memo / Tag" row (UriRow generalized
  to LabeledCopyRow) plus a red warning that transfers without the
  memo will be lost; preview added for the XRP tag case

The memo is deliberately NOT encoded into the QR/payment URI: there is
no cross-chain URI standard for memos, and a misparsed URI is worse
than a clearly displayed field (the exchange-deposit UX).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): verify address checksums for XRP, TRON, Cardano and TON (H1/H2, L8)

High-severity fixes from the kotlin-master-engineer agent review (see
claude-fable-5-review.md): these four parsers accepted any string of
the right shape, so a single-character typo in a sell destination or
buy refund address passed the client and relied entirely on
server-side rejection. All four formats are checksummed; the checksums
are now verified in verifyAddress overrides:

- XRP: ripple-alphabet Base58Check decode (new
  AddressGenerator.rippleBase58Decode, inverse of the existing
  encoder), 0x00 account version byte, double-SHA256 checksum
- TRON: Base58.decodeChecked + 0x41 mainnet version byte
- Cardano: Shelley bech32 checksum with hrp "addr" (Bech32.decode
  gained a max-length overload — Shelley's ~103 chars exceed
  BIP-173's 90-char cap); Byron via minimal CBOR parse of
  [tag24(payload), crc32] with the CRC32 verified
- TON: base64url decode, CRC16-XMODEM check (crc16Xmodem now shared
  from AddressGenerator), testnet tag bit rejected (only 0x11/0x51
  accepted), workchain must be 0 or -1

The hardcoded Cardano exampleAddress turned out to be fabricated (its
bech32 checksum is invalid) — replaced with the CIP-19 mainnet test
vector; the fabricated address is kept as a negative test fixture.

L8: negative bad-checksum fixtures added for all four chains, each
pre-verified computationally: single-char typos (checksum fails), a
testnet-flagged TON address with a valid CRC (exercises the tag
check), and an unknown-workchain raw TON form.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): rethrow cancellation in swap tx builder, concurrent price cache (H3/H4)

Remaining high-severity fixes from the kotlin-master-engineer agent
review (see claude-fable-5-review.md):

- H3: buildAndSendSwapTx caught CancellationException in its broad
  catch (Exception) and converted it to ResponseResource.Failure. If
  the coroutine was cancelled after sendTransaction() had already
  broadcast the DASH swap tx, the caller saw "swap failed" and could
  retry — a double swap. CancellationException is now rethrown ahead
  of the generic handler; both Maya and SwapKit commit paths route
  through this function.

- H4: usdPriceCache was a plain HashMap written on responseScope
  (pool refresh / snapshot hydration / reset) while read on the main
  dispatcher via applyPoolPrices — torn reads or a resize spin were
  possible. Now a ConcurrentHashMap; all call sites unchanged.

This completes the review: C1, H1-H4, M1-M6 and L1-L8 are all
addressed.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): clear the entered buy amount when leaving the flow backwards

The enter-amount ViewModel is nav-graph scoped, so backing out to the
coin picker (or exiting via "Back home" on the receive screen) kept the
committed amount and its SavedStateHandle copy alive, restoring a stale
amount on the next entry into the buy flow. Clear both when the
enter-amount fragment is popped off the back stack; isRemoving keeps
config changes and process-death restore intact.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): mention transient route outages in no-route error copy

SwapKit reports both an out-of-range amount and a temporarily
unavailable provider route as noRoutesFound; the messages on the
enter-amount and refund screens only suggested changing the amount.
Add a "try again shortly" hint, since NEAR route outages observed in
testing recovered within a minute.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): consistent copy for shared swap errors, document per-screen display

Two inconsistencies: the validation_error message mentioned a refund
address on the sell address-input screen (where the user enters a
destination), and SwapKit's ambiguous noRoutesFound showed "amount too
low" on the sell enter-amount banner but neutral no-route copy
elsewhere. Make the validation message address-neutral and feed the
banner from the active backend's errorMessageRes (Maya's genuine
amount-too-low keeps its minimum copy).

Document the full flow/screen/code/text matrix in SWAPKIT_PROTOCOL.md.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): sell swap QA fixes — quote expiry, refresh, fees, explorer links

- Show the order-preview countdown as a quote expiration ("Quote expires
  in 10 sec"), not part of the Confirm button, so it doesn't read as an
  auto-send; per-network expiry constants (Maya/NEAR, both 10s, TBC)
- Rename the expired-quote button from "Retry" to "Refresh"
- Keep fees out of the receiving-currency figures: the purchase/fee/total
  breakdown falls back to DASH when the amount was entered in the
  receiving crypto (fee is charged in DASH on top of the amount sold)
- Store the refreshed quote on the viewmodel so a commit after Refresh
  uses the new vault address/fee, not the stale original
- Add explorer links to the sell success screen: Maya routes open
  mayascan.org/tx/<txid> (inbound DASH tx hash), NEAR routes open
  explorer.near-intents.org/transactions/<deposit address>; NEAR
  description copy is placeholder pending final QA wording
- Enter-amount screen button now says "Get Quote" instead of "Continue"

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(maya): compose convert screen from Figma, reuse Menu/MenuItem

Reimplement MayaConvertCryptoFragment in Jetpack Compose per Figma node
24021:10970, reusing the shared EnterAmount and NumericKeyboardCompose
components; all amount formatting and swap logic is kept in the fragment
and ConvertViewViewModel.

The conversion-direction card is built from the design-system Menu and
MenuItem components. MenuItem gains two backward-compatible params: a
customIcon composable slot (for URL-loaded coin logos) and
subtitleMaxLines with ellipsis overflow.

Delete the orphaned view-based ConvertViewFragment, ConverterView and
CryptoCurrencyItem along with their layouts, the old fragment layout and
the CryptoCurrencyItem styleable; retag ConvertViewViewModel's logger to
its own class.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(common): add TextField compose component from Figma design system

Implements the TextField-Base component (Figma node 4111:12913, variant
set 4112:13707): floating label, blue-bordered focus state with focus
ring, typing state with clear button, red-tinted error state with
independently colorable help text, inside/outside help text slots,
character counter, and custom trailing icon slot. Previews cover the
variant grid including slot/state combinations.

Also registers TextField (and the missing AddressField) in the
figma-to-compose component mapping and DEVELOPMENT-PATTERNS, adds the
mcp__figma__* fallback tool names to the figma-to-compose agent, and
forbids implementing designs from guesswork when Figma is unreachable.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(maya): compose address input screen from Figma design

Rebuilds the Maya sell "Enter address" screen (Figma 24007:13081) in
Jetpack Compose: MayaAddressInputScreen hosted by the rewritten
MayaAddressInputFragment, keeping the original AddressInputViewModel
behavior (validation, scan, clipboard, exchange sources, bootstrap
quote check) with inline quote errors instead of dialogs.

The address field uses the design-system TextField with a permanent
innerLabel ("BTC Address") above the text line — not a disappearing
hint. TextField gains the innerLabel slot (AddressField parity);
AddressField gains innerLabel, focusRequester and onImeAction. No
imePadding on the screen: the host activity's adjustResize already
handles the keyboard, and padding twice pushed the Continue button
over the field.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(maya): keep quote buttons disabled through navigation to next screen

On both sell-flow screens the button re-enabled the moment the quote
request finished, flashing blue (and tappable) while the fragment was
still doing post-quote work before navigating:

- MayaConvertCryptoFragment: re-assert isProcessing when swapTradeOrder
  fires, since the ViewModel drops showLoading before emitting it and
  the observer still refreshes inbound addresses and builds the payment
  intent before navigating. Error paths that keep the user on the
  screen re-enable the button for retry; returning from the preview
  resets it via the sticky showLoading observer.

- MayaAddressInputFragment: only drop isLoading on the quote-error
  path; a successful quote keeps Continue disabled through safeNavigate.
  onResume clears the flag when the user comes back, since this
  fragment instance survives on the back stack.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(common): persist entered address across process death

AddressInputViewModel now backs the typed address with SavedStateHandle:
saved on every setInput, restored into the initial UI state. If the OS
kills the process while an address-input screen (e.g. Maya sell flow)
is in the background, the entered address comes back on restore instead
of a blank field. The convert-amount screen already had the equivalent
via ConvertViewViewModel's saved Amount.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(maya): convert transaction result screen to Compose

Replaces the view-based maya_convert_result_fragment.xml with
MayaConvertResultScreen built from design-system components
(DashButton TintedBlue, MyTheme typography/colors), following the
UIState + ComposeView-hosting pattern of the other Maya screens.
No Figma design exists for this screen; it mirrors the old layout.

Behavior is unchanged: transaction type/outcome mapping, contact
support link, Maya/NEAR explorer link, back press blocked after
success, lock-screen pop to portal. The unused layout and its
tools:layout nav reference are removed.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(maya): extract result-screen mapping into unit-tested mapper

Moves the TransactionType/outcome -> screen content matrix and the
Maya/NEAR explorer-link classification out of MayaConvertResultFragment
into MayaConvertResultStateMapper, a pure object returning string
resource IDs and args so it runs on the JVM without a Context. The
fragment now only resolves the resources.

Adds 18 JUnit tests covering every type/outcome combination, the
deposit-error verbatim-message rule, and the explorer route
classification (uppercased txid, home-page fallbacks, MAYA-over-NEAR
precedence, unknown routes hidden).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(maya): grammar in refund address description

"a wallet you controls" -> "a wallet you control".

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(common): offer only unselected currencies in EnterAmount picker

The currency picker on the enter-amount screens used to list all
currencies with the selected one highlighted. The selected currency is
already displayed as the primary amount, so it is not a meaningful
option: the picker now shows only the currencies the user can switch
to, remapping tap indices back to the caller's full currencyCodes list
so both call sites (Maya sell convert, DEX buy enter-amount) work
unchanged.

SegmentedPicker gains an additive showSelection flag (default true):
when false it renders no thumb and no highlighted option, for pickers
whose options are alternatives rather than a persistent selection.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(maya): disclose slippage tolerance on the conversion preview

Adds a caption under the order total informing the user that the final
amount can differ from the estimate by up to the default slippage
tolerance. The percentage is formatted from
SwapKitConstants.DEFAULT_SLIPPAGE_PERCENT — the same hardcoded value
sent with quote requests — so the copy tracks the actual tolerance.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(dex): align enter-amount screens with new designs

- Buy enter-amount screen: NavBar drops its title in favor of a
  TopIntro heading "Convert Dash to <code>", where tokens are
  qualified with their host network ("USDT (Ethereum)") and native
  L1 coins show just the code ("BTC") via MayaCurrencyList.networkName.
  The sell convert screen title gets the same treatment.
- Remove the unused balance/icon parameters and state left over from
  the dropped balance card (coinIconUrl, showBalance, dashBalance,
  fiatBalance).
- Expose the locale on the buy screen content for previews and add a
  German-locale preview showing the decimal comma and trailing symbol.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(common): add Paste button to AddressField (Figma 36320:8288)

AddressField gains an optional onPasteClick: while the field is empty
a plain-blue "Paste" text button renders next to the QR icon (10dp
gap per design), disabled with the field and hidden once text is
entered. The DEX refund-address screen wires it to the existing
clipboard paste; long-press-to-paste still works.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(maya): compose order preview screen from Figma design

Rebuilds the conversion order-preview screen (Figma 24021:11223) as
MayaConversionPreviewScreen using design-system components, replacing
fragment_maya_conversion_preview.xml + content_conversion_preview_maya:

- quote countdown moves into the Confirm button ("Confirm (10s)"),
  which turns into a tinted Refresh on expiry; Cancel/Confirm sit
  side by side at the bottom
- From row gains the fiat value of the sold amount; coin rows show
  name over code; the destination address gets its own row
- keeps the slippage notice, debug route diagnostics, offline state
  (Compose port of network_unavailable_view) and all original
  behavior: breakdown currency fallback, dialogs, fee info, analytics

The ViewModel gains SavedStateHandle persistence: the displayed order
(including refreshed quotes) and the quote fetch time survive process
death, so recreation resumes the remaining validity window or lands
on the expired/Refresh state instead of restarting a full countdown.
Quick round-trips (e.g. fee info) now also resume the countdown
rather than always forcing a refresh.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(maya): restyle conversion result per Figma sheet design

Aligns MayaConvertResultScreen with Figma 34195:9065: 90dp success
icon, HeadlineMediumBold primary title (state color now carried by the
icon), TitleMedium secondary message, 60dp side paddings and a filled
blue bottom button. Success preview text updated to the design copy.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(maya): show conversion result as a full-height bottom sheet

MayaConvertResultFragment becomes a ComposeBottomSheet (forceExpand)
nav dialog destination. Success states block dismissal (the swap is
already sent; Close pops home); error states can be backed/swiped
away, popping like the old back handling.

The wallet lock screen auto-dismisses all dialogs, so the sheet is
re-shown once the lock screen goes away: LockScreenBroadcaster gains a
deactivatingLockScreen event (fired by LockScreenActivity), the
pending result params persist in the nav-graph ConvertViewViewModel's
SavedStateHandle (surviving process death), and the preview screen
re-navigates to the sheet on unlock. The record clears when the user
acknowledges the result; pressing Done also drops everything the flow
persisted (entered amount, pending result) via clearSavedState.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: ContactsFragment was blank if pressing back from SearchUserFragment

* Revert "fix: ContactsFragment was blank if pressing back from SearchUserFragment"

This reverts commit fd05118.

* feat(dex): track sell swaps via SwapKit /track and show status on home screen

Sell swaps (DASH -> other asset) are now recorded and tracked end to end:

- New swap_orders table (AppDatabase v20, entity in common, DAO in maya)
  keyed by the funding DASH txId; stores asset pair, destination, deposit
  address, expected/actual amounts and /track status
- Order inserted at broadcast in MayaConversionPreviewViewModel, with
  transaction_metadata service tagged directly (Maya vs Swapkit resolved
  from the active backend)
- SwapKit POST /track wired into SwapKitEndpoint/SwapKitWebApi;
  SwapTrackingService polls non-terminal orders every 30s, resumes on app
  start, stops when orders settle or exceed 24h. NEAR Intents routes fall
  back to tracking by deposit address when the hash lookup fails; the API
  500s while Maya swaps are in flight, so errors are logged and retried
- Home screen row: "Conversion . DASH/XXX" with a blue Processing chip
  while in flight, "Converted . DASH/XXX" when complete, plus
  Refunded/Failed states; solid convert-circle icon on the standard halo
  (halo-less Figma icon deferred to a global icon rework). Swap status
  rides through PresentableTxMetadata (now diffable by value) and the tx
  display cache

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(dex): swap icon and provider explorer link in transaction details

When the transaction funded a DEX swap, TransactionDetailsDialog now
shows the convert-circle icon and a second card under "View on block
explorer" (same button format) linking to the swap provider's tracker:
MayaChain scan by tx hash, or the NEAR Intents explorer by deposit
address, reusing MayaConvertResultStateMapper.explorerFor so both
screens stay consistent. Hidden for tx error states, since a failed
DASH tx never funded a swap.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(maya): show settlement explorer link on the conversion result sheet

The Compose result screen supported an explorer link but the fragment
never set explorerLinkText, so no link rendered at all. Now:

- Successful conversions link to the settlement network explorer:
  mayascan.org/tx/{TXID} for Maya routes, near-intents.org by deposit
  address for NEAR routes (route classified from routeName)
- Error states show the same link when a transaction was actually
  generated (txid or deposit address present), so the user can follow
  funds that already left the wallet; errors before broadcast show none
- Drop the unused ExplorerSpec.descriptionRes and its strings

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): rethrow cancellation in safeCall, concurrent route map, QR remember keys

Three fixes from the second agent review round:
- SwapKitWebApi.safeCall rethrows CancellationException instead of
  swallowing it and reporting phantom errors to analytics (same
  pattern as the H3 fix in MayaBlockchainApi)
- SwapKitApiAggregator.preferredRouteResolvedAt is a ConcurrentHashMap:
  it is written on responseScope but cleared from the caller thread
  (same pattern as the H4 usdPriceCache fix)
- DEXReceiveScreen QR remember block keys on isLoading too, so the
  bitmap recomputes when loading finishes after the address arrived
  instead of staying cached as null (permanent spinner)

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): age out swap orders unresolved after 24h to FAILED

Orders older than MAX_TRACKING_AGE_MS were silently dropped from the
poll set but left in an active status, so the home-screen row showed
a "Processing" chip forever. Now the tracking loop marks them FAILED;
since FAILED is terminal, the write also removes them from the
observed active-orders query and the loop restarts with only the
remaining live orders.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(maya): keep inline errors and the no-DASH gate across configuration changes

The convert and address-input screens held their inline error and the
"no DASH to convert" Get-quote gate in fragment fields (mutableStateOf /
plain vars), so a rotation recreated them empty:

- ConvertViewViewModel now exposes a persistent userDashAccountEmpty flag
  alongside the one-shot toast event, and the fragment derives its
  Get-quote gate from it.
- MayaConvertCryptoViewModel and MayaAddressInputViewModel hold the
  currently shown inline error; the fragments mirror every show/clear
  through a setInlineError helper and re-seed it on creation.
- The address-input observer compares against a ViewModel-held
  lastSeenAddress instead of the recreated uiState, so the replay of the
  persisted address after rotation is no longer mistaken for an edit
  that invalidates the error.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(dex): apply low-severity cleanups from the second agent review round

- Preview quote countdown: stamp quoteCreatedAt in the ViewModel when the
  refreshed quote arrives and resume the remaining window in the observer,
  so the sticky LiveData re-delivery after rotation no longer restarts a
  full countdown
- explorerFor: new emptyRouteIsMaya param; transaction details passes
  service == Maya, so a provider-less SwapKit order gets no explorer link
  instead of a guessed Maya one (with tests)
- Document that the NEAR Intents /transactions/ route accepts deposit
  addresses (verified against the explorer) in strings-maya.xml
- @volatile on poolListLastUpdated and classificationLastUpdated, both
  reset from the caller thread but written on responseScope
- DEXEnterAmountViewModel: snapshot-then-update so MutableStateFlow.update
  lambdas stay side-effect free
- Localize the DEX enter-amount display and the keypad decimal-separator
  key label (display-only param on NumericKeyboardCompose); the Maya
  convert keypad label now matches the separator its fragment inserts
- CardanoAddressParser: bounds-check the Byron CRC argument bytes so
  truncated input is rejected by require instead of the outer catch
- AddressField: route the long-press handler through rememberUpdatedState
  so pointerInput(Unit) doesn't pin the first-composition lambda

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: forget search text when leaving the DEX integration

* fix(dex): avoid nav-graph ViewModel crash when leaving buy flow to Home

DEXEnterAmountFragment.onDestroy() forced the nav-graph-scoped viewModel
lazy to resolve, which re-runs getBackStackEntry(nav_maya). When the whole
flow is popped to Home ("Back home" on the receive screen), that graph is
already off the back stack, so resolution threw IllegalArgumentException.

Capture the ViewModel in onCreateView (graph guaranteed alive) and clear
the entered amount via that captured instance in onDestroy, never touching
the lazy after teardown.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
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.

3 participants