solidity – Why new MyContract() in Truffle Returns Address 0x000

soliditytruffle

I'm trying to test my code in Truffle but I'm facing something weird, when I create a new contract instance in one my functions, it seems to have the address 0x0000.

My function:

function createNewPot(string memory _name, string memory _description) public {
        uint newPotIndex = lastPotIndex++;
        potList[newPotIndex] = new Pot(this, newPotIndex, _name, _description, msg.sender);
}

My test:

describe('Pot creation', () => {
        it('creates a new pot', async () => {
            const title = "Titre de dingue"
            const description = "Description de ouf"

            await potManager.createNewPot(title, description, { from: sophie })
            let lastPotIndex = await potManager.lastPotIndex.call()
            let potCreatedAddress = await potManager.potList.call(lastPotIndex)

            console.log({ potCreatedAddress })
        })
    })

And here is the result of my console.log:
{ potCreatedAddress: '0x0000000000000000000000000000000000000000' }

Do you know why am I not receiving a valid address ?
Thanks

Best Answer

Your issue is here :

uint newPotIndex = lastPotIndex++;

This is a post incrementation so basically equivalent to :

uint newPotIndex = lastPotIndex;
lastPotIndex = lastPotIndex + 1;

By opposition to a pre incrementation equivalent to :

lastPostIndex = lastPostIndex + 1;
uint newPotIndex = lastPotIndex;

So when you call :

let lastPotIndex = await potManager.lastPotIndex.call()

You get the index of the newPotIndex + 1 ( because you did a post incrementation and you are getting potList[lastPotIndex] or potList[newPotIndex + 1]) which is not initialized, so defaults to a value of 0. Your code should revert on arrays, so I assume that potList is a mapping.

I suppose that the value you meant to display is accessible through :

let potCreatedAddress = await potManager.potList.call(lastPotIndex - 1)

Be careful to the special case where lastPotIndex == 0 though.