6

How can i send payments from my ubuntu ethereum node to any address?

Is there any working example, that may help me to get this done?

CODE EDITED

var Web3 = require('web3');
var Tx = require('ethereumjs-tx');
// Show Web3 where it needs to look for a connection to Ethereum.
//web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545'));
web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/<account-id>'));
var gasPrice = "2";//or get with web3.eth.gasPrice
var gasLimit = 3000000;
var addr = "0x......................";
var toAddress = "0x..............................";
var amountToSend = "0.00192823123348952"; //$1
var nonce = web3.eth.getTransactionCount(addr); //211;
var rawTransaction = {
"from": addr,
"nonce": web3.utils.toHex(nonce),
"gasPrice": web3.utils.toHex(gasPrice * 1e9),
"gasLimit": web3.utils.toHex(gasLimit),
"to": toAddress,
"value": amountToSend ,
"chainId": 41 //remember to change this
};
var privateKey = ".........................................................";
var privKey = new Buffer(privateKey, 'hex');
console.log("privKey  : ", privKey);
var tx = new Tx(rawTransaction);
tx.sign(privKey);
var serializedTx = tx.serialize();
console.log('serializedTx : '+serializedTx);
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
if (!err)
{
console.log('Txn Sent and hash is '+hash);
}
else
{
console.error(err);
}
});
1
  • Is it possible to send full balance in one transaction calculating before the gas cost and set the correct value amount for setting the account in zero?
    – Jonathan
    Dec 19, 2021 at 18:51

4 Answers 4

12

There are 2 ways to do it. If you want to use the address with its password, follow the method below.

web3.personal.unlockAccount(addr, pass);
const toAddress = "0x...."; // Address of the recipient
const amount = 2; // Willing to send 2 ethers
const amountToSend = web3.utils.toWei(amount, "ether"); // Convert to wei value
var send = web3.eth.sendTransaction({ from: addr, to: toAddress, value: amountToSend });

For this above method, you would need the keystore file to be present within the same Ubuntu machine.

If you want to send with privateKey:

var gasPrice = 2; // Or get with web3.eth.gasPrice
var gasLimit = 3000000;

var rawTransaction = {
  "from": addr,
  "nonce": web3.toHex(nonce),
  "gasPrice": web3.utils.toHex(gasPrice * 1e9),
  "gasLimit": web3.utils.toHex(gasLimit),
  "to": toAddress,
  "value": amountToSend,
  "chainId": 4 // Remember to change this
};

var privKey = new Buffer(privateKey, 'hex');
var tx = new Tx(rawTransaction);

tx.sign(privKey);
var serializedTx = tx.serialize();

web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
    if (!err)
    {
        console.log('Txn Sent and hash is '+hash);
    }
    else
    {
        console.error(err);
    }
});
20
  • I think first method is very easy to be used, Yes i have keystore files saved on the same ubuntu server. If i use first code then transaction will be success with just password only? web3.personal.unlockAccount(addr, pass); Do i need to specify keystore file too? If yes then how and where? after transaction is success, how can i get transaction hash and other info to check trasnactions status?
    – shawn
    Mar 17, 2018 at 10:21
  • But the best practice suggests the second method to go for. You no need to specify the keystore as it will be picked by web3 and related libraries. You can use send or, can change the sendTransaction just same like sendRawTransaction to get the hash value
    – Rajesh
    Mar 17, 2018 at 10:25
  • In second method, it needs Private key, So how private key will be picked from keystore file?
    – shawn
    Mar 17, 2018 at 10:33
  • keythereum library will help you with that. datadir parameter is optional though.You may need to specify if you are testing on other networks const keyObject = keythereum.importFromFile(addr, datadir); const privateKey = keythereum.recover(pass, keyObject);
    – Rajesh
    Mar 17, 2018 at 10:38
  • If you are using the second method, you won't need node to be running on your local system, you can use infura.io or similar service providers in that case. Refer the below for the first method to get txn hash https://ethereum.stackexchange.com/a/43012/20357
    – Rajesh
    Mar 17, 2018 at 10:41
