Skip to content

merge: master (Dash DEX, about-me redesign) into kotlin-sdk-phase1 - #1525

Merged
bfoss765 merged 16 commits into
feat/kotlin-sdk-phase1from
feat/merge-kotlin-sdk-master
Aug 3, 2026
Merged

bfoss765 merged 16 commits into
feat/kotlin-sdk-phase1from
feat/merge-kotlin-sdk-master

Conversation

@HashEngineering

Copy link
Copy Markdown
Collaborator

What this is

A true merge commit (f73bf13e2, parents b6f6f2109 + d4c04952b) bringing origin/master into the Kotlin SDK phase1 line, with master's dashj/bitcoinj-based additions re-expressed on phase1's neutral (dashj-free) module APIs.

What master brought in

Conflict + auto-merge fallout resolution

Only one file had textual conflicts (SwapKitApiAggregator.kt), but ~20 more files auto-merged master's bitcoinj code into dashj-free modules. All were re-expressed on the neutral APIs, keeping master's behavior:

  • SwapKitApiAggregator: kept phase1's neutral types (FiatValue, InsufficientFundsException, string-address sendCoins); adopted master's max-sell sweep quoting, pre-broadcast sweep re-check, error mapping (errorMessageRes / isAmountTooLowError), HydratedSnapshot refactor, lastFiatExchangeRate tracking
  • SwapOrder / SwapOrderDao: keyed by neutral TxId instead of Sha256Hash; call sites fixed (conversion viewmodel, WalletTransactionMetadataProvider, TransactionResultViewModel)
  • Example-address generation (AddressGenerator, MayaCryptoCurrency): random SessionExampleKey + vendored Base58/SHA-256 replaces ECKey/Sha256Hash; BTC validation via AddressUtils.verify
  • Foreign-chain parsers (Solana/XRP/TRON/Cardano/XRD + Bech32/Zcash intent parsers): vendored Base58/AddressFormatException
  • MayaBlockchainApi stays interface-only in the maya module; master's CancellationException rethrow (double-swap guard) ported to the wallet-side impl
  • ContactsFragment: phase1's per-view ContactsIdentityGate kept; master's onDestroyView flag-reset workaround dropped as redundant
  • Misc: segwitHrp rename, currentReceiveAddressString(), AddressNetwork.fromId(networkId), LocalDashColors in SettingsScreen, OP_RETURN memo extraction in intent-parser tests

Verification

  • :common, :integrations:maya, :wallet (_testNet3Debug) compile
  • All common + maya unit tests pass, including the new 22-test example-address suite

🤖 Generated with Claude Code

HashEngineering and others added 14 commits June 16, 2026 13:22
* feat: add ComposeBottomSheet.kt

* feat: add new DashPayUserBottomSheet and connect to Contacts and SearchUserFragment.kt

* fix: avatar was defaulting to letter image

* feat: add coil compose to wallet module

* fix: use NavBarClose and fix background color

* fix: add filter to bottom sheet

* fix: update icons, adjust filter

* fix: update the received request card

* fix: text and refactor

* fix: icons in activity for sent/accept

* fix: replace DashPayUserActivity with DashPayUserBottomSheet in other places

* fix: defer finish() after showing DashPayUserBottomSheet, drop dead code

Calling Activity.finish() immediately after DashPayUserBottomSheet.show()
raced with launchWhenResumed in the sheet's show path, risking an
IllegalStateException or a silently dropped fragment commit. Post the
finish() so the fragment transaction lands first. Also remove now-unused
DashPayUserActivity/Intent imports and commented-out startActivity calls
left behind by the bottom-sheet migration.

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

* fix: more minor fixes

* fix: expand if necessary, add scrolling

* fix: don't finish() while DashPayUserBottomSheet is hosted by the activity

The bottom sheet is shown on TransactionResultActivity's own
FragmentManager, so finishing the activity right after show() tore the
sheet down with it - clicking the contact icon just closed the payment
window and revealed the main screen.

Icon click: drop the finish() entirely; dismissing the sheet returns to
the transaction result screen. Close button with contact data: defer
finish() until the sheet is dismissed via FragmentLifecycleCallbacks,
mirroring the old finish() + DashPayUserActivity flow.

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

* fix: coderabbit fixes

* fix: master-engineer findings

* fix: remove duplicate Grapper.kt causing conflicting Grabber overloads

Grapper.kt was a byte-for-byte duplicate of Grabber.kt declaring the same
Grabber composable, causing conflicting overloads and overload resolution
ambiguity errors in the common module build.

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

* fix: compile issues after merging to master

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
* feat: group transactions on DashPayUserBottomSheet

* fix: support scrolling

* fix: onDispose fix
* fix: address about-me review findings in DashPay user bottom sheet

- ProfilePictureZoomTransformation: reject malformed zoom rects up front
  instead of producing a 1px sliver
- ProfileAvatarCompose: gate username/URL logging behind BuildConfig.DEBUG;
  drop Size.ORIGINAL so Coil downsamples to the avatar bounds
- DashPayUserBottomSheet: disable the unimplemented Ignore button; notify
  the host only after the contact op succeeds; show wallet-net tx amount
  instead of the first output
- DashPayUserBottomSheetViewModel: apply Sent/Received filter to contact
  rows using the same direction logic as the row UI
