In my truffle tests, I am trying to call a function from an account other than the default account, so not accounts[0] from the below result. web3.eth.defaultAccount doesn't seem to work.

web3.eth.getAccounts().then(accounts => {
  accounts[0] // Don't use this.
  web3.eth.defaultAccount = accounts[1].
  contractInstance.foo() // called from accounts[0]

I know I can use

contractinstance.foo({from: accounts[1]})

but I don't want to add this parameter every time, as most of the code will use accounts[1].

Is there a way to change the default account or am I missing something here? Thanks

  • I'm personally not aware of any other way. if you find it troubling to write contractinstance.foo({from: accounts[1]}) in many places, then put it inside a function and call that function instead (declare and implement that function inside the function which takes accounts as an input parameter, so that you don't have to pass it on every call). – goodvibration Oct 8 '19 at 16:20

Since you are using Truffle you can override the contract's defaults with .defaults()

const MyContract = artifacts.require("MyContract.sol")

  from: "0x..."

@truffle/contract documentation (previously named truffle-contract)

| improve this answer | |

Your Answer

