@dgpub/prime-sdk
Version:
Etherspot Prime (Account Abstraction) SDK
100 lines (99 loc) • 3.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetaMaskWalletProvider = void 0;
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, accountAddress) {
const chainId = await this.sendRequest('eth_chainId');
const domainSeparator = {
name: "EtherspotWallet",
version: "2.0.0",
chainId: chainId,
verifyingContract: accountAddress
};
let signature = await this.sendRequest('eth_signTypedData_v4', [
this.address,
{
"types": {
"EIP712Domain": [
{
"name": "name",
"type": "string"
},
{
"name": "version",
"type": "string"
},
{
"name": "chainId",
"type": "uint256"
},
{
"name": "verifyingContract",
"type": "address"
}
],
"message": typedData
},
"primaryType": "message",
"domain": domainSeparator,
"message": message
}
]);
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;