0

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

1 Answer 1

1

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.

1
  • Dude, you rock !
    – Alxndr BRL
    Commented Dec 8, 2021 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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