5

I use ganache-cli to build local blockchain and truffle to deploy contract. To interact with deployed contracts i use truffle console. For example i transfer tokens from my current account(that is web3.eth.personal.getAccounts()[0]) to web3.eth.personal.getAccounts()[1] after this i want to change my current account to web3.eth.personal.getAccounts()[1] address.

How to do that?

raury
  • 85
  • 1
  • 7
  • Can you give code example how you do the transfer and what do you mean by "current acount"? (There is a "default account" which web3 uses if you don't specify the sender, but I'm not sure if that's what you mean without the code example). – Petr Hejda Apr 24 '21 at 19:07
  • @PetrHejda yes current = default and transfer is just erc20 transfer method implementation. For example my default address is '0x123' and i transfer tokens to '0x456', after that i want to transfer this tokens from '0x456' to '0x789' but i cant because my current address is '0x123' instead of '0x456'. If you have worked with remix you possibly know that it is possible to change account when contracts are deployed. So i suppose i can do the same in truffle through console but dont know how. – raury Apr 24 '21 at 22:40

2 Answers2

3

Changing the value of web3.eth.defaultAccount doesn't work for me. But configuring from in the truffle.js works.

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*", 
      from: "0x12345678"
    }
  }
};
Greg
  • 31
  • 2
2

You can set the default account as

web3.eth.defaultAccount = web3.eth.personal.getAccounts()[1];

or simply as an address

web3.eth.defaultAccount = '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe';

Mind that Ganache by default only has 10 predefined accounts that it knows the private keys to. So you need to pass an address that Ganache knows private key to. If you pass an unknown account address, web3 (and Ganache) will not be able to submit transactions using this (unknown) address.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100