UNPKG

@keplr-ewallet/ewallet-sdk-eth

Version:
86 lines 2.98 kB
import { isAddress, isAddressEqual } from "viem"; import { getPublicKey, makeSignature, getEthereumProvider, personalSign, switchChain, toViemAccount, getAddress, } from "./api"; import { publicKeyToEthereumAddress } from "./utils"; export class EthEWallet { constructor(eWallet, useTestnet = false) { this.getEthereumProvider = getEthereumProvider.bind(this); this.sign = personalSign.bind(this); this.switchChain = switchChain.bind(this); this.toViemAccount = toViemAccount.bind(this); this.getPublicKey = getPublicKey.bind(this); this.getAddress = getAddress.bind(this); this.makeSignature = makeSignature.bind(this); this.eWallet = eWallet; this.useTestnet = useTestnet; this._provider = null; this._publicKey = null; this._address = null; this.eWallet.on("_accountsChanged", (payload) => { console.log("[keplr-ewallet-sdk-eth] _accountsChanged", payload); this.handleAccountChange(payload.publicKey); }); } get type() { return "ethereum"; } get chainId() { if (!this._provider) { return `eip155:${1}`; } return `eip155:${parseInt(this._provider.chainId, 16)}`; } get publicKey() { return this._publicKey; } set publicKey(publicKey) { this._publicKey = publicKey; } get address() { return this._address; } set address(address) { this._address = address; } get provider() { return this._provider; } set provider(provider) { this._provider = provider; } handleAccountChange(publicKey) { if (!this._provider) { return; } if (!publicKey) { this._publicKey = null; this._address = null; this._provider.emit("accountsChanged", []); return; } try { const publicKeyHex = publicKey.startsWith("0x") ? publicKey : `0x${publicKey}`; const address = publicKeyToEthereumAddress(publicKeyHex); if (!isAddress(address)) { this._publicKey = null; this._address = null; this._provider.emit("accountsChanged", []); return; } const shouldEmitChange = this._address === null || !isAddressEqual(this._address, address); this._publicKey = publicKeyHex; this._address = address; if (shouldEmitChange) { this._provider.emit("accountsChanged", [address]); } } catch (error) { console.error("[keplr-ewallet-sdk-eth] failed to get account from public key", error); this._publicKey = null; this._address = null; this._provider.emit("accountsChanged", []); } } } //# sourceMappingURL=eth_ewallet.js.map