16

I'm using the $ truffle console.
I can see my available accounts using truffle(development)> web3.eth.accounts.

But when I run some smart contract code, which account is running the contract?

And, how can I change the account which is running the contracts in the truffle console?

kris
  • 380
  • 1
  • 4
  • 12

2 Answers2

34

In truffle console:

var accounts;
// in web front-end, use an onload listener and similar to this manual flow ... 
web3.eth.getAccounts(function(err,res) { accounts = res; });

var account1 = accounts[0]; // first account
var account2 = accounts[1]; // second account, if exists
...

var contract;
Contract.deployed()
.then(function(response) {
  contract = response;
  return contract.function(arg1, arg2, {from: account2}); // send txn from 2nd account

In Truffle tests you can start out with accounts passed in for convenience:

contract("basic test pattern", function(accounts) {
  owner = accounts[0];
  ...

Hope it helps.

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145
  • I did that bug msg.sender is always '0x00' – shredding Apr 11 '18 at 14:35
  • Using the contract of truffle unbox example, and following your specifications it gives this error: MetaCoin Error: invalid address (arg="receiver", coderType="address", value=undefined)

    . Actually accounts variable successfully stores two addresses. I used accounts[1] to transfer using the .sendCoin method of the MetaCoin contract, uint as 2nd argument with the quantity to transfer, and {from: accounts[0]}. solc is 0.5.16

    – José Crespo Barrios Oct 10 '20 at 18:51
6

Now you can use await to simplify code:

let accounts = await web3.eth.getAccounts()
memorybox
  • 161
  • 1
  • 1