2

There are multiple ways of doing it. If you want to do it from NodeJS using Web3:

const Web3 = require("web3");
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:" + port));
web3.eth.sendTransaction({from: accounts[0],to: accounts[1], value: web3.utils.toWei("1", "ether")})
  • accounts[0] and [1] should be HEX addresses
  • the gas spent will be 21 000 as a standard for all Ethereum transactions to prevent several attacks

If you want to do it using Ubuntu and Geth, checkout this article walking you through the full process step by step: https://blog.gophersland.com/ethereum-how-to-transfer-funds-using-geth-cli

0

First, open a terminal and attach to your node geth attach http://localhost:8545 (replace with or your appropriate port / internal IP).

Next, we're gonna check if you're synced up with the chain. Type eth.syncing, if it returns false that means that your Geth is up to date and is not currently syncing. It keeps importing the latest block to remain up to date. Check eth.blockNumber against a block explorer if you want to double-check.

Then, we can construct the transaction using the following syntax from go-ethereum/wiki/Sending-ether.

Example: eth.sendTransaction({from:eth.coinbase, to:"0x0000000000000000000", value: web3.toWei(0.05, "ether")}

  • 0x0000000000000000000is the recipient address.
  • 0.05 is the amount, which would be 0.05 ether

You can check on the geth console if eth.coinbase is the account you'd like to send from.

Then hit enter and you'll be presented with the transaction hash which is now broadcasted to the network.

0

You can check this helper script which sends BNB from a Binance Smart Chain waller: https://github.com/religion-counter/onlyone/blob/main/helper-scripts/send-bnb.js

// Sends ${amountToSend} BNB from ${sourceAccount.address} to ${targetAccounts[targetIndex].address}
// targetIndex is passed as argument - process.argv.splice(2)[0];
// sourceAccount is specified in SOURCE_ACC.json
// targetAccounts are specified in TARGET_ACCS.json
// The sourceAccount is just an object with address and privateKey values.
// targetAccounts are JSON with Array with objects with address value.
// originalAmountToSend is the amount that the script sends

var fs = require('fs')
var Tx = require('ethereumjs-tx').Transaction;
var Web3 = require('web3')
var Common = require('ethereumjs-common').default;

var web3 = new Web3(new Web3.providers.HttpProvider('https://bsc-dataseed.binance.org/'))
var BSC_FORK = Common.forCustomChain(
    'mainnet',
    {
        name: 'Binance Smart Chain Mainnet',
        networkId: 56,
        chainId: 56,
        url: 'https://bsc-dataseed.binance.org/'
    },
    'istanbul',
);

var originalAmountToSend = '0.01';
var amountToSend = web3.utils.toWei(originalAmountToSend, 'ether');
var sourceAccount = JSON.parse(fs.readFileSync('SOURCE_ACC.json', 'utf-8'));
var targetAccounts = JSON.parse(fs.readFileSync('TARGET_ACCS.json', 'utf-8'));

var targetIndex = Number(process.argv.splice(2)[0]);

console.log(`Sending ${originalAmountToSend} BNB from ${sourceAccount.address} to ${targetAccounts[targetIndex].address}`);

async function sendBNB(fromAddress, toAddress, pk, amountToSend) {

    var privateKey = Buffer.from(pk.slice(2), 'hex');
    var count = await web3.eth.getTransactionCount(fromAddress);

    var rawTransaction = {
        "from": fromAddress,
        "gasPrice": web3.utils.toHex(5000000000),
        "gasLimit": web3.utils.toHex(220000),
        "to": toAddress,
        "value": web3.utils.toHex(amountToSend),
        "nonce": web3.utils.toHex(count)
    };

    var transaction = new Tx(rawTransaction, { 'common': BSC_FORK });
    transaction.sign(privateKey);

    var result = await web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'));
    console.log(result);
    return result;
}

console.log(
    sendBNB(sourceAccount.address, targetAccounts[targetIndex].address, sourceAccount.privateKey, amountToSend));

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.