Predicting Smart Contract Behavior

So how might we predict how a given Smart Contract will behave? For example, suppose we are about to click "submit" on a transaction to mint an NFT. What will the smart contract do?

To predict this we must obviously know the Smart Contract's code. Fortunately, this code is on the blockchain and available to everyone. For simplicity let's assume the contract is verified on Etherscan, though the argument doesn't rely on this fact.

You head to Etherscan and look up the contract's mint() function:

function mint(uint256 id) {
    require(_ownerOf[id] == address(0), "Id already minted");

    balanceOf[to]++;
    ownerOf[id] = msg.sender;
}

This is a simple NFT contract. It's free and you can choose any id you want to mint, as long as it's not already taken. If the id is available, your balance will go up by 1 and your address will be stored in the mapping of token ids to owners.

So you reason: I have none of these NFTs yet, so my balance is currently 0. I'm minting token id 99, which is currently unminted. So after this transaction the smart contract storage will have 1 as my balance and will map id 99 to my address as the owner.

After the the mint succeeds, you check the NFT contract's storage and, sure enough, your prediction of the results of the mint transaction was correct!

And of course it couldn't be any other way. By design, Smart Contracts operate entirely deterministically based on their input. They have no source of entropy or randomness. Everything about their behavior can be predicted in advance, so long as you know their inputs.

Given you can predict exactly what is in the Smart Contract's state without looking, why did you just pay to update that state?

Predicting with Certainty

Your prediction in this simplified example actually was not certain. This is because you cannot know in advance whether someone will mint id 99 ahead of you, thereby invalidating your transaction.

Unlike Smart Contract logic, transaction ordering within a secure blockchain is non-deterministic and unpredictable. If you and someone else are both going after id 99, there is no systematic way to determine who will win.

So if you want to predict with certainty what a Smart Contract will do, you must wait until after the transaction is included in a block. At this point you can check the history of transactions to see if someone minted id 99 first. If they did, we will know that your transaction didn't affect contract state.

Basically it's actually not possible to predict what a Smart Contract will do in advance, but you can know what it would have done immediately after your mint transaction is included in a block.

Last updated