Search code examples
solidity

Is there a better way to create unique id instead of uint256 in Solidity?


I am working on a Simple TicTacToe (my first smart contract).

I have a Game struct. Each Game has an uint256 id.

The thing is I think it's weird to use an id that has the possibility to overflow.

I guess that Ethereum smart contract doesn't use uint256 for any of their ids, because if they have 1M transactions their ids have a chance to overflow, right?

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

contract TickTackToe {
    Game[] public games;

    uint256 uniqueGameIndex = 0;

    struct Game {
        address owner;
        address opponent;
        byte[9] board;
        bool isOwnerTurn;
        uint256 game_id;
    }

    function mintGame() public {
        Game memory game = Game(msg.sender, address(0), [0,0,0,0,0,0,0,0,0], true, uniqueGameIndex++);
        games.push(game);
    }

    function join(uint256 gameIdx) public {
        Game storage game = games[gameIdx];
        game.opponent = msg.sender;
    }
}

Thanks


Solution

  • The number at the end of the uint<N> datatype name is the size of this datatype in bits - not the maximal decimal value.

    Ethereum transaction hash has the length of 256 bits as well - usually represented as 64 hex characters.

    if they have 1M transactions their ids have a chance to overflow, right?

    The largest decimal number that fits into the 256 bit space is 115,792,089,237,316,195,423,570,985,008,687,907,853,269,984,665,640,564,039,457,584,007,913,129,639,935 (source).

    So 1,000,000 safely fits into uint256.