Akash Vekariya
Akash Vekariya

Reputation: 345

What happens when multiple call asking for the current counter in solidity gets the same value?

I was learning to create NFT markertplace (openZeppelin-ERC721) and got stuck in counter. I wander what happen when this code below is executed.

pragma solidity ^0.8.0;

library Counters {
    struct Counter { uint256 _value; }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked { counter._value += 1; }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked { counter._value = value - 1; }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

Suppose person A and B both are trying to create NFT and the counter is supposed to increment and give them ID for their NFTs. But, what if they both try to create NFT at the same time, I mean ofcourse there is a lot of chance of happening this. Will the other NFT will be discarded, get a new ID and if so, wouldn't it take a bit longer than expected? what about the GAS fees then???

Lots of question I hope you understand what I am trying to say!

Upvotes: 0

Views: 1020

Answers (3)

Muhammad Hamza
Muhammad Hamza

Reputation: 61

Which ever transaction is picked first will get the first token (counter) and the other one comes after it.

Upvotes: 0

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83428

But, what if they both try to create NFT at the same time, I mean ofcourse there is a lot of chance of happening this.

Your assumption is incorrect. Do not make assumption and always think critically.

All Ethereum transactions are executed sequentially and there is no theoretical way of having two transactions happening at the same time. Please see the transaction lifecycle in EVM based chains.

Upvotes: 1

djd
djd

Reputation: 173

I don't find in this code where it changes the NFT id. It's a counter that can increment or decrement a value. If two people create an nft at the same time, the function that handles nft ids will determine who gets what id based on which transaction is in the ethereum block first. No nft would get discarded unless that is what the smart contract is set to do. If you can explain what you mean by gas fees, you might find an answer.

Upvotes: 0

Related Questions