- TransactionResultActivity: persist the deferred-finish flag so dismissing
  the restored bottom sheet still exits after rotation

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

* fix: ContactsFragment was blank if pressing back from SearchUserFragment

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
feat: redesign about me (dashpay user screen -> dialog)
* 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]>
…#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]>
feat: add Dash DEX as the Maya replacement
* fix(topper): resolve ANR for Topper Queries by using Dispatchers.IO

* fix(dashspend): show generated merchant-name icon for gift cards without a logo

DashSpend gift card transactions whose merchant has no logo were falling
back to the static gift card icon in the tx_display_cache. Generate a
full-name merchant icon (matching the merchant list) instead, both on the
home tx list (TxDisplayCacheService) and in the transaction details view
(TransactionResultViewBinder). Adds MerchantNameIcon to the shared
MerchantInitialIcon component and caches generated bitmaps by merchant name.

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

* fix: address some coderabbitai feedback

* fix: review fixes for crashes, gift-card cache, and PIN change

- UserLocationState: rethrow CancellationException so coroutine
  cancellation isn't swallowed by the generic catch
- MerchantsAtmsResultAdapter: capture logoLocation in a local val to
  avoid dereferencing a nullable merchant
- TxDisplayCacheService: try iconBitmapForEntry first on cold start so
  logo-less gift cards still get a generated icon when customIconId is null
- WalletTransactionMetadataProvider: persist merged gift-card values (not
  raw input) and carry redeemUrlChallenge to avoid null overwrites
- MainActivityExt: fix time-skew dialog to report minutes (abs/60)
- SecurityGuard/DualFallbackEncryptionProvider/EncryptWalletLiveData:
  remove stale fallbacks on PIN change before recreating them
- bump versionName to 11.8.2, dashj 22.0.4, dpp 4.0.0

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

* fix(identity): add missing DECRYPTION key during identity upgrade

Check hasDecryptionKey() alongside the transfer and encryption key
checks so identities missing only the DECRYPTION key are flagged for
upgrade and have it added on next sync. The dpp library now includes a
DECRYPTION key in its default key list and reuses the ENCRYPTION key
material when adding it.

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

* Revert "fix(identity): add missing DECRYPTION key during identity upgrade"

This reverts commit 77e3df97f55f550e5213d230ce5b2e8f6f1ee388.

* fix(dashpay): tolerate legacy identity-cache CBOR failure on v4.x contacts

Port the dpp-4.0.1 CBOR crash fixes from the kotlin migration branch
(51f3ec9, dff670f) instead of bumping the dpp dependency.

Accepting/receiving a contact request from an identity carrying a
contract-bound key (iOS/Rust-SDK identities) crashed inside the legacy
dashj-platform in-memory identity cache: storeIdentity CBOR-encodes the
fetched identity and throws "No converter for SingleContractDocumentType"
after a successful fetch, aborting the whole accept/receive flow.

- Add IdentityCacheTolerance.kt: pure, unit-tested helper that runs the
  cached get and, only on that specific CBOR cache failure, recovers via
  a cache-bypassing refetch. Any other error propagates unchanged.
- Add PlatformService.getContactIdentity(), wired into the send, accept,
  and receive/reconcile call sites (PlatformBroadcastService,
  PlatformSyncService).
- Never string-interpolate a legacy dashj Identity in logs: toString()
  routes through hashCode() -> CBOR toBuffer() and throws the same
  "No converter for ..." on contract-bound identities. Log the id only.

Scoped to the CBOR fix only; the migration branch's accept-vs-send error
wording UX (which depends on refactoring not present on this branch) is
intentionally excluded.

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

* test: fix MainViewModelTest compilation and stale mocks

The test had drifted from MainViewModel's constructor and init block:

- Pass the missing crowdNodeApi constructor arg (mock with signUpStatus
  and balance stubbed, needed by the CrowdNode withdrawal-reminder flow)
- Stub BlockchainIdentityConfig.observe() (BaseProfileViewModel init)
- Stub WorkManager.getWorkInfosByTagFlow (allOperationsStatus moved from
  LiveData to Flow)
- Relax TxDisplayCacheService mock (init now calls setFilter)
- Stub Configuration.isRestoringBackup and the crowdnode reminder
  saved-state key

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

* test: fix pre-existing failures in voting-delay and CSV-export tests

- GetUsernameVotingResultOperationTest assumed a 2-minute buffer after
  the voting period, but production (DELAY_AFTER_VOTING_PERIOD) has
  always been 1 minute — all 9 assertions were off by exactly 60s.
  Align the expected values and comments with the shipped formula.
- TransactionExportTest never called initMetadataMap() before
  exportString(), crashing on the lateinit metadataMap. Production
  callers (ToolsViewModel) initialize it first; do the same.

Full :wallet:test_testNet3DebugUnitTest suite now passes.

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

---------

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

* fix(topper): resolve ANR for Topper Queries by using Dispatchers.IO

* fix(dashspend): show generated merchant-name icon for gift cards without a logo

DashSpend gift card transactions whose merchant has no logo were falling
back to the static gift card icon in the tx_display_cache. Generate a
full-name merchant icon (matching the merchant list) instead, both on the
home tx list (TxDisplayCacheService) and in the transaction details view
(TransactionResultViewBinder). Adds MerchantNameIcon to the shared
MerchantInitialIcon component and caches generated bitmaps by merchant name.

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

