Commit Graph

206 Commits

Author SHA1 Message Date
pezkuwichain b32f3e8d50 feat: Bitcoin native SegWit protocol primitives (Bech32, DER, BIP143, raw tx)
Phase 1 of native BTC send/receive support (native SegWit/P2WPKH only, bc1q...
addresses - Taproot and legacy/P2SH-SegWit explicitly out of scope). Hand-rolled
since no Bitcoin library exists on this project's classpath (bitcoinj/PSBT/Base58/
Bech32) - same rationale as this session's Tron work needing its own Base58Check.

- Bech32/Bech32m codec (BIP173/BIP350) + segwit address encode/decode
- DER ECDSA signature encoding with BIP62 low-S normalization
- HASH160/P2WPKH scriptPubKey construction and address<->accountId conversion
- BIP143 sighash computation and raw segwit transaction serialization

Every primitive is verified byte-for-byte against official BIP173/BIP350/BIP143
test vectors (fetched directly from github.com/bitcoin/bips at implementation
time) - see each *Test.kt's doc comment for exact vector provenance. No JDK is
available in this environment to run these locally; also cross-verified via an
independent Python transliteration of each function before committing.
2026-07-12 13:27:38 -07:00
pezkuwichain 438a4510c8 ci: pass TRONGRID_API_KEY through to the Gradle build (#13)
Isolated from the Tron feature branch so it can land on main independently -
android_build.yml is a reusable workflow pinned to @main by every caller, so a
secret it doesn't declare/pass through never reaches the build regardless of
which branch's source gets checked out.
2026-07-12 05:21:18 -07:00
pezkuwichain 32002db5da feat: send TronGrid API key on every request to raise the anonymous rate limit
Complements the retryOn429 fix - having a key means requests are far less likely to hit
the rate limit at all, rather than just retrying transparently after they do. Wired the
same way as INFURA_API_KEY/DWELLIR_API_KEY: buildConfigField read from local.properties or
CI secret, added TRONGRID_API_KEY to android_build.yml's secret passthrough (every caller
already uses secrets: inherit, so no per-workflow changes needed beyond this).
2026-07-12 05:08:22 -07:00
pezkuwichain 04c0c41a2d fix: transparently retry TronGrid calls on HTTP 429 instead of surfacing it to the user
TronGrid's public (no API key) endpoint rate-limits aggressively under normal, human-paced
usage - confirmed live during send-flow testing, where every Confirm tap (each re-running
fee estimation + broadcast) started hitting bare 429s after only a few attempts, with no
way through except retrying by hand until one happened to land outside the rate-limit window.

Added retryOn429 (exponential backoff, same shape as the existing test-only helper in
TronBalancesIntegrationTest) at the RealTronGridApi level so every call - fee estimation,
broadcast, balance reads - retries transparently. Broadcast is safe to retry on 429
specifically since it means TronGrid rejected the request before processing it, not that
the transaction may already be in flight.
2026-07-12 04:54:58 -07:00
pezkuwichain bc9087136c fix: Tron transfers signed with the wrong key (or crashed) due to missing multi-chain-encryption case
SecretsSigner.multiChainEncryptionFor() only recognized substrate accounts, standard
Ethereum accounts, and explicit per-chain override accounts. A Tron account's accountId
matches none of those (same secp256k1 scheme as Ethereum, but a different SLIP-44 derivation
path/keypair), so it fell through to null and crashed on the `!!` - found live testing the
send flow end-to-end, reproduced on every Confirm tap.

Fixing just the null case would have signed Tron transfers with the Ethereum keypair
instead of the Tron one (getMetaAccountKeypair only distinguished ethereum/substrate),
producing an invalid signature. Threaded a proper isTronBased flag through
down to mapMetaAccountSecretsToKeypair so Tron gets its own MetaAccountSecrets.TronKeypair.
2026-07-11 19:20:02 -07:00
pezkuwichain e1d199931c fix: native TRX fee estimation crashes when amount is not yet entered
TronGrid's createtransaction rejects amount=0 with a ContractValidateException.
estimateNativeFee called it unguarded (unlike the TRC-20 path, which already
wraps its dry run in runCatching), so the send screen's reactive fee loader
surfaced this as a generic "Network not responding" error whenever it ran
before the user typed an amount - found live testing the send flow end-to-end.
2026-07-11 18:08:33 -07:00
pezkuwichain 0eab8a8ea2 fix: TRC-20 balance always read 0 for never-activated holders
Trc20AssetBalance/RealTronGridApi.fetchTrc20Balance() read through
TronGrid's /v1/accounts/{address} REST endpoint - but a TRC-20 balance
lives entirely in the token contract's own storage, not the holder's
Account object. An address that has only ever received TRC-20 tokens
(never native TRX, never otherwise "activated" on-chain) has no Account
object at all, so /v1/accounts silently returns `data: []` for it
regardless of its real token balance, and the old code treated that the
same as a genuinely empty/zero account.

Found via a live test: a real wallet received 5 USDT-TRC20, the exchange
confirmed the transfer complete on-chain, but the app kept showing 0.
Independently verified live: /v1/accounts returned empty for the address,
while a direct balanceOf(address) contract call (triggerconstantcontract)
correctly returned 5000000.

Rewrote fetchTrc20Balance() to read via balanceOf(address) instead -
reuses the existing triggerConstantContract() call already used for TRC-20
transfer fee estimation, plus a new encodeBalanceOfParameters() ABI helper
alongside the existing transfer() one. Added a regression test pinned to
this exact real address/balance so this can't silently regress again.
2026-07-11 15:21:24 -07:00
pezkuwichain cf02896a58 fix: apply the chain/asset-standard label to the main balance list too
The Send/Receive/etc. network picker (NetworkFlowViewModel) already showed
"Ethereum (ERC-20)"/"Tron (TRC-20)" for a multi-chain token's per-chain rows,
but the main Assets dashboard's own expandable per-token breakdown (tap a
token like USDT to see every chain it exists on) is a completely separate
code path (TokenAssetMappers/TokenAssetViewHolder) that still showed a bare
chain name - found via a real device screenshot of that specific screen.

Moved the shared display-name-with-label logic to a public extension
(Chain.displayNameWithAssetStandard(), runtime/ext/ChainExt.kt) so both
screens build the exact same string instead of duplicating (and now
diverging) the same logic twice.
2026-07-11 14:07:59 -07:00
pezkuwichain ff7624c1ac temp: point CHAINS_URL at pending/post-fix-release, not master
wallet-util's master/main got reset to the last content the still-live
Play Store release can parse (see wallet-util repo history around
2026-07-11 - an unrelated production incident, not a regression on this
branch). master no longer serves Tron config/icons, so this branch's test
builds would silently regress to "no Tron" - not because of anything wrong
here, but because the shared config source moved out from under it.

pending/post-fix-release preserves exactly what master had before the
reset. MUST be reverted to "master" before this branch is merged - this
override should never ship.
2026-07-11 09:09:17 -07:00
pezkuwichain 07c9848118 fix: isolate per-chain/per-asset failures in ChainSyncService.syncUp()
A single malformed or not-yet-understood remote chain/asset entry used to
abort the whole sync via a plain .map{} - chainDao.applyDiff() never even
gets called, so a brand new install (empty local DB) ends up with zero
cached chains forever, i.e. a completely empty tokens list, until the
remote data or the app's parsing code changes. This is exactly what
happened in production: master's config received a batch of upstream
changes the still-live app version couldn't parse, and every fresh install
got stuck with a blank list while existing installs (which already had a
populated local DB from a prior successful sync) were unaffected.

Mirrors the same mapListNotNull + runCatching pattern already used on the
read side (ChainRegistry.currentChains) - one bad chain, or one bad asset
within an otherwise-fine chain, is now logged and skipped instead of taking
the rest of the sync down with it.
2026-07-11 08:55:56 -07:00
pezkuwichain 141d2b1f42 fix: Networks screen never showed live health/feedback for Tron's toggle
nodesHealthState() only ever looked at wssNodes(), so an HTTPS-only chain
(Tron - no wss endpoint at all) always got an empty node list here: the
enable/disable switch itself worked correctly (it reads/writes
chain.isEnabled directly, unrelated to this list), but with nothing ever
rendering underneath it, the screen looked frozen/unresponsive - this is
almost certainly why a single real toggle needed several taps to land
correctly, since there was no visible confirmation whichever tap actually
took effect.

Falls back to httpNodes() when a chain has no wss nodes, and adds a real
TronNodeHealthStateTester (GET /wallet/getchainparameters, needs no address)
instead of naively reusing EthereumNodeHealthStateTester's eth_getBalance
call, which TronGrid doesn't speak and would have always reported the node
as down regardless of its actual health.
2026-07-11 06:50:27 -07:00
pezkuwichain e055e1a84c feat: order and label per-chain token breakdown by ecosystem + standard
The per-chain list shown when picking an action (Send/Receive/Swap/Buy/Sell/
Gift) for a token that exists on multiple chains (e.g. USDT) now orders
Ethereum and Tron right after the existing Pezkuwi/Polkadot/Kusama priority
chains instead of falling into the alphabetical "everything else" bucket,
and appends a token-standard label - "(PEZ-20)"/"(ERC-20)"/"(TRC-20)" - to
disambiguate which issuance this is, since a bare chain name alone doesn't
convey that.

