How to deal when testing with eth brownie for a sender with not enough balance

Viewed 237

I'm trying in my tests to simulate a situation where a sender calls a payable method of a contract but does not have enough balance. A sample code would be:

with brownie.reverts():
   contract.buy({'from': accounts[0], 'value': 100000000000000000000000000})

Instead of the test continuing I get a ValueError:

E ValueError: sender doesn't have enough funds to send tx. The upfront cost is: 100000000000000000000000000 and the sender's account only has: 100000000000000000000

How do I catch such errors with brownie?

1 Answers

You try to send more eth than is on account balance. If you use use ganache-cli the initial balance of each account is 100 eth. You can create account of bigger balance by collecting all eth into single account, as follow:

Create following brownie-config.yaml:

networks:
  default: development
  development:
    cmd_settings:
      accounts: 50

where you can change 50 to your desired number. Then create script.py file in scripts/ directory with following code:

from brownie import accounts, Wei

def main():
    print('initial number of accounts ', len(accounts))
    balance = accounts[0].balance()
    print('initial balance of account_0 in Eth ', Wei(balance).to('ether'))

    # transfer all eth into account_0
    for i in range(1, len(accounts)):
        amount = accounts[i].balance()
        accounts[i].transfer(accounts[0], amount)

    balance = accounts[0].balance()
    print('final balance of account_0 in Eth ', Wei(balance).to('ether'))

Run:

brownie run scripts/script.py

to check final balance of accounts[0] EOA

Warning: It loops over all accounts and make transfer for each of them, so for big accounts number script can run really slow

Related