Skip to content

Instantly share code, notes, and snippets.

@chmanie
Created November 14, 2017 05:02
Show Gist options
  • Save chmanie/cdf2697e42bf9adb1dc018731688b894 to your computer and use it in GitHub Desktop.
Save chmanie/cdf2697e42bf9adb1dc018731688b894 to your computer and use it in GitHub Desktop.
MetaMaskSigner / Web3Signer for ethers.js
import { providers } from 'ethers';
import Eth from 'ethjs';
class Web3Provider extends providers.Provider {
constructor() {
super();
// https://github.com/MetaMask/faq/blob/master/detecting_metamask.md#web3-deprecation
if (typeof window.web3 == 'undefined' || typeof window.web3.currentProvider == 'undefined') {
throw new Error('Web3Provider can just be used with a web3 currentProvider injected');
}
this.eth = new Eth(window.web3.currentProvider);
}
async perform(method, params) {
switch (method) {
case 'getGasPrice': {
const gasPriceBn = await this.eth.gasPrice();
// Converting to string for now as this is the only format both BN libs understand
return gasPriceBn.toString();
}
case 'getTransactionCount':
return this.eth.getTransactionCount(params.address, params.blockTag);
default:
return Promise.reject(new Error('Not implemented'));
}
}
}
export default Web3Provider;
import Web3Provider from './Web3Provider';
const ethersTxToWeb3 = (tx, from) => ({
from,
to: tx.to,
value: tx.value ? tx.value.toString() : '0',
gas: tx.gasLimit.toString(),
gasPrice: tx.gasPrice.toString(),
data: tx.data,
nonce: tx.nonce,
});
class Web3Signer {
constructor() {
this.provider = new Web3Provider();
}
async getAddress() {
// https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#raising_hand-account-list-reflects-user-preference
const accounts = await this.provider.eth.accounts();
return accounts[0];
}
async sign(tx) {
const from = await this.getAddress();
const web3Tx = ethersTxToWeb3(tx, from);
return this.provider.eth.sendTransaction(web3Tx);
}
}
export default Web3Signer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment