Skip to content

Commit 76f35ff

Browse files
release(runway): cherry-pick fix(assets): make mainnet-address warning non-blocking in custom token import (#47983)
- fix(assets): make mainnet-address warning non-blocking in custom token import cp-13.58.0 (#47928) ## **Description** Fixes a defect that prevented importing PulseChain (chain id 369 / `0x171`) ERC-20 tokens through the custom token import form. PulseChain is a fork of Ethereum Mainnet state, so every Mainnet token contract exists at the same address on PulseChain — which makes the extension's mainnet-address check fire for nearly every legitimate token there. ### Problem — Custom token import: blocking "Mainnet token" warning Entering any address that matches a known Ethereum Mainnet token while on a non-Mainnet network showed *"This address matches a known Ethereum Mainnet token address…"* and disabled import entirely. On PulseChain this fires for nearly every legitimate token. **Root cause:** the custom token import page (introduced in ef8fed1 / #42574, replacing the old `ImportTokensModal` deleted in a93e640 / #43712) treated the mainnet-address match as a blocking error: `handleAddressChange` early-returned after `setWarning(t('mainnetToken'))` (also suppressing on-chain autofill), and `isValid` gated submission on `!warning`. The old modal showed the same warning but **excluded it from its error gate** (`hasError()`), so import stayed possible. Stale community PR #31864 had flagged this exact PulseChain scenario but targets the deleted file. **Fix:** the warning is now non-blocking and the on-chain lookup continues, so symbol/decimals autofill from the selected network (on a fork chain the contract at that address is real and answers correctly). The warning banner still renders to caution users who are genuinely on the wrong network. Compared to the old modal (which cleared/hid symbol+decimals under the warning), autofill gives the user real on-chain data to review before submitting. **dApp `wallet_watchAsset` path:** verified working on current builds; the reported `Unauthorized` was not reproducible (see investigation). ## **Changelog** CHANGELOG entry: Fixed a bug that blocked custom token imports on chains that forked Ethereum Mainnet (such as PulseChain) whenever the token address matched a known Ethereum Mainnet token ## **Related issues** Fixes: [ASSETS-4371](https://consensyssoftware.atlassian.net/browse/ASSETS-4371) (Jira) ## **Manual testing steps** **Setup:** run a dev/test build, then add PulseChain as a custom network (RPC `https://rpc.pulsechain.com`, chain id `369`, ticker `PLS`) and select it. Use a wallet funded on PulseChain, or any wallet — a zero balance is fine. **Custom token import path:** 1. On the home screen, open the token list options (⋯) → *Manage tokens* → *Add a custom token*. 2. Enter a known Mainnet token address, e.g. DAI `0x6B175474E89094C44Da98b954EedeAC495271d0F` or USDC `0xA0b86991C6218b36C1D19D4a2e9EB0cE3606eB48`. 3. Verify the yellow "This address matches a known Ethereum Mainnet token address…" warning appears. 4. Verify symbol and decimals still autofill from PulseChain (e.g. USDC → symbol `USDC`, decimals `6`) and that the import button is **enabled**. 5. Submit and verify the token appears in the token list on PulseChain. 6. Repeat on Ethereum Mainnet with the same address and verify no warning shows. ### Automated E2E coverage New and extended Selenium E2E coverage (local Anvil chain `0x539`, MV3 test build, [1391a9c](1391a9cf5dd)). Both specs were run on **two builds**: `origin/main` (fix reverted, tests kept) and this branch — same spec files, same commands. | Test | `origin/main` | This branch | | --- | --- | --- | | `import-custom-token-mainnet-address.spec.ts` — mainnet warning shown, import button enabled, token listed | ❌ **Fails**: warning renders, then `TimeoutError: Waiting for element to be located By(css selector, [data-testid="custom-token-import-submit-button"]:not([disabled])) — Wait timed out after 10033ms` (import stays blocked — this is the bug) | ✅ **Passes 3/3**: warning renders, import enabled, token imported and listed as `100 DAI` | | `watch-asset-call-add-token.spec.ts` (new mainnet-listed-address case) — dapp `wallet_watchAsset` approved, token added | ✅ **Passes 2/2** (all 4 cases in the spec green) | ✅ **Passes 3/3** (all 4 cases green) | Exact commands (identical on both builds; `yarn build:test` rebuilt per tree): ```sh yarn test:e2e:single test/e2e/tests/tokens/import-custom-token-mainnet-address.spec.ts --browser=chrome yarn test:e2e:single test/e2e/tests/tokens/watch-asset-call-add-token.spec.ts --browser=chrome ``` On the `origin/main` run, the branch's spec files were overlaid unmodified before building (`git checkout origin/main` then `git checkout fm/assets-4371-pulsechain-tokens -- <spec/helper/page-object files>`), so main was tested against the exact same tests with only the product fix absent. - **`test/e2e/tests/tokens/import-custom-token-mainnet-address.spec.ts`** (new): deploys the test ERC-20 with DAI metadata and moves its code + storage — including the mapping-derived balance entry — to the Mainnet DAI address with `anvil_setCode`/`anvil_setStorageAt`, so a *real* contract lives at a `STATIC_MAINNET_TOKEN_LIST` address on a non-Mainnet network. That is the exact PulseChain situation (a fork chain reusing Mainnet addresses). Asserts: (a) the mainnet warning is displayed, (b) the import button is **enabled**, (c) the token (`100 DAI`) is listed after import. - Fails on `origin/main`: after the warning renders, the spec times out waiting for `[data-testid="custom-token-import-submit-button"]:not([disabled])` — import stays blocked. - Passes on this branch: 3/3 local runs. - **`test/e2e/tests/tokens/watch-asset-call-add-token.spec.ts`** (new case): the same Mainnet-listed address offered through `wallet_watchAsset` from the test dapp on the non-Mainnet local chain; after approval the token is added (`100 DAI`). This case **also passes on `origin/main`** (2/2 runs) — kept as regression coverage, and it confirms the mainnet-address check is **not** what breaks the dApp watchAsset path; the reported dApp failure was not reproducible on current builds. - Page-object additions in `custom-token-import-page.ts` (`enterTokenAddress`, `submitTokenImport`, `checkMainnetAddressWarningIsDisplayed`, `checkImportButtonIsEnabled`); the chain setup lives in `test/e2e/tests/tokens/mainnet-listed-token.helpers.ts`. Each spec was run 3× locally with no flakes. ## **Screenshots/Recordings** Before (origin/main) vs. after (this branch) — live runs on real PulseChain RPC (chain 369) with the DAI Mainnet address (`0x6B17...1d0F`), a real contract on PulseChain: | Before (main): Save disabled | 1. Address entered | 2. Warning + autofill, Save enabled | 3. Added toast | 4. Home token list | | --- | --- | --- | --- | --- | | <img src="https://github.com/user-attachments/assets/8961ba7c-15dc-4af0-8a36-7df0343a67fd" width="220" alt="origin/main: custom token import on PulseChain with DAI address, warning shown, Save disabled"> | <img src="https://github.com/user-attachments/assets/693e9eae-d9e3-48eb-a412-16716b18f66c" width="220" alt="Custom token import form on PulseChain with the DAI address typed"> | <img src="https://github.com/user-attachments/assets/2142cb69-d4dc-4e6c-8d7c-68e92e341fcd" width="220" alt="Mainnet warning shown plus DAI symbol and 18 decimals autofilled, Save enabled"> | <img src="https://github.com/user-attachments/assets/bbb80a15-b11b-4776-a8e4-bcc4c63f25cc" width="220" alt="Success toast: USDC was successfully added, DAI and USDC listed on PulseChain"> | <img src="https://github.com/user-attachments/assets/3fb5bf75-af15-41f9-a522-a3a7254a8a77" width="220" alt="Home tokens tab on PulseChain listing PLS, DAI, and USDC"> | Evidence from the full E2E run on a local MV3 test build (`mm` CLI): - **Import form**: with the USDC Mainnet address pasted on PulseChain, the Mainnet-address warning is shown **and** symbol/decimals autofill from the chain (`USDC` / `6`), with the submit button enabled. ### **Video walkthrough** https://github.com/user-attachments/assets/a2385674-9d46-4ce8-8ec1-b0f2fadfabae > 🤖 AI-generated walkthrough — script, animation, and voice made by an agent ## **Pre-merge author checklist** - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and MetaMask Extension Coding Standards - [x] I've completed the PR template to the best of my ability - [x] I've included tests if applicable - [x] I've documented my code using JSDoc format if applicable - [x] I've applied the right labels on the PR (see labeling guidelines). Not required for external contributors. ## **Adversarial review (adverse)** The change was reviewed with a three-round multi-perspective adversarial review loop (auditor / adversary / pragmatist, cross-examination, deterministic synthesis). Round 1: **SHIP-WITH-CAVEATS** (0 critical · 6 warning · 6 info, 3/3 ship). Round 2: **SHIP-WITH-CAVEATS** (0 critical · 6 warning · 7 info). Round 3: **SHIP-WITH-CAVEATS** (0 critical · 6 warning · 7 info; 2 conditional + 1 approve). No critical or blocking findings in any round; rounds 2 and 3 converged on the same trade-off discussion. **Scope note:** rounds 1–3 reviewed a superset of this diff that also decoupled the dApp `wallet_watchAsset` persist; that change was **removed at review** ([2645a3a](2645a3a9c71)) as unproven against the user-reported failure. Findings and dispositions are kept for the record: **Addressed in code:** - *Dropping `!warning` unblocks every future warning, not just the mainnet one* (consensus, round 1) → applied in rounds 1–3 as a rename to a dedicated `mainnetWarning` state; **reverted during human review** ([534cdbb](534cdbb50eb)) to keep the diff minimal — the original `warning` state/prop names are kept and blocking conditions continue to use the error states that still gate submission. - *Rejection path's only observable behavior (Sentry) untested* (consensus, round 1) → `captureException` was mocked and asserted in the controller test — *change removed at review* ([2645a3a](2645a3a9c71)). - *Test data mislabeled DAI as symbol 'APE'* (round 1) → the test now stubs DAI-accurate on-chain metadata, and additionally asserts the warning clears when the address changes to a non-mainnet token and reappears for the mainnet one. - *Failure report lacks context / hard to group* (rounds 2–3) → `{ extra: { assetId, chainId } }` was added so triage could correlate failures without attaching account or origin identifiers; **reverted during human review** ([534cdbb](534cdbb50eb)) to shrink the diff, and the whole change was then **removed at review** ([2645a3a](2645a3a9c71)). **Answered with source evidence (no change needed):** - *"Asset may be absent from state right after the promise resolves"* (rounds 2–3, on the removed change) → `AssetsController.addCustomAsset` persists `customAssets`/`assetsInfo`/zero-balance **synchronously, before its first `await`** (the account refresh). The persist therefore completes during the call itself, before `handleWatchAssetRequest` resolves; the token is in state and renderable at that point. The only resolve-without-persist path is a synchronous throw before the state update — pre-validated inputs (`toAssetId` construction, decimals bounds) make that a narrow unexpected-error window, and it is reported to Sentry. - *"Failures leave no local trace / Sentry is consent-gated"* (rounds 2–3, on the removed change) → `shared/lib/sentry` `captureException` unconditionally `console.error`s the exception locally (the Sentry *upload* is the consent-gated part), so a service-worker console breadcrumb always exists. - *"Stale async address lookup can set the mainnet warning for a different address"* (round 2) → the handler bumps an `addressLookupRef` and checks `isLatestLookup()` **after the awaited chain probe and before every validation branch**, including the mainnet-warning one; stale lookups return early. - *"Autofill on fork chains lets attackers spoof trusted mainnet identities"* (rounds 1–3, repeatedly challenged by co-reviewers) → autofill metadata comes from the **selected network's contract**, not the mainnet list; on any custom network a user could already import an arbitrary contract with a typed symbol, and fiat-value lookups in the wallet are keyed by chain-scoped asset ids, not bare addresses. The warning banner still displays. **Accepted as documented trade-offs / follow-ups:** - *(removed change)* The fire-and-forget decoupling changed `wallet_watchAsset`'s resolution semantics from "pipeline finished" to "approved and persisted; enrichment continues in the background". A bounded-timeout alternative was considered and rejected: it would add arbitrary latency to healthy chains and still swallow the failure after the timeout. EIP-747's boolean result indicates the request was handled — a dApp cannot rely on balance data being present in any case, since enrichment timing was always chain-dependent. - The underlying fragility (no per-request timeout in the custom-network RPC client; `addCustomAsset` coupling persist with a full account refresh; no data-source support for chains like 369) was the working hypothesis behind the removed change; the dApp path was verified working on current builds and the reported failure was not reproducible. - The advisory banner's copy (`mainnetToken` message) still reads as cautionary advice and may deserve a copy pass for the now-advisory context. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > UI validation tweak on custom token import with unit and E2E coverage; no auth, payments, or persistence logic changes beyond allowing submit when only the advisory warning is set. > > **Overview** > On **custom token import**, an address that matches a known Ethereum Mainnet token on a **non-Mainnet** network (e.g. PulseChain) no longer blocks submission. The yellow mainnet warning still shows, but validation continues so symbol/decimals autofill from the selected chain runs and the import button can stay enabled when other checks pass. > > **Product change** in `custom-token-import.tsx`: after setting the mainnet warning, `handleAddressChange` no longer early-returns, and `isValid` no longer requires `!warning`. > > **Tests**: unit cases for warning on/off-network and enabled submit; E2E that deploys an ERC-20 at the Mainnet DAI address on a local chain (fork-style setup), asserts warning + enabled import + listed balance; page-object helpers; an extra `wallet_watchAsset` E2E case for the same address pattern. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 382a2a3. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> [ASSETS-4371]: https://consensyssoftware.atlassian.net/browse/ASSETS-4371?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ [9f80e4c](9f80e4c) [ASSETS-4371]: https://consensyssoftware.atlassian.net/browse/ASSETS-4371?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ Co-authored-by: Prithpal Sooriya <prithpal.sooriya@gmail.com>
1 parent 82cc434 commit 76f35ff

6 files changed

Lines changed: 359 additions & 8 deletions

File tree

‎test/e2e/page-objects/pages/token-management/custom-token-import-page.ts‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ class CustomTokenImportPage {
2121

2222
private readonly driver: Driver;
2323

24+
private readonly mainnetAddressWarning =
25+
'[data-testid="custom-token-import-mainnet-warning"]';
26+
2427
private readonly networkSelector = '[data-testid="network-selector"]';
2528

2629
private readonly pageSelector = '[data-testid="custom-token-import-page"]';
@@ -35,24 +38,44 @@ class CustomTokenImportPage {
3538
this.driver = driver;
3639
}
3740

41+
async checkImportButtonIsEnabled(): Promise<void> {
42+
console.log('Check that the custom token import button is enabled');
43+
await this.driver.waitForSelector(this.submitButtonEnabled);
44+
}
45+
46+
async checkMainnetAddressWarningIsDisplayed(): Promise<void> {
47+
console.log('Check that the Mainnet token address warning is displayed');
48+
await this.driver.waitForSelector(this.mainnetAddressWarning);
49+
}
50+
3851
async checkPageIsLoaded(): Promise<void> {
3952
console.log('Check that the Add Custom Token page is loaded');
4053
await this.driver.waitForSelector(this.pageSelector);
4154
}
4255

56+
async enterTokenAddress(tokenAddress: string): Promise<void> {
57+
console.log(`Enter custom token address ${tokenAddress}`);
58+
// Product clears the form whenever selectedNetwork changes
59+
// (custom-token-import.tsx:423-428). Wait for the network picker and
60+
// address input to settle, then fill once — do not retry typing.
61+
await this.driver.waitForElementToStopMoving(this.networkSelector);
62+
await this.waitForAddressInputStable();
63+
await this.driver.fill(this.addressInput, tokenAddress);
64+
}
65+
4366
async goBackToHomepage(): Promise<void> {
4467
console.log('Go back to homepage from the Add Custom Token page');
4568
await this.driver.clickElement(this.backButton);
4669
}
4770

4871
async importToken(tokenAddress: string): Promise<void> {
4972
console.log(`Import custom token at address ${tokenAddress}`);
50-
// Product clears the form whenever selectedNetwork changes
51-
// (custom-token-import.tsx:423-428). Wait for the network picker and
52-
// address input to settle, then fill once — do not retry typing.
53-
await this.driver.waitForElementToStopMoving(this.networkSelector);
54-
await this.waitForAddressInputStable();
55-
await this.driver.fill(this.addressInput, tokenAddress);
73+
await this.enterTokenAddress(tokenAddress);
74+
await this.submitTokenImport();
75+
}
76+
77+
async submitTokenImport(): Promise<void> {
78+
console.log('Submit the custom token import');
5679
await this.driver.waitForSelector(this.submitButtonEnabled);
5780
await this.driver.clickElement(this.submitButton);
5881
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { withFixtures } from '../../helpers';
2+
import { DEFAULT_FIXTURE_ACCOUNT } from '../../constants';
3+
import { login } from '../../page-objects/flows/login.flow';
4+
import HomePage from '../../page-objects/pages/home/homepage';
5+
import TokensTab from '../../page-objects/pages/home/tokens-tab';
6+
import CustomTokenImportPage from '../../page-objects/pages/token-management/custom-token-import-page';
7+
import TokenManagementPage from '../../page-objects/pages/token-management/token-management-page';
8+
import FixtureBuilderV2 from '../../fixtures/fixture-builder-v2';
9+
import {
10+
deployErc20AtMainnetListedAddress,
11+
MAINNET_LISTED_TOKEN_ADDRESS,
12+
MAINNET_LISTED_TOKEN_MINTED_AMOUNT,
13+
MAINNET_LISTED_TOKEN_SYMBOL,
14+
} from './mainnet-listed-token.helpers';
15+
16+
describe('Import a Mainnet-listed token address on a non-Mainnet network', function () {
17+
it('shows the mainnet warning, keeps the import enabled, and adds the token', async function () {
18+
await withFixtures(
19+
{
20+
fixtures: new FixtureBuilderV2().build(),
21+
title: this.test?.fullTitle(),
22+
},
23+
async ({ driver, localNodes }) => {
24+
// Put a real DAI ERC-20 at the Mainnet DAI address on the local chain
25+
// (0x539), mirroring fork chains like PulseChain where every Mainnet
26+
// token lives at its Mainnet address.
27+
await deployErc20AtMainnetListedAddress(
28+
localNodes[0],
29+
DEFAULT_FIXTURE_ACCOUNT,
30+
);
31+
32+
// The deployment spends gas from the Anvil account the wallet uses,
33+
// so its native balance no longer matches the fixture's.
34+
await login(driver, { localNode: localNodes[0] });
35+
36+
const homePage = new HomePage(driver);
37+
await homePage.checkPageIsLoaded();
38+
39+
const tokensTab = new TokensTab(driver);
40+
await tokensTab.clickTokenOptionsButton();
41+
await tokensTab.clickManageTokens();
42+
43+
const tokenManagementPage = new TokenManagementPage(driver);
44+
await tokenManagementPage.checkPageIsLoaded();
45+
await tokenManagementPage.clickAddCustomToken();
46+
47+
const customTokenImportPage = new CustomTokenImportPage(driver);
48+
await customTokenImportPage.checkPageIsLoaded();
49+
await customTokenImportPage.enterTokenAddress(
50+
MAINNET_LISTED_TOKEN_ADDRESS,
51+
);
52+
53+
await customTokenImportPage.checkMainnetAddressWarningIsDisplayed();
54+
await customTokenImportPage.checkImportButtonIsEnabled();
55+
56+
await customTokenImportPage.submitTokenImport();
57+
58+
await tokenManagementPage.checkPageIsLoaded();
59+
await tokenManagementPage.checkSuccessToastIsDisplayed();
60+
await tokenManagementPage.goBackToHomepage();
61+
62+
await homePage.checkPageIsLoaded();
63+
await tokensTab.checkExpectedTokenBalanceIsDisplayed(
64+
MAINNET_LISTED_TOKEN_MINTED_AMOUNT,
65+
MAINNET_LISTED_TOKEN_SYMBOL,
66+
);
67+
},
68+
);
69+
});
70+
});
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import { keccak256, pad, toHex } from 'viem';
2+
import type { Anvil } from '../../seeder/anvil';
3+
import {
4+
contractConfiguration,
5+
SMART_CONTRACTS,
6+
} from '../../seeder/smart-contracts';
7+
8+
type Hex = `0x${string}`;
9+
10+
/** DAI on Ethereum Mainnet — present in STATIC_MAINNET_TOKEN_LIST. */
11+
export const MAINNET_LISTED_TOKEN_ADDRESS: Hex =
12+
'0x6b175474e89094c44da98b954eedeac495271d0f';
13+
14+
export const MAINNET_LISTED_TOKEN_SYMBOL = 'DAI';
15+
export const MAINNET_LISTED_TOKEN_MINTED_AMOUNT = '100';
16+
17+
const TOKEN_NAME = 'Dai Stablecoin';
18+
const TOKEN_SYMBOL = 'DAI';
19+
const TOKEN_DECIMALS = 18;
20+
const MINTED_AMOUNT = 100;
21+
22+
/**
23+
* Flat storage slots copied from the deployed replica to the Mainnet-listed
24+
* address: token metadata (name, symbol, decimals, total supply) and the
25+
* mapping base slots.
26+
*/
27+
const FLAT_STORAGE_SLOTS_TO_COPY = 12;
28+
29+
/**
30+
* Deploys the test ERC-20 (HST) with DAI metadata on the local node, then
31+
* moves its code and storage — including the account's mapping-derived
32+
* balance entry — to `MAINNET_LISTED_TOKEN_ADDRESS` with `anvil_setCode` and
33+
* `anvil_setStorageAt`. The local chain (a non-Mainnet network) then carries a
34+
* real ERC-20 at an address that is in `STATIC_MAINNET_TOKEN_LIST`, which is
35+
* the situation fork chains like PulseChain create for every Mainnet token.
36+
*
37+
* @param localNode - The running local Anvil node.
38+
* @param accountAddress - Address whose token balance is carried over to the
39+
* Mainnet-listed address (the extension's wallet account).
40+
*/
41+
export async function deployErc20AtMainnetListedAddress(
42+
localNode: Anvil,
43+
accountAddress: string,
44+
): Promise<void> {
45+
const { walletClient, publicClient, testClient } = localNode.getProvider();
46+
const hst = contractConfiguration[SMART_CONTRACTS.HST];
47+
const account = accountAddress as Hex;
48+
49+
const deployer = (await walletClient.getAddresses())[0] as Hex;
50+
const deployHash = await walletClient.deployContract({
51+
abi: hst.abi,
52+
account: deployer,
53+
args: [MINTED_AMOUNT, TOKEN_NAME, TOKEN_DECIMALS, TOKEN_SYMBOL],
54+
bytecode: hst.bytecode as Hex,
55+
});
56+
await testClient.mine({ blocks: 1 });
57+
const receipt = await publicClient.getTransactionReceipt({
58+
hash: deployHash,
59+
});
60+
const replicaAddress = receipt.contractAddress as Hex;
61+
62+
const code = await publicClient.getCode({ address: replicaAddress });
63+
if (!code) {
64+
throw new Error('HST replica deployment produced no code to copy');
65+
}
66+
await testClient.setCode({
67+
address: MAINNET_LISTED_TOKEN_ADDRESS,
68+
bytecode: code,
69+
});
70+
71+
for (let slot = 0; slot < FLAT_STORAGE_SLOTS_TO_COPY; slot++) {
72+
const value = await publicClient.getStorageAt({
73+
address: replicaAddress,
74+
slot: toHex(slot),
75+
});
76+
if (value === undefined || BigInt(value) === 0n) {
77+
continue;
78+
}
79+
await testClient.setStorageAt({
80+
address: MAINNET_LISTED_TOKEN_ADDRESS,
81+
index: slot,
82+
value,
83+
});
84+
}
85+
86+
// ERC-20 balances and allowances live at keccak256(pad(account) . pad(slot))
87+
// off each mapping base slot, so the constructor-minted balance is copied by
88+
// mirroring the account's derived entries as well.
89+
for (let slot = 0; slot < FLAT_STORAGE_SLOTS_TO_COPY; slot++) {
90+
const derivedIndex = keccak256(
91+
`0x${pad(account, { size: 32 }).slice(2)}${pad(toHex(BigInt(slot)), {
92+
size: 32,
93+
}).slice(2)}`,
94+
);
95+
const value = await publicClient.getStorageAt({
96+
address: replicaAddress,
97+
slot: derivedIndex,
98+
});
99+
if (value === undefined || BigInt(value) === 0n) {
100+
continue;
101+
}
102+
await testClient.setStorageAt({
103+
address: MAINNET_LISTED_TOKEN_ADDRESS,
104+
index: derivedIndex,
105+
value,
106+
});
107+
}
108+
}

‎test/e2e/tests/tokens/watch-asset-call-add-token.spec.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
DAPP_URL,
3+
DEFAULT_FIXTURE_ACCOUNT,
34
LOCALHOST_NETWORK_CLIENT_ID,
45
SECOND_NODE_NETWORK_CLIENT_ID,
56
WINDOW_TITLES,
@@ -11,6 +12,12 @@ import AddTokenConfirmation from '../../page-objects/pages/confirmations/add-tok
1112
import TokensTab from '../../page-objects/pages/home/tokens-tab';
1213
import TestDapp from '../../page-objects/pages/test-dapp';
1314
import { login } from '../../page-objects/flows/login.flow';
15+
import {
16+
deployErc20AtMainnetListedAddress,
17+
MAINNET_LISTED_TOKEN_ADDRESS,
18+
MAINNET_LISTED_TOKEN_MINTED_AMOUNT,
19+
MAINNET_LISTED_TOKEN_SYMBOL,
20+
} from './mainnet-listed-token.helpers';
1421

1522
describe('Add token using wallet_watchAsset', function () {
1623
const smartContract = SMART_CONTRACTS.HST;
@@ -138,4 +145,51 @@ describe('Add token using wallet_watchAsset', function () {
138145
},
139146
);
140147
});
148+
149+
it('adds a token at a Mainnet-listed address when the dapp is on a non-Mainnet network', async function () {
150+
await withFixtures(
151+
{
152+
dappOptions: { numberOfTestDapps: 1 },
153+
fixtures: new FixtureBuilderV2()
154+
.withPermissionControllerConnectedToTestDapp()
155+
.build(),
156+
title: this.test?.fullTitle(),
157+
},
158+
async ({ driver, localNodes }) => {
159+
// Put a real DAI ERC-20 at the Mainnet DAI address on the local chain
160+
// (0x539), mirroring fork chains like PulseChain where every Mainnet
161+
// token lives at its Mainnet address.
162+
await deployErc20AtMainnetListedAddress(
163+
localNodes[0],
164+
DEFAULT_FIXTURE_ACCOUNT,
165+
);
166+
167+
// The deployment spends gas from the Anvil account the wallet uses,
168+
// so its native balance no longer matches the fixture's.
169+
await login(driver, { validateBalance: false });
170+
171+
const testDapp = new TestDapp(driver);
172+
await testDapp.openTestDappPage();
173+
await testDapp.checkPageIsLoaded();
174+
175+
await testDapp.requestWatchErc20Asset({
176+
address: MAINNET_LISTED_TOKEN_ADDRESS,
177+
decimals: 18,
178+
symbol: MAINNET_LISTED_TOKEN_SYMBOL,
179+
});
180+
await driver.switchToWindowWithTitle(WINDOW_TITLES.Dialog);
181+
182+
const addTokenConfirmation = new AddTokenConfirmation(driver);
183+
await addTokenConfirmation.checkPageIsLoaded();
184+
await addTokenConfirmation.confirmAddToken();
185+
186+
await driver.switchToWindowWithTitle(
187+
WINDOW_TITLES.ExtensionInFullScreenView,
188+
);
189+
await new TokensTab(driver).checkTokenAmountIsDisplayed(
190+
`${MAINNET_LISTED_TOKEN_MINTED_AMOUNT} ${MAINNET_LISTED_TOKEN_SYMBOL}`,
191+
);
192+
},
193+
);
194+
});
141195
});

0 commit comments

Comments
 (0)