@etherspot/prime-sdk
Version:
Etherspot Prime (Account Abstraction) SDK
80 lines (79 loc) • 2.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetaMaskWalletProvider = void 0;
const ethers_1 = require("ethers");
const common_1 = require("../../common");
const dynamic_wallet_provider_1 = require("./dynamic.wallet-provider");
class MetaMaskWalletProvider extends dynamic_wallet_provider_1.DynamicWalletProvider {
static get ethereum() {
return this.detect() ? window.ethereum : null;
}
static detect() {
var _a;
return !!((_a = window === null || window === void 0 ? void 0 : window.ethereum) === null || _a === void 0 ? void 0 : _a.isMetaMask);
}
static async connect() {
if (!this.instance) {
if (!this.detect()) {
throw new Error('MetaMask not found');
}
this.instance = new MetaMaskWalletProvider();
await this.instance.connect();
}
if (!this.instance.address) {
throw new Error('Can not connect to MetaMask');
}
return this.instance;
}
constructor() {
super('MetaMask');
}
async signMessage(message) {
return this.sendRequest('personal_sign', [
(0, common_1.toHex)(message),
this.address,
]);
}
async signTypedData(typedData, message, factoryAddress, initCode) {
const { domain, types, primaryType } = typedData;
const msgParams = JSON.stringify({
domain,
message,
primaryType,
types
});
const signature = await this.sendRequest('eth_signTypedData_v4', [
this.address,
msgParams
]);
if (initCode !== '0x') {
const abiCoderResult = ethers_1.utils.defaultAbiCoder.encode(['address', 'bytes', 'bytes'], [factoryAddress, initCode, signature]);
return abiCoderResult + '6492649264926492649264926492649264926492649264926492649264926492';
}
return signature;
}
async connect() {
const { ethereum } = window;
ethereum.autoRefreshOnNetworkChange = false;
ethereum.on('accountsChanged', ([address]) => this.setAddress(address));
ethereum.on('chainChanged', () => {
window.location.reload();
});
try {
const chainId = await this.sendRequest('eth_chainId');
this.setNetworkName(chainId);
const [address] = await this.sendRequest('eth_requestAccounts');
this.setAddress(address);
}
catch (err) {
}
}
async sendRequest(method, params) {
const { ethereum } = window;
return ethereum.request({
method,
params,
});
}
}
exports.MetaMaskWalletProvider = MetaMaskWalletProvider;