Created
July 12, 2018 16:21
-
-
Save OR13/6e6e984a00e91d3d467fb9b96b958fb1 to your computer and use it in GitHub Desktop.
Funding a MetaMask Account with Ganache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Web3 = require('web3'); | |
const fundMetaMaskFromDefaultAccounts = async (amountETH, providerUrl) => { | |
if (window.web3) { | |
const metaMaskWeb3 = window.web3; | |
const ganacheWeb3 = new Web3(new Web3.providers.HttpProvider(providerUrl)); | |
const getAccounts = someWeb3 => { | |
return new Promise((resolve, reject) => { | |
someWeb3.eth.getAccounts(async (err, accounts) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(accounts); | |
} | |
}); | |
}); | |
}; | |
const getBalance = (someWeb3, someAddress) => { | |
return new Promise((resolve, reject) => { | |
someWeb3.eth.getBalance(someAddress, (err, balance) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(balance.toNumber()); | |
} | |
}); | |
}); | |
}; | |
let metaMaskAccounts = await getAccounts(metaMaskWeb3); | |
let metaMaskAccountBalance = await getBalance( | |
metaMaskWeb3, | |
metaMaskAccounts[0] | |
); | |
console.log('unfunded account: ', { | |
metaMaskAccounts, | |
metaMaskAccountBalance | |
}); | |
let defaultAccounts = await getAccounts(ganacheWeb3); | |
let receipt = await ganacheWeb3.eth.sendTransaction({ | |
from: defaultAccounts[0], | |
to: metaMaskAccounts[0], | |
value: ganacheWeb3.toWei(amountETH, 'ether'), | |
gasLimit: 21000, | |
gasPrice: 20000000000 | |
}); | |
console.log(receipt); | |
metaMaskAccountBalance = await getBalance( | |
metaMaskWeb3, | |
metaMaskAccounts[0] | |
); | |
console.log('funded account: ', { | |
metaMaskAccounts, | |
metaMaskAccountBalance | |
}); | |
} else { | |
console.log('MetaMask is not available, please install it.'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment