Sending transaction on ETC network using nodejs to call smart contract

dapp-development

#1

https://ethereum-classic-guide.readthedocs.io/en/latest/docs/world_database/transactions.html

I am sending transaction using rpc command according to above link

    web3 = new Web3(new Web3.providers.HttpProvider('https://ethereumclassic.network');
    var txData = contractInstance.methods.play(...).encodeABI()
    const tx = {
        nonce: txNonce,
        from: publickey,
        to: contractAddr,
        data: txData,
        gasLimit: web3.utils.toHex(gasEstimate),
        gasPrice: gasPriceToUse,
        value: web3.utils.toHex(web3.utils.toWei('0', 'ether'))
      };

      const result = await web3.eth.accounts.signTransaction(tx, privatekey);
      var txSigned = tx;
      txSigned.v = result.v;
      txSigned.r = result.r;
      txSigned.s = result.s;
      console.log(result);
      console.log("sending tx...")

      let options = {
          url: config.rpc_endpoint[process.env.NODE_ENV],
          method: "post",
          headers:
          { 
            "Content-Type": "application/json"
          },
          body: JSON.stringify(txSigned)
      };

      request(options, (error, response, body) => {
          if (error) {
            logger.error('An error has occurred: ', error);
          } else {
            logger.info('Post successful: response: ', body);
          }
      });

It is providing {"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":null}
Here web3 version is 1.0.0-beta.34.
One to mention: Above worked for ETH network.
My question is how I can send transaction without any error that is calling smart contract function.
UPDATE: I tried various functions without using rpc command directly but using web3 function but it showed Cannot execute transaction message.
If someone has previous experience in this field, please share valid link or any code snippet! Thank you!


#2

I think your problem might be with EIP-155. You need to update your code like this:

const tx = {
    nonce: txNonce,
    to: contractAddr,
    data: txData,
    gasLimit: web3.utils.toHex(gasEstimate),
    gasPrice: gasPriceToUse,
    value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
    chainId: 61
  };

#3

Thank you @Neuron
I will try this and let you know result ASAP


#4

Hello @Neuron
Same result even though add chainID to the transaction.
Shows transaction execution failed.
This is exact result I see.

error: message=Returned error: Transaction execution error., stack=Error: Returned error: Transaction execution error.
at Object.ErrorResponse (/root/ffETCbackend/node_modules/web3-core-helpers/src/errors.js:29:16)
at /root/ffETCbackend/node_modules/web3-core-requestmanager/src/index.js:140:36
at XMLHttpRequest.request.onreadystatechange (/root/ffETCbackend/node_modules/web3-providers-http/src/index.js:77:13)
at XMLHttpRequestEventTarget.dispatchEvent (/root/ffETCbackend/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/root/ffETCbackend/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/root/ffETCbackend/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage. (/root/ffETCbackend/node_modules/xhr2/lib/xhr2.js:469:24)
at IncomingMessage.emit (events.js:165:20)
at endReadableNT (_stream_readable.js:1101:12)
at process._tickCallback (internal/process/next_tick.js:152:19)


#5

does it work in remix?


#6

@Neuron It works perfectly with Remix.
I just have problem sending transaction on code itself. Do you know any other public api to send ETC transaction?
Do you think it is because of version of web3?
Or could you send me your Skpye? I want to have realtime communication with you.
My skype is [email protected] Thank you!


#7

No skype, m8

I’m sorry you’re having problems. I don’t think there’s an API yet, but if you know your contract’s bytecode here’s the snippet that has worked for me.

const fs = require('fs');
const solc = require('solc');
const Web3 = require('web3');
const Tx = require('ethereumjs-tx')

var privateKey = new Buffer('******', 'hex')

const web3 = new Web3(new Web3.providers.HttpProvider("https://mew.epool.io"))
const nonce = 42 // (just hardcoded, but pretty sure you can get this info using web3)
const gasPrice = 200000000000

// Compile the source code
function findImports(path) {
  return { contents: fs.readFileSync('contracts/' + path).toString() }
}
const input = fs.readFileSync('contracts/MyContract.sol');
const output = solc.compile({ sources: { 'MyContract.sol': input.toString() } }, 1, findImports);
const bytecode = output.contracts['MyContract.sol:MyContractName'].bytecode;

const gasPriceHex = web3.utils.toHex(gasPrice);
const gasLimitHex = web3.utils.toHex(3959391);

const nonceHex = web3.utils.toHex(nonce);

const rawTx = {
  nonce   : nonceHex,
  gasPrice: gasPriceHex,
  gasLimit: gasLimitHex,
  data    : '0x' + bytecode,
  value   : '0x00',
  chainId : 61
};

const tx = new Tx(rawTx);
tx.sign(privateKey);
const serializedTx = tx.serialize();
console.log('transaction')
console.log(serializedTx.toString('hex'))

function waitForTransactionReceipt(hash) {
  console.log('waiting for contract to be mined');
  web3.eth.getTransactionReceipt(hash, (e, r) => {
    if (r == null) {
      setTimeout(() => {
        waitForTransactionReceipt(hash);
      }, 60000);
    } else {
      // The transaction was mined, we can retrieve the contract address
      console.log('contract address: ' + r.contractAddress);
      console.log(r)
    }
  });
}

console.log('broadcasting...')
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), (err, hash) => {
  if (err) { console.log(err); return; }
  // Log the tx, you can explore status manually with eth.getTransaction()
  console.log('contract creation tx: ' + hash);
  // Wait for the transaction to be mined
  waitForTransactionReceipt(hash);
});

