5

I have deployed my contract in private blockchain, now I am calling functions using Nodejs and web3. Here, I want to transfer tokens for which I need to unlock my account from which I am transferring the tokens and then I want to check the balance of the account to which the tokens were transfered. Here, is the code:

var Web3 = require('web3');
var web3 = new Web3(new 
Web3.providers.HttpProvider("http://localhost:8545"));
var Personal = require('web3-eth-personal')
var personal = new Personal(Personal.givenProvider)

var ABI = {contract abi}
web3.eth.personal.unlockAccount("0xcc8d743....97278fe497ee90...", "password", 
60).then(
contract.methods.transfer('0x43a91c052B913299Dd4F47C91bB7d982D8A8632e', 
2).send({from:'0xCc8d743eB486bF38ED1197278Fe497eE90...', gas:210000})
.on("result", 
contract.methods.balanceOf('0x43a91c052B913299Dd4F47C91bB7d982D8A8632e')
.call((error, result)=>console.log(result))).on("error", function(error) 
{console.log(error);}))

But I am getting the balance of the account first which should be called after transfer function and for the transfer function I am getting the error saying 'need authentication'.

100000008
Error: Returned error: authentication needed: password or unlock

1 Answer 1

0

Use this code. It's all mentioned clearly in documentation, unlocking account and send transaction. You can also see how-to-call-my-contracts-function-using-sendtransaction

let isUnlocked = await web3.eth.personal.unlockAccount("0xcc8d743....97278fe497ee90...", "password", 
60)

if(isUnlocked){
  myContract.methods.myMethod(123).send({from: '0xcc8d743....97278fe497ee90...'}, (error, txHash) => {
    // handle the error here
    if(!err && txHash){
      myContract..methods.balanceOf('0xcc8d743....97278fe497ee90...', (err, balance) => {
        console.log('balance is', balance)
      })
    }
});

}

Using Callbacks

web3.eth.personal.unlockAccount('0x..', 'password', (unlocked) => {
  myContract.methods.myMethod(123).send({from: '0xcc8d743....97278fe497ee90...'}, (error, txHash) => {
    if(!err && txHash){
      myContract..methods.balanceOf('0xcc8d743....97278fe497ee90...', (err, balance) => {
        console.log('balance is', balance)
      })
    }
  });
})
2
  • If I use await I have to use async also. I don't know how to use async and await @Prashant Prabhakar Singh
    – crypto S.
    Commented Jan 16, 2019 at 9:09
  • @cryptoS. It's no big deal. Still, if you don't want to use async-await. use callbacks for unlocking too. Commented Jan 16, 2019 at 10:03

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.