Skip to content

Instantly share code, notes, and snippets.

@agrcrobles
Created January 19, 2018 20:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agrcrobles/d1cabde05fc38cc032336f1dbdbfb4df to your computer and use it in GitHub Desktop.
Save agrcrobles/d1cabde05fc38cc032336f1dbdbfb4df to your computer and use it in GitHub Desktop.
Create HookedWalletEthTx Subprovider for web3 to make it work on web
import Web3 from 'web3';
const ProviderEngine = require('web3-provider-engine');
const Web3Subprovider = require('web3-provider-engine/subproviders/web3.js');
const HookedWalletEthTxSubprovider = require('web3-provider-engine/subproviders/hooked-wallet-ethtx.js');
const PUBLIC_ACCOUNT = '0xPUBLIC_ACCOUNT_HERE';
const network = truffleConfig.networks.ropsten;
const TESTRPC_ADDRESS = `${network.protocol}://${network.host}/${network.key}`;
function WalletProvider(provider_url) {
this.engine = new ProviderEngine();
// https://github.com/MetaMask/provider-engine
this.engine.addProvider(
new HookedWalletEthTxSubprovider({
getAccounts: function(callback) {
callback(null, [PUBLIC_ACCOUNT]);
},
getPrivateKey: function(address, callback) {
if (address === PUBLIC_ACCOUNT) {
const privateBuffered = Buffer.from(
'PRIVATE_KEY_HERE',
'hex'
);
return callback(null, privateBuffered);
}
return callback(new Error('not private key supplied for that account'));
},
})
);
this.engine.addProvider(
new Web3Subprovider(new Web3.providers.HttpProvider(provider_url))
);
this.engine.start(); // Required by the provider engine.
}
WalletProvider.prototype.sendAsync = function() {
this.engine.sendAsync.apply(this.engine, arguments);
};
WalletProvider.prototype.send = function() {
return this.engine.send.apply(this.engine, arguments);
};
WalletProvider.prototype.getAddress = function() {
return this.address;
};
const web3Provider = new WalletProvider(TESTRPC_ADDRESS);
const web3 = new Web3(web3Provider);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment