UNPKG

@uprtcl/ethereum-provider

Version:

_Prtcl provider wrappers around web3

104 lines (100 loc) 3.53 kB
import { Connection, Logger } from '@uprtcl/evees'; import { ethers } from 'ethers'; class EthereumConnection extends Connection { constructor(ethOptions = { provider: 'http://localhost:8545', }, options) { super(options); this.ethOptions = ethOptions; } /** * @override */ async connect() { if (typeof this.ethOptions.provider === 'string') { this.provider = new ethers.providers.JsonRpcProvider(this.ethOptions.provider); } else { this.provider = this.ethOptions.provider; } this.signer = undefined; this.account = ''; this.network = await this.provider.getNetwork(); this.networkId = this.provider.send ? await this.provider.send('net_version', []) : this.network.chainId; } getLatestBlock() { return this.provider.getBlockNumber(); } async connectWallet() { await window['ethereum'].enable(); const provider = new ethers.providers.Web3Provider(window['ethereum']); this.ethOptions = { provider }; await this.connect(); this.signer = this.provider.getSigner(); const account = await this.signer.getAddress(); this.account = this.signer ? account.toString() : ''; } async disconnectWallet() { await this.connect(); } canSign() { return !!this.signer; } /** * @returns the current used account for this ethereum connection */ getCurrentAccount() { return this.account.toLowerCase(); } getNetworkId() { return this.networkId; } async signText(text, account) { if (!this.signer) throw new Error('signer not set'); return this.signer.signMessage(text); } async verifySignature(message, signature) { return ethers.utils.verifyMessage(message, signature).toLocaleLowerCase(); } } class EthereumContract { constructor(options, connection) { this.options = options; this.connection = connection; this.logger = new Logger('EthereumContract'); } get userId() { return this.connection.getCurrentAccount(); } /** must be created everytime to have the up to date signer */ get contractInstance() { return new ethers.Contract(this.contractAddress, this.options.contract.abi, this.connection.signer ? this.connection.signer : this.connection.provider); } async ready() { await this.connection.ready(); this.contractAddress = this.options.contractAddress || this.options.contract.networks[await this.connection.getNetworkId()].address; } /** * Calls a method of the holding contract and resolves only when confirmed */ async send(funcName, pars) { this.logger.log(`CALLING ${funcName}`, pars); const tx = await this.contractInstance[funcName](...pars); this.logger.log(`TX HASH ${funcName} `, { tx, pars }); const receipt = await tx.wait(); this.logger.log(`RECEIPT ${funcName} receipt`, { receipt, pars }); } /** * Simple call function for the holding contract */ async call(funcName, pars) { return this.contractInstance[funcName](...pars); } } export { EthereumConnection, EthereumContract }; //# sourceMappingURL=uprtcl-ethereum-provider.es5.js.map