[Ethereum] How to state private keys when using node.js and ethereum to run a contract

ethereumjsnodejssolidity

I have to run node.js to execute smart contracts. My quetsion is about the keys.

I have seen this from the docs –

1. Code to sign
2. Code to execute

But I am unsure how the two are combined. Could someone clarify this?

I have a deployed contract which has this function –



 function addBonus( string bonusType, uint bonusTarget,  uint bonusEndYear,
        uint bonusEndMonth, uint bonusEndDay, 
        string bonusToken, uint bonusAmount, string bonusName, uint ineq ) public {
// processing
}

From the docs –

var Tx = require('ethereumjs-tx'); 
var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex') 
var rawTx = {  
nonce: '0x00',  
gasPrice: '0x09184e72a000',   
gasLimit: '0x2710',  
to: '0x0000000000000000000000000000000000000000', 
value: '0x00',   
data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057' } 
var tx = new Tx(rawTx); 
tx.sign(privateKey); 
var serializedTx = tx.serialize();  
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {  
if (!err)    
console.log(hash); // "0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385" });

And this –

// contract abi
var abi = [{
    name: 'myConstantMethod',
    type: 'function',
    constant: true,
    inputs: [{ name: 'a', type: 'string' }],
    outputs: [{name: 'd', type: 'string' }]
}, {
    name: 'myStateChangingMethod',
    type: 'function',
    constant: false,
    inputs: [{ name: 'a', type: 'string' }, { name: 'b', type: 'int' }],
    outputs: []
}, {
    name: 'myEvent',
    type: 'event',
    inputs: [{name: 'a', type: 'int', indexed: true},{name: 'b', type: 'bool', indexed: false}]
}];
// creation of contract object
var MyContract = web3.eth.contract(abi);
// initiate contract for an address
var myContractInstance = MyContract.at('0xc4abd0339eb8d57087278718986382264244252f');
// call constant function
var result = myContractInstance.myConstantMethod('myParam');
console.log(result) // '0x25434534534'
// send a transaction to a function
myContractInstance.myStateChangingMethod('someParam1', 23, {value: 200, gas: 2000});
// short hand style
web3.eth.contract(abi).at(address).myAwesomeMethod(...);
// create filter
var filter = myContractInstance.myEvent({a: 5}, function (error, result) {
 if (!error)
   console.log(result);
   /*
   {
       address: '0x8718986382264244252fc4abd0339eb8d5708727',
       topics: "0x12345678901234567890123456789012", "0x0000000000000000000000000000000000000000000000000000000000000005",
       data: "0x0000000000000000000000000000000000000000000000000000000000000001",
       ...
   }
   */
});

I assume we have to combine these two expressed ideas somehow. I cannot see any private keys in the second example and the first one has no example of running a contract.

Best Answer

   var infuraApiKey =process.env.INFURA_API_KEY;
  // var privateKey = process.env.PRIVATE_KEY;

   var web3js = new web3(new web3.providers.HttpProvider("https://kovan.infura.io/v3/"+infuraApiKey));

   web3js.eth.defaultAccount = myAddress;
   var privateKey=new Buffer(process.env.PRIVATE_KEY, 'hex');

//   var toAddress = 'ADRESS_TO_SEND_TRANSACTION';

   //contract abi is the array that you can get from the ethereum wallet or etherscan
   var contractABI =bonusABI;
   var contractAddress =bonusAddress;
   //creating contract object
   var contract =  web3js.eth.contract(contractABI).at(contractAddress);
   var count;
   var nounce;
   var errcode="";
   web3js.eth.getTransactionCount(myAddress, function(err, result) {
        nounce=result;
        var nounceHex = web3js.toHex(nounce);

        var rawTransaction = {"from":myAddress,
        "gasPrice":web3js.toHex(2*1e9),
        "gasLimit":web3js.toHex(920000),
        "to":contractAddress,
        "data":contract.addBonus.getData(bonusType, target, year, month, day, token, bonus, bonusName, ineq),
        "nonce":nounceHex}

        var transaction = new Tx(rawTransaction);
        transaction.sign(privateKey);

        var serializedTx = transaction.serialize();
        web3js.eth.sendRawTransaction('0x'+serializedTx.toString('hex'), function(err1, hash) {
           if (!err1) {
               errcode=hash;
          }
           else
               errcode=err1;
        });
  })
Related Topic