The label is intentionally chain-specific, not derived from Chain.Asset.Type,
since every Statemine-type chain (Polkadot AH, Kusama AH, Pezkuwi AH) shares
the same asset type but only Pezkuwi AH's issuance needs the PEZ-20 label.
2026-07-11 06:44:35 -07:00
pezkuwichain e1679367d7 fix: make Tron address backfill self-healing instead of one-shot
TronAddressBackfillMigration was gated behind a global SharedPreferences
flag ("has this migration ever run on this install") rather than checking
per-account whether a Tron keypair is actually missing. Once that flag was
set - even by a run that found nothing to fix, or partially failed - the
migration never ran again on that install, so an account that lost its Tron
keypair some other way (the cloud-backup schema gap fixed in c78b325) could
never be repaired without a fresh reinstall.

backfillIfNeeded() already does a cheap, correct per-account check (skips
instantly if the account already has a keypair, isn't SECRETS-type, has no
entropy, etc.), so there's no need for an outer one-shot gate at all - just
run it unconditionally on every app start.
2026-07-11 05:29:11 -07:00
pezkuwichain c78b325e6d fix: cloud backup schema dropped Tron address/keypair on every round trip
WalletPublicInfo/WalletPrivateInfo had no tron field at all, so any wallet
created via the (default) cloud-backup wallet creation flow, or restored
from a cloud backup, silently lost its Tron address and keypair even though
AccountSecretsFactory/SecretsMetaAccountLocalFactory derived them correctly
moments earlier - this is why TRX/USDT-TRC20 never appeared for any wallet,
new or old, confirmed via a device-side diagnostic dump of the actual DB row
(tronAddress=NULL) after a fresh wallet creation.

Also reserves (but does not wire up) solana/bitcoin fields in the same
schema, since native derivation for those doesn't exist yet - adding them
now means that work won't need another silent-drop-prone pass through this
same schema later.

Adds a regression test exercising the exact apply-diff path that lost the
data, plus tron support in the shared cloud-backup test builder DSL.
2026-07-11 04:09:34 -07:00
pezkuwichain c713ebf6b2 debug: dump all meta accounts' tronAddress/tronPublicKey presence at startup
hasAccountIn=false was observed live for the currently active account despite
every derivation/mapping code path (creation, backfill, DB->domain mapping)
tracing correctly - need to see the actual DB state per account to know
whether this is a write-time or read-time gap.
2026-07-11 02:10:00 -07:00
pezkuwichain 7f071f4821 debug: log Tron chain arrival + gate evaluation in BalancesUpdateSystem
TRX is completely absent from the Assets list even for a brand-new
wallet on a completely fresh install - ruled out per-account backfill
(fresh wallet correctly derives tronAddress) and stale per-device chain
state (fresh install, no carried-over connectionState). Need to see
empirically whether the Tron chain even reaches currentChains at all,
and if so, which of hasAccountIn/connectionState.isDisabled gates it.
2026-07-10 17:25:31 -07:00
pezkuwichain 5f5f74989a fix: enable returnDefaultValues for feature-account-impl unit tests
Log.d/Log.e added to TronAddressBackfillMigration throw 'Method ... not
mocked' in plain JVM unit tests without this - the framework's own stubs
are meant to be configured this way for exactly this case, not worked
around by avoiding Log calls in production code.
2026-07-10 16:11:15 -07:00
pezkuwichain 29395576a3 debug: add logging to Tron address backfill migration
TRX still missing on a real device after installing the backfill fix,
with no way to tell whether the migration ran, skipped, or threw for that
specific account - the migration had zero logging. Adds Log.d at every
decision point (per-account skip reason, success) plus a try-catch around
each account so one account's failure can't silently abort the whole
migration or crash app startup for everyone else.
2026-07-10 15:56:34 -07:00
pezkuwichain 634a318fdf fix: unnecessary stubbing + missing assertTrue import in Tron backfill test
@Before's preferences.getBoolean stub was never invoked by migrate()-only
tests (only migrationNeeded() reads that preference), tripping Mockito's
strict-stubs UnnecessaryStubbingException across the whole class. Moved
it into a dedicated migrationNeeded() test, matched via any() rather than
the production class's private preference-key constant (which isn't
visible here), and added the missing assertTrue import.
2026-07-10 14:24:20 -07:00
pezkuwichain d719dbe35c fix: import the invoke operator needed for KeyPairSchema { ... } builder syntax in the test 2026-07-10 13:47:34 -07:00
pezkuwichain 46f8abc04c fix: backfill Tron address for pre-existing wallets - TRX was invisible for every account created before Tron support shipped
Found via manual device testing against a real, pre-Tron production
wallet: TRX/USDT-TRC20 didn't appear anywhere in the Assets list, not
even as a zero balance - unlike every other configured chain (KSM, USDC,
ETH, BNB, AVAX, LINK all show up at 0). Root cause: MetaAccount.hasAccountIn()
gates Tron balance sync on tronAddress != null, but tronAddress is only
ever populated once, at fresh-mnemonic-creation time in
AccountSecretsFactory.metaAccountSecrets(). The migration that added the
tronPublicKey/tronAddress columns (73_74_AddTronSupport) is pure ALTER
TABLE like every other migration in this codebase - it never derived a
value for pre-existing rows. Net effect: BalancesUpdateSystem silently
skips Tron entirely for every wallet that existed before this feature
shipped, with zero error surfaced anywhere. No automated test catches
this because every automated test creates a fresh (post-Tron) account -
this is exactly the class of bug that only manual testing against a real,
aged wallet can find.

