0

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 at 16:20
1

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

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

MyContract.defaults({
  from: "0x..."
})

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.