[Ethereum] Create new account in ganache

dappsetherjavascriptweb3js

I'm creating a Dapp which provide the user with individual account. while developing, when i create a account by

const accounts = await web3.eth.personal.newAccount('test');

the account is created with 0 balance. So I want to transfer some eth from existing ganache account to the newly created account. And so, I did

web3.eth.personal.unlockAccount(accounts, 'test', 10000)
web3.eth.sendTransaction({to:accounts, from:0x1d28f28f0b9B27FeA2aCAd1428485334d1f7429E,value:web3.utils.toWei("5", "ether")})

where accounts contains the address of newely created account from contains an account in ganache. When i execute it, I get these two errors

Uncaught (in promise) Error: Returned error: sender account not recognized
Uncaught (in promise) Error: Returned error: sender doesn't have enough funds to send tx. The upfront cost is: 1800000000000000 and the sender's account only has: 0

What i'm trying to do is, to create a new account when user signs up and transfer some ether to it so that the user can write something to the smart contract.

Is there any best way to create an account for the user and make it ready (with some ether in it) to write something to the smart contract. or how to manage this account creation when deploying to a testnet.

Best Answer

Should not pass the ganache account directly.

  const accounts = await web3.eth.getAccounts();
  const newAccount = await web3.eth.personal.newAccount('test');
  console.log("newAccount", newAccount);
  await web3.eth.personal.unlockAccount(newAccount, 'test', 10000);
  await web3.eth.getBalance(accounts[0], (err, bal) => { console.log("Ganache balance", bal); } );
  await web3.eth.sendTransaction({to:newAccount, from:accounts[0], value:web3.utils.toWei("5", "ether")});
  await web3.eth.getBalance(newAccount, (err, bal) => { console.log("New Account balance", bal); } );

by getting the account await web3.eth.getAccounts() solved the issue.

enter image description here

Related Topic