* fix: address some coderabbitai feedback

* fix: review fixes for crashes, gift-card cache, and PIN change

- UserLocationState: rethrow CancellationException so coroutine
  cancellation isn't swallowed by the generic catch
- MerchantsAtmsResultAdapter: capture logoLocation in a local val to
  avoid dereferencing a nullable merchant
- TxDisplayCacheService: try iconBitmapForEntry first on cold start so
  logo-less gift cards still get a generated icon when customIconId is null
- WalletTransactionMetadataProvider: persist merged gift-card values (not
  raw input) and carry redeemUrlChallenge to avoid null overwrites
- MainActivityExt: fix time-skew dialog to report minutes (abs/60)
- SecurityGuard/DualFallbackEncryptionProvider/EncryptWalletLiveData:
  remove stale fallbacks on PIN change before recreating them
- bump versionName to 11.8.2, dashj 22.0.4, dpp 4.0.0

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

* fix(identity): add missing DECRYPTION key during identity upgrade

Check hasDecryptionKey() alongside the transfer and encryption key
checks so identities missing only the DECRYPTION key are flagged for
upgrade and have it added on next sync. The dpp library now includes a
DECRYPTION key in its default key list and reuses the ENCRYPTION key
material when adding it.

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

* Revert "fix(identity): add missing DECRYPTION key during identity upgrade"

This reverts commit 77e3df97f55f550e5213d230ce5b2e8f6f1ee388.

* fix(dashpay): tolerate legacy identity-cache CBOR failure on v4.x contacts

Port the dpp-4.0.1 CBOR crash fixes from the kotlin migration branch
(51f3ec9, dff670f) instead of bumping the dpp dependency.

Accepting/receiving a contact request from an identity carrying a
contract-bound key (iOS/Rust-SDK identities) crashed inside the legacy
dashj-platform in-memory identity cache: storeIdentity CBOR-encodes the
fetched identity and throws "No converter for SingleContractDocumentType"
after a successful fetch, aborting the whole accept/receive flow.

- Add IdentityCacheTolerance.kt: pure, unit-tested helper that runs the
  cached get and, only on that specific CBOR cache failure, recovers via
  a cache-bypassing refetch. Any other error propagates unchanged.
- Add PlatformService.getContactIdentity(), wired into the send, accept,
  and receive/reconcile call sites (PlatformBroadcastService,
  PlatformSyncService).
- Never string-interpolate a legacy dashj Identity in logs: toString()
  routes through hashCode() -> CBOR toBuffer() and throws the same
  "No converter for ..." on contract-bound identities. Log the id only.

Scoped to the CBOR fix only; the migration branch's accept-vs-send error
wording UX (which depends on refactoring not present on this branch) is
intentionally excluded.

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

* test: fix MainViewModelTest compilation and stale mocks

The test had drifted from MainViewModel's constructor and init block:

- Pass the missing crowdNodeApi constructor arg (mock with signUpStatus
  and balance stubbed, needed by the CrowdNode withdrawal-reminder flow)
- Stub BlockchainIdentityConfig.observe() (BaseProfileViewModel init)
- Stub WorkManager.getWorkInfosByTagFlow (allOperationsStatus moved from
  LiveData to Flow)
- Relax TxDisplayCacheService mock (init now calls setFilter)
- Stub Configuration.isRestoringBackup and the crowdnode reminder
  saved-state key

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

* test: fix pre-existing failures in voting-delay and CSV-export tests

- GetUsernameVotingResultOperationTest assumed a 2-minute buffer after
  the voting period, but production (DELAY_AFTER_VOTING_PERIOD) has
  always been 1 minute — all 9 assertions were off by exactly 60s.
  Align the expected values and comments with the shipped formula.
- TransactionExportTest never called initMetadataMap() before
  exportString(), crashing on the lateinit metadataMap. Production
  callers (ToolsViewModel) initialize it first; do the same.

Full :wallet:test_testNet3DebugUnitTest suite now passes.

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

* fix(dex): keep sell-swap tracking alive and never regress status to NOT_STARTED

A completed DASH->USDC sell swap stayed un-"Converted" in the field:
- a /track response of NOT_STARTED (tracker hadn't indexed the deposit
  yet) overwrote PENDING and stored the all-zero placeholder outbound
  hash; both are now ignored as "no information"
- the tracking collection ran once per process, so an escaped exception
  (e.g. a Room/SQLite failure under connection-pool pressure) silently
  ended tracking for the process lifetime; the loop now restarts itself
  after a poll period

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

* fix(dex): quantize buy sell-amounts to the asset's on-chain decimals

A DEX buy of 5.70167264 USDC (8 decimals for a 6-decimal token) was
registered with the NEAR Intents quote as 5.701673 (rounded up) while
the EIP-681 deposit URI truncated to 5.701672 - one base unit short of
the quote, so the whole deposit was refunded.

- MayaCryptoCurrency: authoritative per-asset `decimals` across the
  hierarchy (XRP/TRX/ADA/KUJI 6, SOL/TON/SUI 9, NEAR 24, CACAO 10,
  MAYA 4, EVM 18, UTXO 8); the stablecoin/WBTC mapping formerly local
  to MayaEthereumTokenCryptoCurrency is shared with the non-EVM token
  wrappers via tokenDecimals(). formatSwapAmount() rounds a sell
  amount DOWN to min(decimals, 8) so quote, deposit URI and actual
  transfer are always the same exact on-chain value
