2

I was practising on a smart contract, and noticed that it gives out two different address for the same contract deployed while testing it.

const Test = artifacts.require('./Test.sol');

contract('Test', function(accounts) {

    describe('Test1 attributes', () => {
        let dInstance;
        beforeEach(async () => {
            dInstance = await Test.new();
        });

        it('has the address', async () => {
            const address = dInstance.address;
            const bal = await web3.eth.getBalance(address);
            assert(address != "0x" + "0".repeat(40),'has contract address');
            console.log('Current Contract:', address);
            console.log('Current Contract balance:', bal);
        });
    });

    describe('Test2 attributes', () => {
        let dInstance;
        beforeEach(async () => {
            dInstance = await Test.new();
        });

        it('has the address', async () => {
            const address = dInstance.address;
            const bal = await web3.eth.getBalance(address);
            assert(address != "0x" + "0".repeat(40),'has contract address');
            console.log('Current Contract:', address);
            console.log('Current Contract balance:', bal);
        });
    });


})

The truffle tests passed and I could see two different addresses for the same contract.

Contract: Test
    Test1 attributes
Current Contract: 0xCFefb2b6a91901ceb0A7Ea02a688958b0E2E1279
Current Contract balance: 0
      ✓ has the address
    Test2 attributes
Current Contract: 0xe478Aad670D90474c28b63C150bc3E404Cd0F5A3
Current Contract balance: 0
      ✓ has the address


  2 passing (273ms)

Could you please advice me on what might be the cause? I would appreciate discussions over this. Thanks.

2

Because you are using beforeEach at the beginning each describe, so the contract gets redeployed (a new instance of it is created) before every it within each describe.

Change it to before, and the contract will get deployed only once within each describe (you'll still get different addresses of course).

Move this before outside of all describe scopes, and the contract will get deployed only once per each execution of the test.

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.