Created
February 23, 2018 07:43
-
-
Save woniesong92/15a06c9e4683594a8871834107e628eb to your computer and use it in GitHub Desktop.
Send a signed transaction to a contract in Ethereum
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
// Sending a signed transaction to a contract | |
// using the contract's owner's private key | |
// "web3": "^1.0.0-beta.30" | |
// "ethereumjs-tx": "^1.3.3", | |
// createItem function takes (name, price) as args | |
const web3 = new Web3(new Web3.providers.HttpProvider(INFURA_URL)) | |
const myContract = new web3.eth.Contract(MY_ABI, MY_CONRACT_ADDRESS) | |
const ownerAccount = "" | |
const ownerPrivateKey = "" | |
web3.eth.getTransactionCount(ownerAccount, (err, nonce) => { | |
if (err) { | |
console.log(err) | |
callback(err) | |
return | |
} | |
const data = myContract.methods.createItem(name, price).encodeABI() | |
const tx = new EthereumTx({ | |
nonce: nonce, | |
gasPrice: web3.utils.toHex(web3.utils.toWei('20', 'gwei')), | |
gasLimit: 100000, | |
to: MY_CONRACT_ADDRESS, | |
value: 0, | |
data: data, | |
}) | |
tx.sign(new Buffer(ownerPrivateKey, 'hex')) | |
const raw = '0x' + tx.serialize().toString('hex') | |
web3.eth.sendSignedTransaction(raw, (err, transactionHash) => { | |
if (err) { | |
console.log(err) | |
callback() | |
return | |
} | |
callback(transactionHash) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment