import { expect, test, type Page } from "@playwright/test";
import { fileURLToPath } from "node:url";
const TEST_PRIVATE_KEY =
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
const TEST_ADDRESS = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266";
const TEST_WALLET_NAME = "TinyCloud E2E Wallet";
const ETHERS_UMD_PATH = fileURLToPath(
new URL("../node_modules/ethers/dist/ethers.umd.min.js", import.meta.url),
);
function exposeTestShadowRoots() {
return () => {
const attachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function (init: ShadowRootInit) {
return attachShadow.call(this, { ...init, mode: "open" });
};
};
}
function installTestWallet() {
return ({
address,
privateKey,
walletName,
}: {
address: string;
privateKey: string;
walletName: string;
}) => {
const ethers = (window as any).ethers;
const wallet = new ethers.Wallet(privateKey);
const provider = {
selectedAddress: address,
chainId: "0x1",
async request({
method,
params = [],
}: {
method: string;
params?: unknown[];
}) {
switch (method) {
case "eth_requestAccounts":
case "eth_accounts":
return [address];
case "eth_chainId":
return "0x1";
case "personal_sign": {
const message = params[0];
if (typeof message !== "string")
throw new Error("personal_sign missing message");
return message.startsWith("0x")
? wallet.signMessage(ethers.utils.arrayify(message))
: wallet.signMessage(message);
}
case "wallet_getPermissions":
case "wallet_requestPermissions":
return [{ parentCapability: "eth_accounts" }];
default:
return null;
}
},
on: () => provider,
removeListener: () => provider,
isConnected: () => true,
};
const announce = () =>
window.dispatchEvent(
new CustomEvent("eip6963:announceProvider", {
detail: {
info: {
uuid: "8fd9b04a-e8a0-4c43-9d87-5af504aa1f0d",
name: walletName,
icon: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg"/%3E',
rdns: "xyz.tinycloud.e2e-wallet",
},
provider,
},
}),
);
Object.defineProperty(window, "ethereum", {
value: provider,
configurable: true,
});
window.addEventListener("eip6963:requestProvider", announce);
announce();
};
}
async function bootstrapTestAccount(page: Page) {
await page.addInitScript(exposeTestShadowRoots());
await page.addInitScript({ path: ETHERS_UMD_PATH });
await page.addInitScript(installTestWallet(), {
address: TEST_ADDRESS,
privateKey: TEST_PRIVATE_KEY,
walletName: TEST_WALLET_NAME,
});
}