Loading...
Sending etheres from one account to other using wallet is so easy, but one developer may always need to execute the transaction in server side, so lets see hot to execute transaction from backend node server
There are may methods to do this, I will explain easiest one for the beginners point of view. For this tutorial we are using ropsten testnet, you can use any but keep same testent everywhere otherwise it will not work.
We need account public,private key pairs of sender and only public key address of receiver. You can get it from metamask itself.
we need npm web3 module you can install it from
npm install web3
npm install @truffle/hdwallet-provider
You can use localhost if you are using ganache , but for ropsten infura is good, go to infura website create account craete poject and get rpc url it will look like this - https://ropsten.infura.io/v3/your_api_key
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "",
"license": "ISC",
"dependencies": {
"@truffle/hdwallet-provider": "^1.4.1",
"express": "^4.17.1",
"web3": "^1.2.9"
}
}
var express = require('express');
var Web3 = require('web3');
const Provider = require('@truffle/hdwallet-provider');
var app = express();
var port = process.env.PORT || 3000;
var rpcurl = "infura rpc url";
var senderaddress = "address";
var receiveraddress = "addresss";
var senderprivatekey = 'private key'
const sendEther = async () =>{
console.log("in function");
var provider = new Provider(senderprivatekey, rpcurl);
var web3 = new Web3(provider);
console.log("provider set transaction initiated");
web3.eth.sendTransaction({
from: senderaddress,
to: receiveraddress,
value: '100000000000000000' // 0.1 ether 10^17
})
.then(function(receipt){
console.log(receipt);
});
}
// transaction may take a few min to execute since we are using ropsten so be patient
sendEther();
app.listen(port);
console.log('listening on', port);
The above code is self explanatory !
You just need to change the variables according to your need thats it,
Happy DApp Building !