Adds TronAddressBackfillMigration: a one-time, flag-gated pass (mirroring
the existing AccountDataMigration idiom) over SECRETS-type accounts that
still hold their mnemonic entropy in SecretStoreV2 but have no TronKeypair
yet. Derives the Tron keypair via AccountSecretsFactory.chainAccountSecrets
(isEthereum=true, same BIP32/secp256k1 path Tron already uses everywhere
else) at TRON_DEFAULT_DERIVATION_PATH - the same call fresh-account
creation already makes - so a backfilled wallet ends up with byte-for-byte
the same Tron address it would have gotten had it been created today, not
a separately-reimplemented derivation. Watch-only/Ledger/Json/multisig/
proxied accounts (never had a Tron-capable mnemonic) and raw-seed imports
(no entropy) are correctly left untouched, same as they already are for
Ethereum.

Includes a dedicated unit test asserting the backfill derives the exact
same reference Tron address (TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH) that
TronDerivationTest already cross-validated against live TronGrid data for
the standard BIP39 test mnemonic - this touches real wallets' key
material, so it's pinned to a known-good vector rather than just asserting
against its own output.
2026-07-10 12:45:50 -07:00
pezkuwichain cc5d00c4ab fix: make local eq/any/argThat wrappers never return actual null
Switching eq/any/argThat to the raw org.mockito.Mockito statics did not
avoid the 'eq(...) must not be null' crash (it moved from the @Test bodies
to the shared @Before setup(), since JUnit's @Before runs before every
test and failed first there) - Mockito.eq()/any() genuinely return null
regardless of which Kotlin entry point calls them, and that null still
gets checked once it flows into a Kotlin non-null-typed parameter
downstream. Local wrappers now guarantee a non-null return instead:
eq() falls back to the real passed-in value (harmless - the matcher is
already recorded on Mockito's thread-local stack by then), any()/argThat()
return an unchecked-cast dummy, mirroring mockito-kotlin's own internal
implementation of the same helpers.
2026-07-10 10:23:56 -07:00
pezkuwichain a8d2636f66 fix: use raw org.mockito.Mockito statics instead of test_shared wrappers
Root cause of 'eq(...) must not be null' NPE: test_shared's eq()/any()/
argThat() are thin Kotlin wrappers with a declared non-null generic return
type T. Mockito.eq()/any() genuinely return null at runtime (that's how
their matcher-stack recording works) - fine when called directly from
Kotlin (a raw Java static call's return is a platform type, no null-check
inserted), but going through a Kotlin-declared wrapper whose T infers as
non-null at the call site (e.g. eq(baseUrl: String) here) gets a
compiler-inserted null-check on the wrapper's return, which then fires.

Scoped this fix to this test file only rather than touching test_shared's
shared implementation, which every other module's tests also depend on.
2026-07-10 09:36:41 -07:00
pezkuwichain fb1e0c9cf0 fix: add explicit : Unit return type to @Test functions using runBlocking
JUnit4's BlockJUnit4ClassRunner requires @Test methods to compile with a
void return type. 'fun test() = runBlocking { ... }' infers the function's
return type from the block's last expression - two of these tests ended
on a Mockito verify(...).someMethod(...) call, whose return type leaks
through as the inferred type (e.g. String, since TronGridApi.broadcastTransaction
returns String) instead of Unit, so the whole test class failed
ParentRunner validation before any test could even run. Declaring the
return type explicitly as Unit makes Kotlin discard the expression's
value (unit-coercion) rather than infer it - added to all three tests for
consistency, not just the two that were actually failing.
2026-07-10 09:05:03 -07:00
pezkuwichain c5c04807d4 ci: show full exception detail for feature-wallet-impl unit test failures
Default Gradle test logging only prints the exception class name + one
stack frame for a failing test, not its message or cause chain - that's
exactly what happened debugging RealTronTransactionServiceTest's
InvalidTestClassError just now (console showed nothing beyond the bare
exception type). Not useful for anyone hitting a real test failure in CI
without a local Gradle run to inspect the HTML report.
2026-07-10 08:34:06 -07:00
pezkuwichain 096d3d61ed fix: add missing test-shared dependency for feature-wallet-impl unit tests
RealTronTransactionServiceTest needed test-shared's Mockito helpers
(whenever/eq/any/argThat), but feature-wallet-impl never declared
testImplementation project(':test-shared') - every other module that uses
these helpers (feature-account-impl, runtime, common, etc.) already does.
Also pin two ambiguous-without-it type inferences (argThat's lambda param,
emptyMap's type args) explicitly rather than relying on the dependency fix
alone to un-cascade them.
2026-07-10 07:53:08 -07:00
pezkuwichain 9de7267a58 test: add native TRX transfer test - sign/broadcast pipeline had no coverage
RealTronTransactionService's native-TRX branch (transact/calculateFee for
TronTransactionIntent.Native) had zero automated coverage - only the TRC20
ABI encoding (Trc20TransferAbiTest) and address derivation/formatting
(TronDerivationTest, TronAddressTest) were tested. Send/transfer code
moving real funds shouldn't ship untested just because it happens to share
its sign/broadcast plumbing with an already-tested asset type.

Covers: the raw_data is hashed and signed exactly as documented (sha256,
not the raw bytes or txID), the r+s+v signature is assembled correctly
before being sent to broadcastTransaction, and - the one true security
invariant here - a TronGrid response whose txID doesn't match
sha256(raw_data) is refused before ever reaching the signer, not just
before broadcast. Also covers the native fee estimator's bandwidth-shortfall
math against the documented fallback price.

Fixture note: the raw_data_hex/txID pair here is self-consistent (computed
locally) rather than live-captured against TronGrid, unlike
Trc20TransferAbiTest's ABI vector - this class never encodes a real
TransferContract protobuf itself (see its own class doc), so what matters
is that this service correctly hashes/signs/forwards whatever raw_data
TronGrid returns, which a self-consistent fixture exercises identically.
2026-07-10 07:25:33 -07:00
pezkuwichain 55d405c3a1 fix: move TRX ahead of BTC/ETH/BNB in default token order, drop UNI's pin
New order per product spec: Pezkuwi ecosystem, DOT, KSM, USDC, TRX, BTC,
ETH, BNB, AVAX, LINK, TAO, then everything else alphabetically. UNI no
longer gets an explicit slot - it now falls into the same alphabetical
bucket as any other unlisted symbol.
2026-07-09 22:46:09 -07:00
pezkuwichain 7a60afb98f fix: cache AVD and retry emulator boot to stop balances-test CI flake
main's scheduled run has been failing most cycles since 2026-07-06 with
either a corrupted SDK package download (Error on ZipFile unknown archive)
or a plain emulator boot timeout - both manifest as adb never reaching
emulator-5554. The job never cached the AVD, so every single run re-hit
Google's SDK servers for a fresh system image download, keeping it exposed
to this exact flake on every run and every 8-hour schedule tick.

Cache the AVD (skips the download entirely once warm) and duplicate the
test-run step as a same-job retry for the residual flake (cold cache, or
a rare boot timeout even with a warm cache).
2026-07-09 21:28:46 -07:00
pezkuwichain cfaa03c2a3 Merge main: pull in dead-workflow cleanup 2026-07-09 21:22:06 -07:00
pezkuwichain 9105560a36 test: verify Ethereum USDT sync too, closing the third originally-reported gap
Adds a real EVM address for the Founder account - derived via standard
BIP44 (m/44'/60'/0'/0/0) from the same already-verified mnemonic used
for the substrate address, since no dedicated founder EVM wallet record
exists anywhere. Ethereum's USDT-ERC20 assetId isn't a fixed integer
like Substrate assets (EvmAssetsSyncService hashes the contract address
at sync time), so it's resolved dynamically via ChainAssetDao instead
of hardcoded in the JSON fixture.

This closes the loop on all 3 originally-reported symptoms from this
investigation: Tron disabled (fixed, unaffected by any revert), Pezkuwi
tokens missing (fixed - ordering bug), USDT on Polkadot AH/Ethereum
missing (Polkadot AH already covered, Ethereum added here). Ethereum
ERC20 sync uses an entirely separate mechanism (EthereumRequestsAggregator,
not Substrate's StorageSubscriptionMultiplexer) so it was likely never
actually broken by anything this session touched - this verifies that
directly instead of assuming it from code reading.
2026-07-09 19:53:32 -07:00
pezkuwichain 01effc26c9 fix: retry TronGrid 429s instead of just tolerating the flake
Public TronGrid rate-limits aggressively, and this test now runs on
every PR (plus its own 8h schedule) - a bare 429 was failing runs for
a transient, infrastructure reason unrelated to code correctness. Add
exponential backoff retry instead of treating it as an accepted flake.

Also required-status-check balances_test.yml's run-tests job on main
now that both this and the wallet-utils phantom-asset fix are confirmed
clean - it was deliberately left optional until proven, per "don't
promise gates you haven't verified."
2026-07-09 17:29:55 -07:00
pezkuwichain 54bea1234a fix: revert FullSyncPaymentUpdater's retryWhen wrapper - root cause found
Diffed the whole branch against main (the live, working Play Store
source) instead of continuing to guess from logs. Found the actual
regression: syncAsset() was changed from a suspend fun that EAGERLY
calls startSyncingBalance() (registering each asset's storage key
synchronously, during listenForUpdates()) into a plain fun returning a
lazy flow { } that only calls startSyncingBalance() once collected -
to support a retryWhen wrapper added earlier this session.

BalancesUpdateSystem.launchChainUpdaters() calls
subscriptionBuilder.subscribe(coroutineContext) - which seals the
shared per-chain subscription multiplexer - immediately after
listenForUpdates() returns, then only starts collecting the merged
result flow (which is what triggers the lazy startSyncingBalance()
calls) afterward. So every asset's key registration now races against
the seal instead of reliably happening before it, matching main's
original guaranteed ordering. Some assets win the race often enough to
look like they work; this is why the full ecosystem test - which
creates one account and races ALL of it at once - saw every asset fail,
while the older single-asset test mostly saw only HEZ fail.

Reverted to main's version: suspend syncAsset(), eager
startSyncingBalance() call, no retryWhen. Loses automatic retry of
transient full-sync failures (which the retryWhen wrapper was meant to
add), but that capability isn't worth reintroducing an ordering bug
that can silently break sync for an unpredictable subset of assets on
every chain, not just Pezkuwi's.
2026-07-09 14:44:30 -07:00
pezkuwichain ae8acb9d12 revert: NativeAssetBalance back to raw subscribe(key), typed DSL made it worse
CI proved the typed remoteStorage.subscribe DSL swap (previous commit)
was not a fix - it was a regression. All 8 assets across all 3 Pezkuwi
chains failed to sync in the follow-up test run (vs just HEZ-on-Asset-Hub
before), and the logs showed what looks like storage keys meant for
Pezkuwi Asset Hub's Assets pallet being sent to the Pezkuwi relay chain's
connection instead - some kind of cross-chain contamination introduced
by the DSL's interaction with the shared connection, not understood yet.

Reverting to the raw subscriptionBuilder.subscribe(key) form restores
the prior, narrower state: 5 of 6 assets on Pezkuwi Asset Hub sync fine,
HEZ specifically does not, and every other chain is unaffected. The
underlying HEZ bug is still open - this just stops the attempted fix
from actively making things worse while it's investigated further.
2026-07-09 13:32:17 -07:00
pezkuwichain 593fedcdd4 fix: avoid suspend call inside non-inline removeAll(predicate)
removeAll { assetDao.getAsset(...) } failed to compile ("Suspension
functions can only be called within coroutine body"). filter{} is
unambiguously inline and safe for a suspend call inside a suspend
function; pair it with the plain Collection-based removeAll(elements)
overload instead, which takes no lambda at all.
2026-07-09 12:34:02 -07:00
pezkuwichain a16c9cc5e5 ci: run balances tests on every PR, not just schedule/manual dispatch
This is what would have caught the 2026-07-09 HEZ-on-Asset-Hub silent sync
regression at PR time instead of hours into a live-app investigation after
merge. Not yet wired as a required status check - want to confirm it runs
clean on real PRs first (TronBalancesIntegrationTest has a known TronGrid
rate-limit flake that would need addressing before this can safely block
merges).
2026-07-09 12:09:23 -07:00
pezkuwichain 72a881c059 test: expand full-architecture test to cover the whole Pezkuwi ecosystem
Was HEZ-on-Asset-Hub-only. Now data-driven from wallet-utils' new
pezkuwi_assets_for_testBalance.json (TEST_ASSETS_URL), asserting every
asset - HEZ/PEZ/USDT/DOT/ETH/BTC across Pezkuwi's 3 chains - gets an
assets DB row written via a single shared BalancesUpdateSystem run, not
just one asset on one chain. Failure message lists exactly which assets
never synced, by name and chain.
2026-07-09 12:08:27 -07:00
pezkuwichain c5174d0ccf fix: NativeAssetBalance uses typed subscribe DSL, not raw key subscription
Root cause found via 4 rounds of CI diagnostics: HEZ (native asset) on
Pezkuwi Asset Hub was correctly present+enabled in the Chain domain model,
correctly dispatched to NativeAssetBalance, and its System.Account storage
key was correctly computed - but the raw subscriptionBuilder.subscribe(key)
call never actually reached the RPC connection, with zero exceptions and
zero data, while the chain's 5 other assets (all statemine-type, all using
the same SharedRequestsBuilder) synced fine. The same NativeAssetBalance
code worked correctly for every OTHER native asset on every OTHER chain
tested, ruling out a generic bug in the class.

Switched startSyncingBalance() to the typed remoteStorage.subscribe { }
DSL (metadata.system.account.observeWithRaw) - the same mechanism this
class's own subscribeAccountBalanceUpdatePoint() and PooledBalanceUpdater/
BalanceLocksUpdater already use successfully on the same busy chain
connection, instead of the raw subscriptionBuilder.subscribe(key) call
that appears to silently drop registration in that specific configuration.

Also removes the diagnostic logging added during the investigation
(BalancesUpdateSystem's per-chain balancesSync trace, FullSyncPaymentUpdater's
per-chain asset dump) - kept the one genuinely valuable permanent addition,
the "listenForUpdates() threw synchronously" error log for a previously
silent failure mode.
2026-07-09 11:53:35 -07:00
pezkuwichain 7a6b93a323 diag: trace NativeAssetBalance.startSyncingBalance() entry/key/emission
Confirmed via 3 CI runs: HEZ (native asset) is present+enabled in the runtime
Chain object for Pezkuwi Asset Hub and gets dispatched to NativeAssetBalance
without any exception, yet its System.Account subscribe request never reaches
that chain's RPC connection at all - no error logged either. This traces
exactly how far execution gets: does startSyncingBalance() even get entered,
does getRuntime()/storageKey() complete, does subscribe()'s flow ever emit.
2026-07-09 10:51:57 -07:00
pezkuwichain d7cae696c8 diag: log full/enabled asset list per chain in FullSyncPaymentUpdater
HEZ (native type, assetId 0) on Pezkuwi Asset Hub never gets a System.Account
subscription sent to the RPC at all - no exception, no log, while the other 5
statemine-type assets on the same chain sync correctly. Ruled out via code
reading: enabledAssets() default, AssetSourceRegistry dispatch, type mapping,
Room composite PK. This logs the actual chain.assets contents at the exact
point enabledAssets() is consumed, to see directly whether HEZ is present/
enabled in the runtime Chain object or silently absent before this point.
2026-07-09 10:05:42 -07:00
pezkuwichain 2bb8a4e3d0 fix: actually start BalancesUpdateSystem in the full-architecture test
First run of this test produced zero BalancesDiag output at all - not even a
single balancesSync() call for any chain. Root cause: BalancesUpdateSystem.start()
is a cold flow only ever collected by RootInteractor, which is wired to the root
Activity/ViewModel lifecycle. This bare instrumented test never launches that
Activity, so the pipeline was never started - the test's own timeout, not the
production bug, explained the failure. Now collect the same AssetsFeatureApi.
updateSystem instance directly instead of relying on app UI lifecycle.
2026-07-09 09:15:28 -07:00
pezkuwichain 4cf6cef68d fix: add missing scalars converter dependency for androidTest
TronBalancesIntegrationTest.kt uses ScalarsConverterFactory but nothing in
app/build.gradle declared it, so the app module's androidTest compilation
failed with "Unresolved reference 'scalars'" - this was never caught before
now because the emulator balances_test.yml workflow only runs on a schedule/
manual dispatch, not on every push.
2026-07-09 08:16:32 -07:00
pezkuwichain 9beb68daa2 ci: run the whole balances test package, not just BalancesIntegrationTest
Hardcoded -e class only ran one test class, silently excluding any new
integration test added to the same package (e.g. the new full-architecture
BalancesUpdateSystem test).
2026-07-09 07:53:51 -07:00
pezkuwichain 688a23ba6b fix: log and stop swallowing synchronous listenForUpdates() failures; retry NDK download in CI
BalancesUpdateSystem.launchChainUpdaters() wrapped updater.listenForUpdates() in a
try/catch that discarded synchronous exceptions with zero logging - a silent failure
point that could explain a chain's balances never syncing with no trace in logcat.

Also add a full-architecture instrumented test that persists a real watch-only
MetaAccount and polls AssetDao through the actual BalancesUpdateSystem pipeline,
instead of bypassing it like the existing BalancesIntegrationTest does.
2026-07-09 07:52:15 -07:00
pezkuwichain b3714d3b79 fix: order chain queries by rowid so Pezkuwi's chains register first
SELECT * FROM chains had no ORDER BY - SQLite gives no ordering guarantee
for that, so registration/connection order across ~98 chains was
effectively unpredictable per run. The merged chains.json lists Pezkuwi's
own chains first (wallet-utils' merge_chains()), and CollectionDiffer's
findDiff()/Room's batch insert both preserve that order on first sync, so
ordering by rowid (insertion order) makes Pezkuwi's own chains reliably
register and start connecting first/early, instead of being interleaved
unpredictably among ~90+ Nova-inherited chains where they could end up
processed dead last - observed directly: a fresh install took 45+ seconds
without a single Pezkuwi-related registration/connection attempt.

No user should wait minutes for their own wallet's native chain to even
start syncing after install, regardless of whether the eventual outcome
is correct.
2026-07-09 06:03:20 -07:00
pezkuwichain 57dbe77db3 test: add Tron balance integration test
Tron is a REST API (TronGrid), not a Substrate runtime, so it never goes
through BalancesIntegrationTest's chainRegistry-based mechanism at all -
it had zero CI coverage. This exercises the exact TronGridApi the
production app uses for balance reads, via a standalone Retrofit client
(TronGridApi isn't exposed through a public feature API for tests to
reach through the DI graph).

Test account is the mainnet Founder's Tron address, verified live via
TronGrid's public API on 2026-07-09: 3,925.23 TRX native + 625,213.92
USDT-TRC20 - substantial real balances, not a guessed or empty account.
2026-07-09 04:01:00 -07:00
pezkuwichain 1d00f78fa9 fix: isolate per-chain mapping failures in currentChains, not just register/unregister
mapChainLocalToChain() runs as a single mapList{} transform over the entire
chain list. If it throws for even one malformed row (e.g. a JSON parse
failure on the chain's `additional` blob), the whole transform throws,
killing the Eagerly-shared currentChains/chainsById flows for every chain -
permanently, since Eagerly sharing never restarts once its upstream dies.

This is the same class of bug already fixed for registerChain/unregisterChain
in the diff-processing step below, but one level upstream of it: a mapping
failure here never even reaches that per-chain isolation, since it happens
before the diff is computed at all.

Device logs on a fresh install showed exactly this shape: 8 chains (including
Pezkuwi, Pezkuwi Asset Hub, Polkadot Asset Hub) successfully completed
"Constructed runtime" within the first ~2.5 seconds, then all activity for
every remaining chain stopped completely for the rest of the session - no
crash, no battery-saver kill (confirmed off), the process simply went silent,
consistent with the shared flow dying mid-registration and never recovering.
2026-07-09 02:10:40 -07:00
pezkuwichain 99c9fd9db5 fix: don't let a transient fetch failure wipe local chains/assets
ChainSyncService.syncUp() and EvmAssetsSyncService.syncEVMAssets() both
diff a freshly-fetched remote list against everything currently stored
locally, then apply that diff unconditionally. If the remote fetch
succeeds but returns a suspiciously small or empty list (CDN hiccup,
regional network filtering, a bad publish upstream) - rather than
throwing, which retryUntilDone would catch and retry - the diff would
delete most or all of the user's chains/assets from the local DB. This
is active data loss, not a sync failure, and it self-heals on the next
good sync if we just skip applying a suspicious one instead.

Directly relevant: a user's live production install (unrelated to any
in-flight branch work) was observed with a completely empty networks
and token list after previously working fine, matching this exact
failure mode.
2026-07-08 18:21:45 -07:00
pezkuwichain fd7adec0cc fix: wrap long ktlint-violating log line from previous commit
Line exceeded the 160-char limit and had unwrapped arguments.
2026-07-08 14:01:19 -07:00
pezkuwichain 7906a20f96 fix: stop swallowed errors from silently killing balance/updater sync
StatemineAssetBalance and NativeAssetBalance's startSyncingBalance()
wrapped setup and subscription failures in runCatching{}/catch{} that
returned emptyFlow()/NoCause instead of propagating. This meant
FullSyncPaymentUpdater's retryWhen (added for the Tron fix) never
actually engaged for these asset types - a transient failure silently
and permanently stopped sync for that asset (HEZ, PEZ, USDT, DOT, ...)
with only a logcat line as evidence. Let the exceptions propagate so
the existing retry boundary can do its job.

ChainRegistry.currentChains ran registerChain()/unregisterChain() per
chain, unguarded, inside a plain (non-Supervisor) CoroutineScope and an
Eagerly-shared flow that never restarts once it dies. One bad chain row
could permanently kill sync for every chain. Isolated each chain's
register/unregister in its own runCatching, and switched the scope to
a SupervisorJob as defense in depth.

ChainUpdaterGroupUpdateSystem.runUpdaters() called getRuntime() and
built per-chain updater flows with no error boundary; callers merge
several chains' results together, so one chain's failure (e.g. a
disabled chain throwing DisabledChainException) could kill
governance/staking/crowdloan sync for every other chain in the group.
Wrapped the body in flow{} + catch to isolate failures per chain.
2026-07-08 13:54:44 -07:00