@johanneskares/wallet-mock
Version:
Mock Web3 Browser wallets, like Metamask, in Playwright tests.
74 lines • 3.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.installMockWallet = void 0;
const createWallet_1 = require("./createWallet");
const crypto_1 = require("crypto");
let wallets = new Map();
async function installMockWallet({ debug, ...params }) {
const browserOrPage = "browserContext" in params ? params.browserContext : params.page;
const wallet = "wallet" in params
? params.wallet
: (0, createWallet_1.createWallet)(params.account, params.transports, params.defaultChain);
// Connecting the browser context to the Node.js playwright context
await browserOrPage.exposeFunction("eip1193Request", eip1193Request);
// Everytime we call installMockWallet, we create a new uuid to identify the wallet.
const uuid = (0, crypto_1.randomUUID)();
wallets.set(uuid, wallet);
await browserOrPage.addInitScript(({ uuid, debug }) => {
// This function needs to be declared in the browser context
function announceMockWallet() {
const provider = {
request: async (request) => {
return await eip1193Request({
...request,
uuid,
debug,
});
},
on: () => { },
removeListener: () => { },
};
const info = {
uuid,
name: "Mock Wallet",
icon: "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='lucide lucide-cat'><path d='M12 5c.67 0 1.35.09 2 .26 1.78-2 5.03-2.84 6.42-2.26 1.4.58-.42 7-.42 7 .57 1.07 1 2.24 1 3.44C21 17.9 16.97 21 12 21s-9-3-9-7.56c0-1.25.5-2.4 1-3.44 0 0-1.89-6.42-.5-7 1.39-.58 4.72.23 6.5 2.23A9.04 9.04 0 0 1 12 5Z'/><path d='M8 14v.5'/><path d='M16 14v.5'/><path d='M11.25 16.25h1.5L12 17l-.75-.75Z'/></svg>",
rdns: "com.example.mock-wallet",
};
const detail = { info, provider };
const announceEvent = new CustomEvent("eip6963:announceProvider", {
detail: Object.freeze(detail),
});
window.dispatchEvent(announceEvent);
}
announceMockWallet();
window.addEventListener("eip6963:requestProvider", () => {
announceMockWallet();
});
window.addEventListener("DOMContentLoaded", () => {
announceMockWallet();
});
}, { uuid, debug });
}
exports.installMockWallet = installMockWallet;
async function eip1193Request({ method, params, uuid, debug, }) {
const wallet = wallets.get(uuid);
if (wallet == null)
throw new Error("Account or transport not found");
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;
}
}
//# sourceMappingURL=installMockWallet.js.map