- buy order creation and the pre-validation quote use formatSwapAmount;
  the amount keyboard caps crypto entry at the asset's decimals and
  crypto display values round DOWN to match what gets ordered
- regression test covering the refunded field amount, URI round-trip
  and per-currency representability

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

* v11.9.0

* chore: ktlint

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: bfoss765 <[email protected]>
* chore: update branches for CI

* chore: include mappings.txt in fastlane deployment to Google Play
* fix: improve and update tools menu (phase 1)

* fix: improve and update tools menu (phase 2)

* fix: improve and update tools menu (phase 3)

* feat: support dark mode (phase 1)

* feat: support dark mode (phase 2)

* feat: support dark mode (phase 3) and update agents

* fix: merge problems

* fix: compile issues from merging

* feat: dark mode theming for components, colors, and previews

- Add the Figma base color palette as theme-independent primitives:
  MyTheme.ColorScheme companion object and palette_* color resources,
  and wire the light/dark schemes to reference them
- Snap light/dark semantic colors to their Figma values (text, background,
  brand blue, error/success, dash_black family)
- Fix the segmented picker non-selected track (use a 10% gray tint instead
  of an opaque fill) so non-selected items render correctly
- Migrate common-module Compose previews to the dual @Preview(uiMode)
  light/dark pattern wrapped in DashWalletTheme
- Make the shared dialog theme (My.Theme.Dialog) DayNight so dialogs
  follow dark mode

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

* fix: dark mode for dialogs, PIN entry, and legacy background colors

- My.Theme.Dialog: switch to DayNight parent and use background_secondary
  for the dialog window background so all BaseAlertDialogBuilder dialogs
  follow night mode
- CheckPinDialog: theme the dialog window backdrop (background_primary) and
  set the PIN card's cardBackgroundColor (CardView ignores android:background)
- 2FA keyboard card (enter_two_fa_code_fragment): apply CardViewRaised.Radius15
  so its background matches the other keyboard cards in dark mode
- colors.xml: make legacy bg_bright follow the theme (background_secondary)
  and add a dark bg_panel override; previously fixed light values
- plus assorted layout dark-mode adjustments

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

* fix: several issues of white appearing on DarkMode

* fix: several issues of white appearing on DarkMode

* fix: address about-me review findings in DashPay user bottom sheet

- ProfilePictureZoomTransformation: reject malformed zoom rects up front
  instead of producing a 1px sliver
- ProfileAvatarCompose: gate username/URL logging behind BuildConfig.DEBUG;
  drop Size.ORIGINAL so Coil downsamples to the avatar bounds
- DashPayUserBottomSheet: disable the unimplemented Ignore button; notify
  the host only after the contact op succeeds; show wallet-net tx amount
  instead of the first output
- DashPayUserBottomSheetViewModel: apply Sent/Received filter to contact
  rows using the same direction logic as the row UI
- TransactionResultActivity: persist the deferred-finish flag so dismissing
  the restored bottom sheet still exits after rotation

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

* fix: ContactsFragment was blank if pressing back from SearchUserFragment

* fix: support dark mode in newer functions

* fix: support dark mode in newer functions

* fix: address dark mode review findings

Fix confirmed issues from the dark mode review:
- MixingStatusCard: theme-aware tint for the Dash logo instead of
  hardcoded near-black, which vanished on the dark card
- BuyAndSellScreen: restore fixed white text on the always-dark
  "no connection" toast (was unreadable in light mode)
- ItemDetails: use backgroundSecondary for online-merchant details
  card instead of forced white (white-on-white in dark mode)
- ContactRequestPaneCompose, ButtonStyles.blueWithWhiteText: read
  LocalDashColors.current instead of the static light MyTheme.Colors
- fragment_dash_spend_user_auth: fixed white spinner on the
  always-blue button instead of background_secondary
- Migrate legacy layouts exposed by the DayNight theme switch:
  dash_white backgrounds to background_secondary, dash_black text to
  content_primary, dash_light_gray/dash_black hairlines to
  divider_color (invite created, payment request details, contact
  request view, accept invitation row, recover from seed, dashpay
  user, input text dialog, maya/coinbase convert views)

Audited all remaining layout XMLs across modules: every other
dash_white/dash_black use sits on a fixed-color surface (blue
buttons, red banners, dark lock/onboarding/widget backgrounds)
and is correct in both modes.

Also add paired light/dark previews wrapped in DashWalletTheme to
Settings, Tools, TransactionMetadataSettings, MasternodeKeys,
MasternodeKeyChain, About and ItemDetails screens, and fix the
WalletCreationDatePickerDialog dark preview rendering light.

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

* chore: remove obsolete ButtonStyle.kt

* fix: address dark mode code review findings

Correctness/behavior:
- ProfilePictureZoomTransformation: guard against zero-dimension input
  bitmaps (invalid coerceIn bounds) and drop the unreachable crop check
- DashModelDialog: read LocalDashColors inside DashWalletTheme so the
  dialog uses the active light/dark palette
- WalletCreationDatePickerDialog: derive year bounds from a UTC calendar
  to match the picker's UTC date range
- colors.xml (night): add bg_list_selected dark override

Theming:
- CreateInstantUsernameDialog: theme-aware background, remove stale color
  comments and unused import
- DashButton: use colors.green instead of a hardcoded literal
- ic_network_monitor: reference @color/dash_blue instead of raw hex
- PaymentsFragment / SearchHeaderAdapter: drop redundant SegmentedPicker
  style overrides that only re-passed the component defaults

API/cleanup:
- DashPayUserBottomSheet: use BundleCompat.getParcelable
- ContactsFragment: remove obsolete onActivityResult (results now arrive
  via setFragmentResultListener)
- ToolsScreen: remove duplicate ZenLedger Export menu, fix indentation
- TopIntroSend: extract shared preview scaffold
- Grabber/TopNavBase/WalletTransactionsFragment/ExtendedPublicKeyDialog:
  ktlint formatting

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

* fix: support dark mode in payment request details screen

Replace hardcoded white/black colors with theme-aware color resources
so the payment request confirmation screen renders correctly in night
mode:

- view_payment_request_details: root background dash_white ->
  background_secondary; header divider #c7c7c7 -> divider_color
- top_separator: separator body dash_white -> background_secondary
- ic_secured_by: fill #000000 -> content_primary

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

* feat: dark mode support for Dash DEX screens in maya integration

Wrap all maya ComposeView fragments in DashWalletTheme and switch every
screen from the static light palette (MyTheme.Colors) to the theme-aware
LocalDashColors.current, including the shared CoinSelect, AddressField,
SearchField and TextField components they render. Replace hardcoded
tinted-gray literals with colors.gray at 10% (DashButton's TintedGray
formula) and the halted badge's black-8% pill with colors.primary8.

Resource fixes: dialog_withdrawal_limit_info.xml drops the non-night-aware
coinbase_blue for dash_blue, and ic_swapkit_logo fills with content_primary
so the emblem stays visible on the dark Buy & Sell menu.

The QR backing box intentionally stays white in both themes so codes remain
scannable.

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

* fix: dark mode for home screen DashPay cards and progress bar track

The Join DashPay, Accept Invitation and identity-creation cards used
Button.Primary.Large.White, whose dash_white background stays white in
dark mode while the text inside goes white; switch them to the
night-aware Button.Primary.Large.Inverted (background_secondary).

PrimaryButtonTheme.Small.Grey and the progress_horizontal track both
used dash_light_gray, which has no night variant; use the translucent
extra_dark_gray_0.1 instead, matching Compose DashButton's TintedGray.
Also drop the track shape's redundant tint, which would have multiplied
against the 10%-alpha solid and made the track nearly invisible.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
* fix: accept all-uppercase bech32 addresses when scanning

BIP-173 allows a bech32 string to be all-lowercase or all-uppercase
(QR codes use upper for the denser alphanumeric mode), but the parser
regexes were lowercase-only, so scanned all-caps addresses (BTC bc1...,
kujira/maya/thor, Zcash shielded, Cardano Shelley, Radix) were
considered invalid.

- AddressParser: optional ignoreCase flag for the match regex
- Bech32AddressParser: match case-insensitively and reject mixed case
  (needed for chains without params, which never reach a decoder)
- CardanoAddressParser: case-insensitive Shelley alternative only;
  Byron Base58 stays case-sensitive
- Intent parsers normalize matched bech32 addresses to their canonical
  lowercase form before building the swap memo (Base58 forms untouched)
- Add all-caps and mixed-case vectors to both AddressParserTests,
  including the BIP-173 uppercase test vector

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

* fix: URI-prefixed swap inputs kept a leading colon in the memo address

Bech32PaymentIntentParser and EthereumPaymentIntentParser stripped only
uriPrefix.length / currency.length characters from "scheme:address"
inputs, leaving the ":" on the address that goes into the swap memo
(e.g. "=:THOR.RUNE::thor1..."). Skip the colon too, and fix Ethereum's
currency branch which matched startsWith(currency) without the colon.

Bech32 URI payloads are also normalized to canonical lowercase when
they are a valid bech32 match, same as bare scanned addresses.

Adds Bech32PaymentIntentParserTest covering the memo built from bare,
URI-prefixed, and all-uppercase inputs.

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

* fix: persist the committed swap route, not the stale preview quote (MO-983)

commitSwapTransaction refreshes the SwapKit route before broadcasting
(routeIds expire after 60s), and on NEAR Intents routes the refreshed
quote creates a new intent with a fresh one-time deposit address — the
address the transaction actually pays. The success params, the stored
SwapOrder and the marked address were still built from the pre-refresh
preview model, so swap tracking and the NEAR Intents explorer link
followed the abandoned first intent, which stays "Pending Deposit"
forever. Persist the model returned by commitSwapTransaction instead,
and log when the deposit address changed across the refresh.

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

* fix: DEX buy enter-amount title showed the swap direction reversed

The buy flow converts the selected asset into DASH, but
dex_enter_amount_title read "Convert Dash to %s". Now reads
"Convert %s to Dash".

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

* fix: quote max sell swaps for the post-fee sweep output (MO-984)

