Skip to content

Instantly share code, notes, and snippets.

@DonkeVerse
Last active January 11, 2022 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DonkeVerse/3a4e5af448c578386079cda59ed53ad0 to your computer and use it in GitHub Desktop.
Save DonkeVerse/3a4e5af448c578386079cda59ed53ad0 to your computer and use it in GitHub Desktop.
uint256 private constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 private ticketGroup0 = MAX_INT;
uint256 private ticketGroup1 = MAX_INT;
uint256 private ticketGroup2 = MAX_INT;
uint256 private constant MAX_TICKETS = 3 * 256;
function claimTicketOrBlockTransactionV5(uint256 ticketNumber) external {
    require(ticketNumber < MAX_TICKETS, "bad ticket");
    uint256 storageSlot;             // rename storageOffset to storageSlot to be more clear since we aren't using an array
    uint256 offsetWithin256;
    uint256 localGroup;
    uint256 storedBit;
    unchecked {
        storageSlot = ticketNumber / 256;
        offsetWithin256 = ticketNumber % 256;
    }
        
    //solhint-disable-next-line no-inline-assembly
    assembly {
        storageSlot := add(ticketGroup0.slot, storageSlot)    // ticketGroup0.slot is the storage slot, we add storageSlot
        localGroup := sload(storageSlot)                      // load whatever slot we are pointing to into localGroup
    }
 
    storedBit = (localGroup >> offsetWithin256) & uint256(1); // same code as before
    require(storedBit == 1, "already claimed");
    localGroup = localGroup & ~(uint256(1) << offsetWithin256);

    //solhint-disable-next-line no-inline-assembly
    assembly {
        sstore(storageSlot, localGroup)                        // store localGroup at the original storage slot
    }
}

Gas Cost: 26,541
Gas Cost - Transaction Cost (21,000): 5,541

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment