Skip to content

Commit

Permalink
feat: Debug Mode
Browse files Browse the repository at this point in the history
- Add Debug Mode
- Improve Test
  • Loading branch information
johanneskares committed Aug 5, 2024
1 parent 50b737e commit acd5ca7
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 80 deletions.
113 changes: 61 additions & 52 deletions src/createWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import * as chains from "viem/chains";

export type Wallet = ReturnType<typeof createWallet>;
export type WalletRequest = Wallet["request"];

export function createWallet(
account: LocalAccount,
Expand All @@ -26,62 +27,70 @@ export function createWallet(
method: string;
params?: Array<unknown>;
}) => {
try {
const client = createWalletClient({
account,
chain,
transport: transports?.[chain.id] ?? http(),
const client = createWalletClient({
account,
chain,
transport: transports?.[chain.id] ?? http(),
});

if (method === "eth_accounts" || method === "eth_requestAccounts") {
return await client.getAddresses();
}

if (
method === "wallet_requestPermissions" ||
method === "wallet_revokePermissions"
) {
return [{ parentCapability: "eth_accounts" }];
}

if (method === "wallet_getPermissions") return [];

if (method === "wallet_switchEthereumChain") {
chain = getChain((params?.[0] as any).chainId);
return null;
}

if (method === "personal_sign") {
return await client.account.signMessage({
message: {
raw: params?.[0] as Hex,
},
});
}

if (method === "eth_accounts" || method === "eth_requestAccounts") {
return await client.getAddresses();
}

if (
method === "wallet_requestPermissions" ||
method === "wallet_revokePermissions"
) {
return [{ parentCapability: "eth_accounts" }];
}

if (method === "wallet_getPermissions") return [];

if (method === "wallet_switchEthereumChain") {
chain = getChain((params?.[0] as any).chainId);
return null;
}

if (method === "personal_sign") {
return await client.account.signMessage({
message: {
raw: params?.[0] as Hex,
},
});
}

if (method === "eth_sendTransaction") {
const from = (params?.[0] as any).from;
if (from !== account.address) throw new Error("Invalid from address");

return await client.sendTransaction({
to: (params?.[0] as any).to,
data: (params?.[0] as any).data,
gas: (params?.[0] as any).gas,
gasPrice: (params?.[0] as any).gasPrice,
value: (params?.[0] as any).value,
maxFeePerGas: (params?.[0] as any).maxFeePerGas,
maxPriorityFeePerGas: (params?.[0] as any).maxPriorityFeePerGas,
});
}

return await client.request({
method: method as any,
params: params as any,
if (method === "eth_signTypedData") {
throw new Error("eth_signTypedData is not yet supported");
}

if (method === "eth_signTypedData_v3") {
throw new Error("eth_signTypedData_v4 is not yet supported");
}

if (method === "eth_signTypedData_v4") {
throw new Error("eth_signTypedData_v4 is not yet supported");
}

if (method === "eth_sendTransaction") {
const from = (params?.[0] as any).from;
if (from !== account.address) throw new Error("Invalid from address");

return await client.sendTransaction({
to: (params?.[0] as any).to,
data: (params?.[0] as any).data,
value: (params?.[0] as any).value,
// Let viem handle the gas calcutation
// gas: (params?.[0] as any).gas ?? (params?.[0] as any).gasLimit,
// gasPrice: (params?.[0] as any).gasPrice,
// maxFeePerGas: (params?.[0] as any).maxFeePerGas,
// maxPriorityFeePerGas: (params?.[0] as any).maxPriorityFeePerGas,
});
} catch (error) {
console.error("Error within Mock Wallet:", error);
return null;
}

return await client.request({
method: method as any,
params: params as any,
});
},
};
}
Expand Down
52 changes: 40 additions & 12 deletions src/installMockWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ export async function installMockWallet({
account,
transports,
defaultChain,
debug,
...params
}: {
account: LocalAccount;
transports: Record<number, Transport>;
transports?: Record<number, Transport>;
defaultChain?: Chain;
debug?: boolean;
} & ({ page: Page } | { browserContext: BrowserContext })) {
const browserOrPage =
"browserContext" in params ? params.browserContext : params.page;
Expand All @@ -26,14 +28,15 @@ export async function installMockWallet({
wallets.set(uuid, createWallet(account, transports, defaultChain));

await browserOrPage.addInitScript(
({ uuid }) => {
({ uuid, debug }) => {
// This function needs to be declared in the browser context
function announceMockWallet() {
const provider: EIP1193Provider = {
request: async (request) => {
return await eip1193Request({
...request,
uuid,
debug,
});
},
on: () => {},
Expand Down Expand Up @@ -64,7 +67,7 @@ export async function installMockWallet({
announceMockWallet();
});
},
{ uuid },
{ uuid, debug },
);
}

Expand Down Expand Up @@ -93,21 +96,46 @@ async function eip1193Request({
method,
params,
uuid,
debug,
}: {
method: string;
params?: Array<unknown>;
uuid: string;
debug?: boolean;
}) {
const wallet = wallets.get(uuid);
if (wallet == null) throw new Error("Account or transport not found");

// console.log("eip1193Request", method, params);

const result = await wallet.request({
method,
params,
});

// console.log("eip1193Result", result);
return result;
try {
const result = await wallet.request({
method,
params,
});

if (debug === true) {
console.log(
"WALLET",
uuid.substring(0, 8),
"REQUEST",
method,
params,
"RESULT",
result,
);
}
return result;
} catch (e) {
if (debug === true) {
console.log(
"WALLET",
uuid.substring(0, 8),
"REQUEST",
method,
params,
"ERROR",
e,
);
}
throw e;
}
}
23 changes: 7 additions & 16 deletions tests/transaction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,7 @@ test.beforeEach(async ({ page }) => {
isHex(process.env.PRIVATE_KEY) ? process.env.PRIVATE_KEY : "0x",
),
defaultChain: sepolia,
transports: {
[sepolia.id]: (config) => {
return custom({
request: async ({ method, params }) => {
let result: unknown;
try {
result = await http()(config).request({ method, params });
} finally {
console.log("METHOD", method, "PARAMS", params, "RESULT", result);
}
return result;
},
})(config);
},
},
debug: true,
});
});

Expand All @@ -39,5 +25,10 @@ test("Metamask Wallet Test Dapp", async ({ page }) => {
).toBeVisible();
await expect(page.getByText("Name: Mock Wallet")).toBeVisible();

await page.pause();
await page.locator("#personalSign").click();
await expect(
page.getByText(
"0x7ac0fa03981bf136329ffaa21aed4f0ac7fa9a4837e966f16c5bf8783be7e43f41afe27bc4fb75",
),
).toBeVisible();
});

0 comments on commit acd5ca7

Please sign in to comment.