Skip to content

Instantly share code, notes, and snippets.

@pwrstudio
Created December 5, 2017 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwrstudio/6c95043ae3bb6a9aef9734a3fc8469e7 to your computer and use it in GitHub Desktop.
Save pwrstudio/6c95043ae3bb6a9aef9734a3fc8469e7 to your computer and use it in GitHub Desktop.
const Web3 = require('web3')
const Tx = require('ethereumjs-tx')
const web3 = new Web3()
web3.setProvider(new web3.providers.HttpProvider('https://rinkeby.infura.io/TOKEN'))
const CONTRACT_ADDRESS = '0xxx'
const abi = [
{
constant: false,
inputs: [
{
name: 'x',
type: 'string'
}
],
name: 'set',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'get',
outputs: [
{
name: 'x',
type: 'string'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
}
]
const rootContract = new web3.eth.Contract(abi, CONTRACT_ADDRESS)
const addressFrom = '0xxx'
const privKey = '0xxx'
const addressTo = CONTRACT_ADDRESS
function sendSigned(txData, cb) {
const privateKey = new Buffer(privKey, 'hex')
const transaction = new Tx(txData)
transaction.sign(privateKey)
const serializedTx = transaction.serialize().toString('hex')
web3.eth.sendSignedTransaction('0x' + serializedTx, cb)
}
module.exports = rootHash => {
return new Promise((resolve, reject) => {
// get the number of transactions sent so far so we can create a fresh nonce
web3.eth.getTransactionCount(addressFrom).then(txCount => {
// construct the transaction data
const txData = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(75000),
gasPrice: web3.utils.toHex(10e9), // 10 Gwei
to: addressTo,
from: addressFrom,
value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
data: rootContract.methods.set(rootHash).encodeABI()
}
// send
sendSigned(txData, function(err, result) {
if (err) return console.log('error', err)
console.log('sent', result)
})
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment