[Ethereum] Sending transaction with web3.js

go-ethereumsendrawtransactionsolidityweb3js

I'm trying to use web3.js with infura.io to interact with my smartcontract. here is my simple greeter contract code

pragma solidity ^0.5.7;
contract greeter{
    string greeting;

    function greet(string memory _greeting)public {
        greeting=_greeting;
    }
    function getGreeting() public view returns(string memory) {
        return greeting;
    }
}

Here is what I found from web3.js documentation.

var tx = web3.eth.sendTransaction({
             from: '0x3dCDe57Ad49d639c4D702b607Dd5eBc0aB54A671',
             nonce: web3.toHex(txCount),
             gasLimit: web3.toHex(1000000),
             gasPrice: web3.toHex(web3.toWei('10', 'gwei')),
             data:0x756774689538938966626728299293638893o
         });
web3.eth.accounts.signTransaction(tx, privateKey [, callback]);

But it doesn't take me anywhere. Because,where can I pass greeting data? All the documentation talks about sending ether. Then what about sending string data like this? with web3.js 0.20 I can read greeting from chain. I wanted to add new greeting string with greet function. but somehow I have no idea about signing transaction. could anyone help me in understanding how to sign transacion and adding greeting to the contract using web3.js?

Best Answer

You are not providing too much informations for me to give you an easy way to do that :) , anyway this is one way to how you can send transaction:

Better to use web3 1.0, you need also install ethereumjs-tx: npm install ethereumjs-tx

const Tx = require('ethereumjs-tx');

to get instance of your contract:

new web3.eth.Contract(jsonInterface, address, options)

Example:

const myContract = new web3.eth.Contract([...], '..address of your contract..', {
    defaultAccount: '....', // default from address
    defaultGasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
});

and to get the data for the transaction parameter:

const mydata = myContract.methods.greet("<your-greeting.string>").encodeABI()));

to Sign and Send

const privateKey = Buffer('<your privatekey>', 'hex')
    
const rawTx = {
    nonce: <your-tx-nonce.. you can also get it with web3 command >,
    gasLimit: web3.toHex(1000000),
    gasPrice: web3.toHex(web3.toWei('10', 'gwei')),
    to: <your contract address>,
    value: '0x00',
    data: mydata 
}
    
const tx = new Tx(rawTx);
tx.sign(privateKey);
    
const serializedTx = tx.serialize();
    
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
        .on('receipt', console.log);

https://web3js.readthedocs.io/en/1.0/web3-eth.html#sendsignedtransaction https://web3js.readthedocs.io/en/1.0/web3-eth-abi.html?highlight=encode

Related Topic