#8

for realtime communication join https://t.me/rados


#9

SIMPLE TX WITH NODEJS

var Web3 = require('web3');
web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
var Tx = require('ethereumjs-tx');
var Wallet = require('ethereumjs-wallet');

//amount, sender, reciever, privatekey, chatID
var sender = 'MY ADDRESS // SENDING ADDRESS';
var privatekey = 'PRIVATE KEY OF SENDER ADDRESS'
var receivingAddr = 'RECIEVER ADDRESS';

var privateKey = new Buffer(privatekey, 'hex');
var receivingAddr = reciever;
var txValue = web3.utils.numberToHex(web3.utils.toWei(amount, 'ether'));

/*
  you can also sign Transactions with keystore + pwd
  //const keystore = <JSON_HERE>;
  //const decryptedAccount = web3.eth.accounts.decrypt(keystore, <KEYSTORE_DECRYPT_PASSWORD>);
*/

var nonce = web3.eth.getTransactionCount(sender, function(err, txNonce) {
  console.log('NONCE: ' + txNonce + ' -> ' + web3.utils.numberToHex(txNonce)); // 1
  var rawTx = {
    nonce: web3.utils.numberToHex(txNonce),
    gasPrice: '0x14f46b0400', //Fixed Values, you can use numberToHex(toWei())
    gasLimit: '0x55f0', //Fixed Values, you can use numberToHex(Gaslimit)
    to: receivingAddr,
    value: txValue
  }

  //Signing Tx
  var tx = new Tx(rawTx);
  tx.sign(privateKey);
  var serializedTx = tx.serialize();

  //Waiting for confirm, using .on('receipt')!!
  web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')) // Broadcast the transaction to the network
    .on('receipt', (finishTX) => {
      console.log('TRANSACTION SUCCESS!!!\nMINED IN BLOCK #' + finishTX.blockNumber + '\n' + 'http://gastracker.io/tx/' + finishTX.transactionHash);
    });
 });

works with latest nodeJS version + latest web3 version
have fun.


#10

here a simple solution with php/curl if needed:

function sendTX($from, $to, $val, $pass){
    $web3 = "http://provider";
    $data = array(
                 "method" => "personal_sendTransaction",
                 "params" => array(["from" => $from,
                     "to" => $to,
                     "value" => $val],$pass),
                 "id" => "1",
                 "jsonrpc" => "2.0",
                 );
    $json_encoded_data = json_encode($data);
    $ch = curl_init($web3);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_encoded_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json_encoded_data))
    );
    $result = json_decode(curl_exec($ch));
    curl_close($ch);
    $parsed = $result->result;
 return $parsed;
}

greetz