A max ("empty wallet") sell sweeps the balance and bitcoinj deducts the
miner fee from the sweep's single output, so the deposit delivers
balance − fee. The SwapKit quote, however, was requested for the full
balance, and NEAR Intents refuses any deposit below the quoted amount
("Deposited amount is less than quoted amount"), auto-refunding it
about an hour later minus a 0.001 DASH refund fee — every max sell on
a NEAR Intents route was doomed. Maya vault routes execute on whatever
arrives and were unaffected.

Quote the post-fee sweep output instead, estimated with
estimateNetworkFee(emptyWallet = true) from the current balance so the
preview quote and the pre-broadcast refresh in commitSwapTransaction
stay idempotent (the refresh passes the already-reduced amount back
in). NEAR accepts deposits above the quoted amount, so a balance that
grows before broadcast stays safe; a balance that shrinks is caught by
a new guard in buildAndSendDepositTx that aborts with a recoverable
error instead of broadcasting a deposit that can only refund.

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

* feat: show scanned all-caps bech32 addresses in lowercase in the UI

QR codes carry bech32 addresses uppercase (alphanumeric mode); the
address fields now display and store the canonical lowercase form.

- AddressParser.normalizeCase(): lowercases an all-uppercase input only
  when its lowercase form is a valid address, so case-significant forms
  (Base58, EIP-55, mixed case, URIs) pass through unchanged
- Applied at the scan / paste / clipboard-row / source-row entry points
  of MayaAddressInputFragment and DEXRefundAddressFragment; typed input
  is untouched
- Fix AddressInputResult.addressInputWithoutPrefix keeping the leading
  colon when stripping a URI scheme (same off-by-one as the intent
  parsers fixed earlier); it feeds the sell-flow quote request

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

* fix: reject non-target-chain addresses as DEX sell destinations (MO-969)

A Dash P2PKH address could be entered as the destination of a sell
swap and only fail later with a generic "Conversion failed": several
target chains validate with permissive lexical patterns that a Dash
address also satisfies. Solana was the worst offender — its parser
accepted any 32-44 char Base58 string, and a Dash address is 34 Base58
chars.

Three layers:
- SolanaAddressParser now requires the Base58 payload to decode to
  exactly 32 bytes (a raw ed25519 key), rejecting Base58Check
  addresses like Dash/Bitcoin (25-byte payload) in both exactMatch
  and findAll.
- SolanaPaymentIntentParser validates the address in its URI-prefixed
  branch too — createPaymentIntent encodes whatever it is given, so
  "solana:<dash address>" previously bypassed validation entirely.
