Using Web3.js to Send Transactions on Harmony
Last updated
Was this helpful?
Was this helpful?
const Web3 = require('web3');
const BN = require('bn.js');
HMY_PRIVATE_KEY = 'YOUR_PRIVATE_KEY';
HMY_TESTNET_RPC_URL = 'https://api.s0.b.hmny.io';
const web3 = new Web3(HMY_TESTNET_RPC_URL);
let hmyMasterAccount = web3.eth.accounts.privateKeyToAccount(HMY_PRIVATE_KEY);
web3.eth.accounts.wallet.add(hmyMasterAccount);
web3.eth.defaultAccount = hmyMasterAccount.address
const myAddress = web3.eth.defaultAccount;
console.log('My address: ', myAddress);const balance = await web3.eth.getBalance(myAddress);
console.log('My balance: ', balance / 1e18);const newAccount = web3.eth.accounts.create();
console.log('New account created: ', newAccount.address);const gasPrice = new BN(await web3.eth.getGasPrice()).mul(new BN(1));
const gasLimit = 6721900;
const value = 1 * 1e18; // 1 ONE
const from = web3.eth.defaultAccount;
const to = newAccount.address; // account was created on prev step
const result = await web3.eth
.sendTransaction({ from, to, value, gasPrice, gasLimit })
.on('error', console.error);
console.log(`Send tx: ${result.transactionHash} result: `, result.status);
const newAddrBalance = await web3.eth.getBalance(newAccount.address);
console.log('New account balance: ', newAddrBalance / 1e18);