Skip to content

Commit

Permalink
♻️ e2e: use mock connector
Browse files Browse the repository at this point in the history
  • Loading branch information
jgalat committed Sep 22, 2023
1 parent 0389852 commit 3895ef9
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 35 deletions.
4 changes: 2 additions & 2 deletions e2e/fixture/actions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Address, parseEther, parseUnits, type WalletClient, type PublicClient } from 'viem';
import { Address, parseEther, parseUnits, type PublicClient, type WalletClient } from 'viem';

import { erc20, erc20Market, ethRouter, auditor, ERC20TokenSymbol, Coin } from '../utils/contracts';
import { erc20, erc20Market, ethRouter, auditor, type ERC20TokenSymbol, type Coin } from '../utils/contracts';

const MaxUint256 = 2n ** 256n - 1n;
const WeiPerEther = 10n ** 18n;
Expand Down
26 changes: 14 additions & 12 deletions e2e/fixture/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import {
http,
} from 'viem';
import { privateKeyToAccount, generatePrivateKey } from 'viem/accounts';
import { Chain, optimism } from 'viem/chains';
import * as fs from 'fs/promises';
import { optimism, type Chain } from 'viem/chains';

import { type Tenderly, tenderly } from '../utils/tenderly';
import actions, { Actions } from './actions';
Expand All @@ -25,14 +24,14 @@ const defaultOptions = {
marketView: 'advanced',
} as const;

export const chain: Chain = optimism;

type TestParams = {
chain?: Chain;
privateKey?: Address;
options?: Options;
};

const defaultTestParams = {
chain: optimism,
privateKey: generatePrivateKey(),
options: defaultOptions,
} as const;
Expand All @@ -49,12 +48,17 @@ type TestProps = {
setup: Actions;
};

declare global {
interface Window {
e2e: { rpc: string; chainId: number; privateKey: Address };
}
}

const base = (params: TestParams = defaultTestParams) =>
test.extend<TestProps>({
bypassCSP: true,
web3: async ({ page }, use) => {
const { chain, privateKey, options } = {
chain: params.chain ?? defaultTestParams.chain,
const { privateKey, options } = {
privateKey: params.privateKey ?? defaultTestParams.privateKey,
options: {
marketView: params.options?.marketView ?? defaultTestParams.options.marketView,
Expand All @@ -66,13 +70,11 @@ const base = (params: TestParams = defaultTestParams) =>
const walletClient = createWalletClient({ account, chain, transport: http(fork.url()) });
const publicClient = createPublicClient({ chain, transport: http(fork.url()) });

const { pathname: root } = new URL('../', import.meta.url);
const injected = (await fs.readFile(`${root}/fixture/injected.txt`, { encoding: 'utf-8' }))
.replace('__RPC_URL', fork.url())
.replace('__CHAIN_ID', String(chain.id))
.replace('__PRIVATE_KEY', privateKey);
const injected = { privateKey: privateKey, rpc: fork.url(), chainId: chain.id };

await page.addInitScript(injected);
await page.addInitScript((_injected) => {
window.e2e = _injected;
}, injected);

await page.addInitScript((opts) => {
window.localStorage.setItem('marketView', opts.marketView);
Expand Down
1 change: 0 additions & 1 deletion e2e/fixture/injected.txt

This file was deleted.

36 changes: 16 additions & 20 deletions utils/client.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,48 @@
import { EthereumClient, w3mConnectors, w3mProvider } from '@web3modal/ethereum';
import { createConfig, configureChains, ChainProviderFn, Chain } from 'wagmi';
import { InjectedConnector } from 'wagmi/connectors/injected';
import { createConfig, configureChains, ChainProviderFn, Chain, Address } from 'wagmi';
import * as wagmiChains from 'wagmi/chains';
import { jsonRpcProvider } from 'wagmi/providers/jsonRpc';
import { alchemyProvider } from 'wagmi/providers/alchemy';
import { publicProvider } from 'wagmi/providers/public';
import { SafeConnector } from 'wagmi/connectors/safe';
import { optimism } from 'wagmi/chains';

import E2EConnector from './connectors';

declare global {
interface Window {
ethereum: { provider: { connection: { url: string } } };
e2e: { rpc: string; chainId: number; privateKey: Address };
}
}

export const walletConnectId = '11ddaa8aaede72cb5d6b0dae2fed7baa';
const e2e = typeof window !== 'undefined' ? window.e2e : null;
export const isE2E: boolean = JSON.parse(process.env.NEXT_PUBLIC_IS_E2E ?? 'false') && e2e;

const networkId = Number(process.env.NEXT_PUBLIC_NETWORK ?? optimism.id);
export const defaultChain = Object.values(wagmiChains).find((c) => c.id === networkId) ?? optimism;

export const isE2E: boolean = JSON.parse(process.env.NEXT_PUBLIC_IS_E2E ?? 'false');

const sortedChains = isE2E
? [defaultChain]
: [defaultChain, ...Object.values(wagmiChains).filter((c) => c.id !== defaultChain.id)];

const alchemyKey = process.env.NEXT_PUBLIC_ALCHEMY_API_KEY;

const providers: ChainProviderFn<Chain>[] = isE2E
? [
jsonRpcProvider({
rpc: () => ({
http: typeof window !== 'undefined' ? window.ethereum.provider.connection.url : 'http://127.0.0.1:8545',
}),
}),
]
: [
...(alchemyKey ? [alchemyProvider({ apiKey: alchemyKey })] : []),
publicProvider(),
w3mProvider({ projectId: walletConnectId }),
];
const providers: ChainProviderFn<Chain>[] =
isE2E && e2e
? [jsonRpcProvider({ rpc: () => ({ http: e2e ? e2e.rpc : 'http://127.0.0.1:8545' }) })]
: [
...(alchemyKey ? [alchemyProvider({ apiKey: alchemyKey })] : []),
publicProvider(),
w3mProvider({ projectId: walletConnectId }),
];

const { chains, publicClient } = configureChains<Chain>(sortedChains, providers);

export const wagmi = createConfig({
connectors: [
...(isE2E
? [new InjectedConnector({ chains, options: { name: 'E2E', shimDisconnect: false } })]
...(isE2E && e2e
? [new E2EConnector({ chains, ...e2e })]
: [...w3mConnectors({ projectId: walletConnectId, chains }), new SafeConnector({ chains })]),
],
publicClient,
Expand Down
27 changes: 27 additions & 0 deletions utils/connectors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createWalletClient, http, type Chain, type Address } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { MockConnector } from 'wagmi/connectors/mock';

export default class E2EConnector extends MockConnector {
constructor({
privateKey,
rpc,
chainId,
chains,
}: {
privateKey: Address;
rpc: string;
chainId: number;
chains: Chain[];
}) {
const account = privateKeyToAccount(privateKey);
super({
chains,
options: {
chainId,
flags: { isAuthorized: true },
walletClient: createWalletClient({ account, chain: chains[0], transport: http(rpc) }),
},
});
}
}

0 comments on commit 3895ef9

Please sign in to comment.