- MayaAddressInputFragment.onContinue explicitly rejects any
  checksum-valid DASH address (on the wallet's network) as a sell
  destination before quoting, covering every target asset's parser at
  once — a Dash address is never a valid sell-swap destination.

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

* fix: crash resolving nav-graph ViewModel in onDestroy after flow pops to Home

When a completed sell swap pops the whole nav_maya graph back to the
wallet home, back-stack fragments are destroyed after the graph entry
is already gone. A restored instance whose view was never recreated
then resolves its navGraphViewModels lazy for the first time in
onDestroy and NavController.getBackStackEntry throws
IllegalArgumentException ("No destination with ID ... on the back
stack").

Capture the ViewModel in onCreateView (while the graph is guaranteed
present) and use that instance in onDestroy — the pattern
DEXEnterAmountFragment already uses. Fixes the crash in
MayaCryptoCurrencyPickerFragment and the same latent bug in
MayaConvertCryptoFragment.

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

* fix: validate URI payment payloads and gate case normalization per format

CodeRabbit review follow-ups on the DEX sell-swap fixes:

- AddressParser.normalizeCase now only rewrites inputs the parser reports
  as case-insensitive (bech32). Case-sensitive Base58 forms validated by
  pattern only (Solana, Zcash t-addresses) could otherwise have an all-caps
  corrupt address "repaired" into a different, plausible-looking one
  instead of being rejected. Composite parsers (Bitcoin, Zcash, Cardano)
  report case-insensitivity per input form.
- URI payloads (thor:/zcash:/cardano:/radix: etc.) now get the same
  exactMatch validation and lowercase canonicalization as bare addresses
  before reaching the swap memo; a valid scheme prefix no longer bypasses
  address validation, and an all-caps bech32 payload after the prefix is
  lowercased to canonical form.

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

* fix: make nav-graph ViewModel cleanup independent of view creation

The graph-scoped ViewModel was cached in onCreateView, so a restored
back-stack fragment destroyed before its view was recreated skipped the
onDestroy cleanup (stale search query / entered amount on the next
visit). Resolve the navGraphViewModels lazy directly in onDestroy under
runCatching instead: it throws only when the whole flow was already
popped to Home, where the graph scope - and the state to clear - is
gone anyway.

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

* fix: don't wipe convert amount state on configuration change

MayaConvertCryptoFragment.onDestroy() called convertViewModel.clear()
unconditionally, which also runs on a configuration change (isRemoving
false) and erased the entered amounts plus the saved-state amount the
recreated fragment was about to restore. Gate the cleanup on isRemoving,
matching MayaCryptoCurrencyPickerFragment and DEXEnterAmountFragment,
and keep the runCatching protection for the popped-to-Home case.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
…dk-master

Brings in the Dash DEX master line (#1504, #1511, #1519 sell-swap fixes,
about-me redesign) and re-expresses its dashj/bitcoinj-based additions on
the branch's neutral (dashj-free) APIs:

- SwapOrder/SwapOrderDao keyed by TxId instead of Sha256Hash
- example-address generation (AddressGenerator, MayaCryptoCurrency) on a
  random SessionExampleKey + vendored Base58/SHA-256, no ECKey
- foreign-chain parsers on vendored Base58/AddressFormatException
- MayaBlockchainApi stays interface-only; master's CancellationException
  rethrow ported to the wallet-side impl
- SwapKit aggregator: master's max-sell sweep quote + pre-broadcast
  re-check adapted to the neutral SendPaymentService/WalletDataProvider
- ContactsFragment keeps the per-view ContactsIdentityGate; master's
  onDestroyView flag-reset workaround dropped as redundant

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

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d6c0d4a6-01ba-405b-a770-2d916ef36be9

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@HashEngineering

Copy link
Copy Markdown
Collaborator Author

@coderabbitai - review this only concerning the merge changes.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

@HashEngineering Understood — I’ll review #1525 only for regressions or mistakes introduced by the merge reconciliation, excluding pre-existing changes from either parent branch.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@HashEngineering HashEngineering changed the title merge: master (Dash DEX #1504/#1511/#1519, about-me redesign) into kotlin-sdk-phase1 merge: master (Dash DEX, about-me redesign) into kotlin-sdk-phase1 Jul 30, 2026
bfoss765 pushed a commit that referenced this pull request Jul 31, 2026
…lasspath (#1530)

The phase1 branch has never had a PR, so CI first ran over this code in the
master-merge PR (#1525) and surfaced two pre-existing failures.

check (ktlintCheck) — 23 violations across three modules, all invisible until now
because the first failing task aborted the run:
- import ordering in crowdnode/maya/exploredash (19 files)
- one unused import (MayaConversionPreviewViewModel)
- two files missing a trailing newline
- one over-length line in maya's AddressParserTest; the Shelley address literal is
  split in two to fit 120 columns (verified byte-identical to the original)
Everything except the long line was applied with ktlintFormat.

build (testDebugUnitTest) — 8 of 11 uphold tests failed with
"Method getJSONObject in org.json.JSONObject not mocked". android.jar ships a stub
org.json whose methods throw under JVM unit tests; a real implementation had been
arriving transitively from org.dashj:dashj-core, whose POM pulls org.json:json at
runtime scope. Removing dashj from the uphold module took it away, and jjwt's copy
is deliberately excluded so it stays out of the APK. Added org.json as an explicit
testImplementation and corrected the now-misleading "provided by Android natively"
comment. Production code is unaffected — a device supplies org.json.

Verified: ktlintCheck clean and 118 unit tests pass across all six modules.

Co-authored-by: Claude Fable 5 <[email protected]>
…t/merge-kotlin-sdk-master

Picks up phase1's CI repair (#1530) and the post-cutover completeness work
(11.10.36 / AAR v41int11), so this branch now builds against the SDK version
phase1 expects.

Conflicts (9 across 8 files), mostly import collisions from both sides being
ktlint-formatted independently. Two were substantive:

- NotificationItemPayment: phase1 reintroduced a `* 1000` on getDate() that
  master had deliberately removed. Every other NotificationItem returns true
  epoch millis (Contact -> usernameSearchResult.date, Stub ->
  currentTimeMillis, UserAlert -> createdAt), so the multiplier would push
  payment rows ~1000x into the future in the mixed-type sort and break
  relative-time rendering. Resolved by keeping phase1's new SDK-only support
  (the txId property deriving from correctedDisplay.rowId, so a post-cutover
  row works without a dashj Transaction) on master's millis scale, with a
  comment against reintroducing it.

- maya AddressParserTest: master replaced the fabricated Cardano address with
  a real CIP-19 mainnet vector and now asserts the old one is INVALID. #1530
  had merely reformatted that literal to fit 120 columns, so master's version
  supersedes it and was taken wholesale.

Also fixes two ktlint problems this branch's earlier merge (f73bf13)
introduced, which CI never reported because the crowdnode failure aborted
ktlintCheck before reaching these modules:

- PurchaseGiftCardFragmentV2: 4 indentation violations where phase1's neutral
  FiatValue lines kept master's old indentation.
- MayaAddressInputViewModel: the AddressNetwork.fromId(...) line exceeded 120
  columns; plus vendored-import ordering in four maya parsers.

Verified: ktlintCheck clean project-wide, maya + common unit tests pass, and
:wallet:compile_testNet3DebugKotlin builds against the freshly published
0.1.0-v41int11-SNAPSHOT (238 JNI exports, both ABIs).

Co-Authored-By: Claude Fable 5 <[email protected]>
…t/merge-kotlin-sdk-master

Brings in 7 cutover-hardening commits (dabaaac..4978b29): honest first-launch
sync window, chainlock feed and idle detection, wallet.reset() no longer destroying
history, the L1 engine choice hidden above the seam, version-gated upgrade explainer,
self-sends routed via the SDK bridge, and a CBOR-crash fix in contact sync.
dashSdkVersion is unchanged at v41int11, so no SDK rebuild was needed.

Conflicts (3 files):

- MainViewModel: phase1's "make the L1 engine choice invisible above the seam"
  refactor replaced l1ShadowSyncService + cutoverCoordinator with a single
  l1SyncStatusService. Both old params had no remaining usages in the merged body,
  so they are dropped; kept l1SyncStatusService, contactRequestNotificationService
  and master's swapProvider, and matched that order in MainViewModelTest's two
  positional constructor calls. setSwapBackend (master) and
  recheckMixedFundsMigrationPrompt (phase1) are additive — both kept.
- ToolsScreen: kept the imports actually used after phase1's redesign
  (Configuration, TextAlign, ButtonData, DashWalletTheme, LocalDashColors, the
  java.util date types); dropped vectorResource and TopNavBase, now unused.

Also repairs wallet TEST sources that the PREVIOUS merge (93c68c3) left broken.
That merge was verified with :wallet:compile_testNet3DebugKotlin — main sources
only — so these never surfaced locally, and CI never reached them because its
build job fails earlier on resolving the not-yet-published v41int11 snapshot:

- WalletTransactionMetadataProviderGiftCardTest / ...ObserveTest: master's swap
  tracking added a swapOrderDao constructor parameter the tests did not pass.
- GiftCardTest: a duplicated `index = 0` named argument (both sides added it).
- MainViewModelTest: duplicated CrowdNodeApi / SignUpStatus imports.

Verified: :wallet:test_testNet3DebugUnitTest 1200 tests / 0 failures, and
ktlintCheck clean project-wide.

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

Copy link
Copy Markdown
Collaborator Author

Heads-up: this merge silently reverts a * 1000 in NotificationItemPayment.getDate()

Flagging because the resolution changes behaviour rather than just picking a side, so it should be a conscious call rather than something discovered later.

What conflicted. 88a7d7516 (post-cutover completeness) added SDK-only row support to NotificationItemPayment and, in the same edit, reintroduced a * 1000 on getDate():

// 88a7d7516
override fun getDate() = tx?.let { it.updateTime.time * 1000 } ?: (correctedDisplay!!.time * 1000)

master has the opposite, with a comment explaining why (I confirmed master's file is byte-identical to what this branch carried in):

// master
// updateTime.time is already epoch milliseconds; every other NotificationItem returns
// millis too, so the sort key and relative-time display stay consistent across types.
override fun getDate() = tx!!.updateTime.time

Why I went with master's scale. Every other row type returns true epoch millis:

Type getDate()
NotificationItemContact usernameSearchResult.date
NotificationItemStub System.currentTimeMillis()
NotificationItemUserAlert createdAt

Transaction.updateTime is a java.util.Date, so .time is already millis, and 88a7d7516's own comment describes correctedDisplay.time as "epoch-millis". Multiplying either by 1000 puts payment rows ~1000x into the future relative to contact/alert rows in the mixed-type sort, and breaks relative-time rendering ("in 55,000 years" territory). Within payment rows only, sorting still looks fine — which is probably why it wasn't noticed.

How it is resolved here (wallet/src/de/schildbach/wallet/data/NotificationItemPayment.kt:43) — phase1's new SDK-only support kept, master's scale restored:

val txId: Sha256Hash
    get() = tx?.txId ?: Sha256Hash.wrap(correctedDisplay!!.rowId)

override fun getId() = txId.toString()

// Both sources are ALREADY epoch milliseconds ... (do not reintroduce a `* 1000`)
override fun getDate() = tx?.updateTime?.time ?: correctedDisplay!!.time

The txId property and null-tx handling from 88a7d7516 are preserved in full — a post-cutover row still opens the detail dialog without a dashj Transaction.

If the * 1000 was deliberate, say so and I'll revert this hunk — but then the other three row types need the same treatment, or mixed-type ordering stays wrong. My read is that it was an accidental carry-over from the older code the SDK-only support was written against.

Not otherwise verifiable at runtime: it only manifests in mixed-type notification sort order, which the emulator smoke test I ran wouldn't surface.

🤖 Generated with Claude Code

@bfoss765 bfoss765 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed in depth (schema, cutover-machinery preservation, dashj re-introduction, local build+tests). Approving.

  • AppDatabase: lands on v21 with master's additive 20→21 migration (swap_orders + one ADD COLUMN). QA devices at v20 migrate non-destructively (display caches preserved — history stays on screen through the SDK sync); shipped v11.9 devices at v21 get a byte-identical schema hash. The divergence we feared on #1523 never existed — v20 was shared history.
  • Cutover work preserved: the PR contains 4978b2920 as a direct parent; SendCoinsTaskRunner/CutoverCoordinator/BlockchainServiceImpl/CutoverUiDataService are byte-identical to the current head, and a grep of removed lines for cutover/sync/balance/parity terms is empty.
  • No dashj re-introduction into common/features/integrations; engine choice stays below the seam.
  • Local :wallet:compile_testNet3DebugKotlin and full :wallet:test_testNet3DebugUnitTest pass. The red CI build check is the known unresolvable pinned-AAR issue inherited from the base (see PR comment thread), not a defect here.

Two doc-only nits for any follow-up, not blocking: the merge reverted IdentityCacheTolerance.kt's updated KDoc to stale text, and PlatformService.kt carries a duplicated stale KDoc block above getContactIdentity.

@bfoss765
bfoss765 merged commit 992dca4 into feat/kotlin-sdk-phase1 Aug 3, 2026
1 of 2 checks passed
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