0

i have a working dapp on frontend sending transactions and signing them through connected wallet (metamask).

I want to transfert this logic of sending transactions to my backend (nodejs).

so there will be no signing transactions nor metamask.

how can i do that ?

2 Answers 2

2

Hi dev advocate at Chainstack here!

The best way will be to use a web3 library; I recommend web3.js if you want to work in JavaScript.

Remember that you still need to sign the transactions with your private key; it's just done programmatically instead of using the MetaMask front-end.

The following is the basic code to create and send a transaction using web3.js.

var Web3 = require('web3');
var node_URL = 'CHAINSTACK_NODE_URL';
var web3 = new Web3(node_URL);
var Tx = require('ethereumjs-tx').Transaction;

// Logic of this code:
    // Set the addresses and private key to sign the transaction
    // Build transaction 
    // Sign and send the transaction 

// Addresses and private key
const sender = "SENDER_ADDRESS";
const receiver = "RECEIVER_ADDRESS";
const private_key = Buffer.from('PRIVATE_KEY', "hex"); 

// Build the transaction
web3.eth.getTransactionCount(sender, (err, transactionCount) => {
    const transaction_Object = {
        to: receiver,
        gasPrice: web3.utils.toHex(web3.utils.toWei("20", "gwei")),
        gasLimit: web3.utils.toHex(21000),
        nonce: web3.utils.toHex(transactionCount),
        value: web3.utils.toHex(web3.utils.toWei("0.5", "ether")),
    };

    // Signing the transaction 

    // create a new transaction object to sign 
    const tx = new Tx(transaction_Object, {
        chain: "ropsten"
    });

    // sign the transaction using the private key  
    tx.sign(private_key);

    //   Send signed transaction to the blockchain 
    const sTx = tx.serialize();
    const rawTransaction = "0x" + sTx.toString("hex");

    web3.eth.sendSignedTransaction(rawTransaction, (err, hash) => {
        console.log("TxHash:" + hash);
        console.log(err);
    });
})

This is the code to send a transaction from an account to another. You will find more code examples on the Node API reference page.

0

you could get network access via alchemy or Infura and create and sign transactions using a framework like ethers.js or web3.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.