HoodFrens

0xa50adec47fccbde24b0214a831d3bdde4a1e0106

Verification
Verified
v0.8.20+commit.a1b79de6
Type
Contract
37,306 bytes
ABI entries
167
72 read · 46 write
License
mit

Contract information

Address
0xa50adec47fccbde24b0214a831d3bdde4a1e0106
Chain
Robinhood Chain (4663)
Compiler
v0.8.20+commit.a1b79de6
Optimization
Enabled
Creation tx
0x2ba390bb88…1155235f4e

Token

Not a token

This contract does not expose ERC-20 metadata.

Read contract (72)

BONDING_CURVE_DENOMINATOR()uint256
BPS()uint256
COMMISSION_BPS()uint256
CREATOR_FEE_BPS()uint256
DEFAULT_ADMIN_ROLE()bytes32
IPO_FEE_DURATION()uint256
IPO_LOTS_PER_CALL_MAX()uint256
IPO_LOTS_PER_CALL_MIN()uint256
IPO_MAX_LOTS_PER_WALLET()uint256
IPO_PRIZE_FEE_BPS()uint256
IPO_PROTOCOL_FEE_BPS()uint256
IPO_TRADES_PER_SECOND()uint256
LOTS_PER_CALL_MAX()uint256
LOTS_PER_CALL_MIN()uint256
LOT_SIZE_UNITS()uint256
MAX_CREATOR_FEE_BPS()uint256
MAX_IPO_FEE_DURATION()uint256
MAX_IPO_PRIZE_FEE_BPS()uint256
MAX_IPO_PROTOCOL_FEE_BPS()uint256
MAX_PROTOCOL_FEE_BPS()uint256
MAX_SELL_PRIZE_FEE_BPS()uint256
MAX_TOTAL_COMMISSION_BPS()uint256
MAX_TRANSFER_GAS()uint256
MIN_IPO_FEE_DURATION()uint256
MIN_TRANSFER_GAS()uint256
ONE_FULL_SHARE_IN_UNITS()uint256
PROTOCOL_FEE_GROSS_BPS()uint256
REFERRAL_FEE_BPS()uint256
ROLE_CARD_MANAGER()bytes32
ROLE_CARD_SENDER()bytes32
ROLE_ETH_PRIZE_MANAGER()bytes32
ROLE_REFERRER_MANAGER()bytes32
ROLE_STORAGE_CLEANER()bytes32
ROLE_TRADING_TOGGLER()bytes32
SELL_PRIZE_FEE_BPS()uint256
SHARES_DECIMALS()uint8
accruedCreatorFeesWei(uint256)uint256
calculateGrossSellPayoutByLots(uint256, uint256)uint256
calculateGrossSellPayoutByUnits(uint256, uint256)uint256
creatorWallet(uint256)address
customGasLimit(address)uint256
defaultTransferGasLimit()uint256
getAllPlayers(uint256, uint256)uint256[], string[], bool[]
getBuyPriceByLots(uint256, uint256)uint256
getBuyPriceByUnits(uint256, uint256)uint256
getBuyPriceRaw(uint256, uint256)uint256
getEffectiveGasLimit(address)uint256, bool
getFractionalRemainder(address, uint256)uint256, uint256, uint256
getIpoPrizeFeeEndTime(uint256)uint256
getPortfolioFractionalRemainders(address, uint256, uint256)uint256[], uint256[]
getPortfolioHoldingsInLots(address, uint256, uint256)uint256[], uint256[]
getPortfolioHoldingsInUnits(address, uint256, uint256)uint256[], uint256[]
getRoleAdmin(bytes32)bytes32
getUserPlayerHoldingInFullShares(address, uint256)uint256
getUserPlayerHoldingInLots(address, uint256)uint256
getUserPlayerHoldingInUnits(address, uint256)uint256
hasRole(bytes32, address)bool
isIpoPrizeFeeActive(uint256)bool
nextPlayerId()uint256
owner()address
pauseReason()string
paused()bool
pendingOwner()address
players(uint256)string, bool, uint256, uint256
prizeWallet()address
protocolWallet()address
referrerOf(address)address
sharesBalance(uint256, address)uint256
sharesSupply(uint256)uint256
supportsInterface(bytes4)bool
totalAccruedCreatorFeesWei()uint256
totalEthPrizesAwarded()uint256

Events (41)

BatchCleanupCompletedContractPausedContractUnpausedCreatorFeeAccruedCreatorFeePaidCreatorFeeUpdatedCreatorFeesClaimedCreatorWalletSetCustomGasLimitRemovedCustomGasLimitSetDefaultTransferGasLimitUpdatedEthPrizeAwardedEthPrizeDepositedFeesUpdatedIpoBuyFeesAppliedIpoParametersUpdatedIpoTrackingCleanedOwnershipTransferStartedOwnershipTransferredPausedPlayerAddedPlayerIPOPlayerSharesSupplyChangedPrizeTransferFailedReferralFeePaidReferralFeeRedirectedToProtocolReferrerMigratedReferrerSetRoleAdminChangedRoleGrantedRoleRevokedSharePrizeAwardedSharePrizeDepositedSharesTransferredTradeTradingParametersUpdatedTradingStatusUpdatedUnpausedUserSharesChangedWalletsUpdatedZeroBalanceCleaned

ABI

[
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "_prizeWallet",
        "type": "address"
      },
      {
        "internalType": "address",
        "name": "_protocolWallet",
        "type": "address"
      }
    ],
    "stateMutability": "nonpayable",
    "type": "constructor"
  },
  {
    "inputs": [],
    "name": "AccessControlBadConfirmation",
    "type": "error"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "account",
        "type": "address"
      },
      {
        "internalType": "bytes32",
        "name": "neededRole",
        "type": "bytes32"
      }
    ],
    "name": "AccessControlUnauthorizedAccount",
    "type": "error"
  },
  {
    "inputs": [],
    "name": "EnforcedPause",
    "type": "error"
  },
  {
    "inputs": [],
    "name": "ExpectedPause",
    "type": "error"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "owner",
        "type": "address"
      }
    ],
    "name": "OwnableInvalidOwner",
    "type": "error"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "account",
        "type": "address"
      }
    ],
    "name": "OwnableUnauthorizedAccount",
    "type": "error"
  },
  {
    "inputs": [],
    "name": "ReentrancyGuardReentrantCall",
    "type": "error"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "string",
        "name": "cleanupType",
        "type": "string"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "processed",
        "type": "uint256"
      }
    ],
    "name": "BatchCleanupCompleted",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "string",
        "name": "reason",
        "type": "string"
      }
    ],
    "name": "ContractPaused",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [],
    "name": "ContractUnpaused",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInWei",
        "type": "uint256"
      }
    ],
    "name": "CreatorFeeAccrued",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "wallet",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInWei",
        "type": "uint256"
      }
    ],
    "name": "CreatorFeePaid",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newCreatorFeeBps",
        "type": "uint256"
      }
    ],
    "name": "CreatorFeeUpdated",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "wallet",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInWei",
        "type": "uint256"
      }
    ],
    "name": "CreatorFeesClaimed",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "wallet",
        "type": "address"
      }
    ],
    "name": "CreatorWalletSet",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "recipient",
        "type": "address"
      }
    ],
    "name": "CustomGasLimitRemoved",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "recipient",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "gasLimit",
        "type": "uint256"
      }
    ],
    "name": "CustomGasLimitSet",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "oldLimit",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newLimit",
        "type": "uint256"
      }
    ],
    "name": "DefaultTransferGasLimitUpdated",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "winner",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "string",
        "name": "description",
        "type": "string"
      }
    ],
    "name": "EthPrizeAwarded",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInWei",
        "type": "uint256"
      }
    ],
    "name": "EthPrizeDeposited",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newSellPrizeFeeBps",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newProtocolFeeBps",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newIpoPrizeFeeBps",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newIpoProtocolFeeBps",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "currentCreatorFeeBps",
        "type": "uint256"
      }
    ],
    "name": "FeesUpdated",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "baseCostInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "prizeFeeInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "protocolFeeInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "totalCostInWei",
        "type": "uint256"
      }
    ],
    "name": "IpoBuyFeesApplied",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newIpoFeeDuration",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newIpoLotsPerCallMin",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newIpoLotsPerCallMax",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newIpoMaxLotsPerWallet",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newIpoTradesPerSecond",
        "type": "uint256"
      }
    ],
    "name": "IpoParametersUpdated",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "lotsUsed",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "tradesUsed",
        "type": "uint256"
      }
    ],
    "name": "IpoTrackingCleaned",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "previousOwner",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "newOwner",
        "type": "address"
      }
    ],
    "name": "OwnershipTransferStarted",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "previousOwner",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "newOwner",
        "type": "address"
      }
    ],
    "name": "OwnershipTransferred",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "address",
        "name": "account",
        "type": "address"
      }
    ],
    "name": "Paused",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "string",
        "name": "name",
        "type": "string"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "snipeAmountInUnits",
        "type": "uint256"
      }
    ],
    "name": "PlayerAdded",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "string",
        "name": "name",
        "type": "string"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "startTimestamp",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "endTimestamp",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "currentSupply",
        "type": "uint256"
      }
    ],
    "name": "PlayerIPO",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "int256",
        "name": "supplyChangeInUnits",
        "type": "int256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newTotalSupplyInUnits",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "currentPriceInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "marketCapInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "string",
        "name": "reason",
        "type": "string"
      }
    ],
    "name": "PlayerSharesSupplyChanged",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "intendedRecipient",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "string",
        "name": "description",
        "type": "string"
      }
    ],
    "name": "PrizeTransferFailed",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "referrer",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInWei",
        "type": "uint256"
      }
    ],
    "name": "ReferralFeePaid",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "intendedRecipient",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "seller",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      }
    ],
    "name": "ReferralFeeRedirectedToProtocol",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "oldReferrer",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "newReferrer",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "referralCount",
        "type": "uint256"
      }
    ],
    "name": "ReferrerMigrated",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "referrer",
        "type": "address"
      }
    ],
    "name": "ReferrerSet",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "bytes32",
        "name": "role",
        "type": "bytes32"
      },
      {
        "indexed": true,
        "internalType": "bytes32",
        "name": "previousAdminRole",
        "type": "bytes32"
      },
      {
        "indexed": true,
        "internalType": "bytes32",
        "name": "newAdminRole",
        "type": "bytes32"
      }
    ],
    "name": "RoleAdminChanged",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "bytes32",
        "name": "role",
        "type": "bytes32"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "account",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "sender",
        "type": "address"
      }
    ],
    "name": "RoleGranted",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "bytes32",
        "name": "role",
        "type": "bytes32"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "account",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "sender",
        "type": "address"
      }
    ],
    "name": "RoleRevoked",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "winner",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInUnits",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "string",
        "name": "description",
        "type": "string"
      }
    ],
    "name": "SharePrizeAwarded",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInUnits",
        "type": "uint256"
      }
    ],
    "name": "SharePrizeDeposited",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "from",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "to",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInUnits",
        "type": "uint256"
      }
    ],
    "name": "SharesTransferred",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "trader",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "bool",
        "name": "isBuy",
        "type": "bool"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amountInUnits",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "priceInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "feeInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newSupplyInUnits",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "bool",
        "name": "isIPOWindow",
        "type": "bool"
      }
    ],
    "name": "Trade",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newLotSizeUnits",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newLotsPerCallMin",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newLotsPerCallMax",
        "type": "uint256"
      }
    ],
    "name": "TradingParametersUpdated",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "bool",
        "name": "enabled",
        "type": "bool"
      }
    ],
    "name": "TradingStatusUpdated",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "address",
        "name": "account",
        "type": "address"
      }
    ],
    "name": "Unpaused",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "int256",
        "name": "amountChangeInUnits",
        "type": "int256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "newUserBalanceInUnits",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "totalCostInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "totalFeesInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "netAmountInWei",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "string",
        "name": "reason",
        "type": "string"
      }
    ],
    "name": "UserSharesChanged",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": false,
        "internalType": "address",
        "name": "newPrizeWallet",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "address",
        "name": "newProtocolWallet",
        "type": "address"
      }
    ],
    "name": "WalletsUpdated",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "user",
        "type": "address"
      }
    ],
    "name": "ZeroBalanceCleaned",
    "type": "event"
  },
  {
    "inputs": [],
    "name": "BONDING_CURVE_DENOMINATOR",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "COMMISSION_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "CREATOR_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "DEFAULT_ADMIN_ROLE",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "",
        "type": "bytes32"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "IPO_FEE_DURATION",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "IPO_LOTS_PER_CALL_MAX",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "IPO_LOTS_PER_CALL_MIN",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "IPO_MAX_LOTS_PER_WALLET",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "IPO_PRIZE_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "IPO_PROTOCOL_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "IPO_TRADES_PER_SECOND",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "LOTS_PER_CALL_MAX",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "LOTS_PER_CALL_MIN",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "LOT_SIZE_UNITS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MAX_CREATOR_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MAX_IPO_FEE_DURATION",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MAX_IPO_PRIZE_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MAX_IPO_PROTOCOL_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MAX_PROTOCOL_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MAX_SELL_PRIZE_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MAX_TOTAL_COMMISSION_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MAX_TRANSFER_GAS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MIN_IPO_FEE_DURATION",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "MIN_TRANSFER_GAS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "ONE_FULL_SHARE_IN_UNITS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "PROTOCOL_FEE_GROSS_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "REFERRAL_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "ROLE_CARD_MANAGER",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "",
        "type": "bytes32"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "ROLE_CARD_SENDER",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "",
        "type": "bytes32"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "ROLE_ETH_PRIZE_MANAGER",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "",
        "type": "bytes32"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "ROLE_REFERRER_MANAGER",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "",
        "type": "bytes32"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "ROLE_STORAGE_CLEANER",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "",
        "type": "bytes32"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "ROLE_TRADING_TOGGLER",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "",
        "type": "bytes32"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "SELL_PRIZE_FEE_BPS",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "SHARES_DECIMALS",
    "outputs": [
      {
        "internalType": "uint8",
        "name": "",
        "type": "uint8"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "acceptOwnership",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "name": "accruedCreatorFeesWei",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "string",
        "name": "name",
        "type": "string"
      },
      {
        "internalType": "uint256",
        "name": "numLots",
        "type": "uint256"
      }
    ],
    "name": "addPlayerAndSnipeByLots",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "string",
        "name": "name",
        "type": "string"
      },
      {
        "internalType": "uint256",
        "name": "snipeAmountUnits",
        "type": "uint256"
      }
    ],
    "name": "addPlayerAndSnipeByUnits",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "winner",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      },
      {
        "internalType": "string",
        "name": "description",
        "type": "string"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "awardEthPrize",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "winner",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      },
      {
        "internalType": "string",
        "name": "description",
        "type": "string"
      }
    ],
    "name": "awardEthPrize",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address[]",
        "name": "winners",
        "type": "address[]"
      },
      {
        "internalType": "uint256[]",
        "name": "amounts",
        "type": "uint256[]"
      },
      {
        "internalType": "string[]",
        "name": "descriptions",
        "type": "string[]"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "awardEthPrizeBatch",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address[]",
        "name": "winners",
        "type": "address[]"
      },
      {
        "internalType": "uint256[]",
        "name": "amounts",
        "type": "uint256[]"
      },
      {
        "internalType": "string[]",
        "name": "descriptions",
        "type": "string[]"
      }
    ],
    "name": "awardEthPrizeBatch",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256[]",
        "name": "playerIds",
        "type": "uint256[]"
      },
      {
        "internalType": "address[]",
        "name": "winners",
        "type": "address[]"
      },
      {
        "internalType": "uint256[]",
        "name": "amountUnits",
        "type": "uint256[]"
      },
      {
        "internalType": "string[]",
        "name": "descriptions",
        "type": "string[]"
      }
    ],
    "name": "awardSharePrizeBatchMultiPlayerMultiUser",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256[]",
        "name": "playerIds",
        "type": "uint256[]"
      },
      {
        "internalType": "address[]",
        "name": "winners",
        "type": "address[]"
      },
      {
        "internalType": "uint256[]",
        "name": "numLots",
        "type": "uint256[]"
      },
      {
        "internalType": "string[]",
        "name": "descriptions",
        "type": "string[]"
      }
    ],
    "name": "awardSharePrizeBatchMultiPlayerMultiUserByLots",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "winner",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "numLots",
        "type": "uint256"
      },
      {
        "internalType": "string",
        "name": "description",
        "type": "string"
      }
    ],
    "name": "awardSharePrizeByLots",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "components": [
          {
            "internalType": "uint256",
            "name": "playerId",
            "type": "uint256"
          },
          {
            "internalType": "address",
            "name": "user",
            "type": "address"
          }
        ],
        "internalType": "struct HoodFrens.CleanupTarget[]",
        "name": "targets",
        "type": "tuple[]"
      }
    ],
    "name": "batchCleanupIpoTracking",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "processed",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "skippedInvalidPlayer",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "skippedActiveIpo",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "skippedAlreadyClean",
        "type": "uint256"
      }
    ],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "components": [
          {
            "internalType": "uint256",
            "name": "playerId",
            "type": "uint256"
          },
          {
            "internalType": "address",
            "name": "user",
            "type": "address"
          }
        ],
        "internalType": "struct HoodFrens.CleanupTarget[]",
        "name": "targets",
        "type": "tuple[]"
      }
    ],
    "name": "batchCleanupZeroBalances",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "processed",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "skippedInvalidPlayer",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "skippedNonZeroBalance",
        "type": "uint256"
      }
    ],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "numLots",
        "type": "uint256"
      }
    ],
    "name": "buySharesByLots",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "amountUnits",
        "type": "uint256"
      }
    ],
    "name": "buySharesByUnits",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "numLots",
        "type": "uint256"
      }
    ],
    "name": "calculateGrossSellPayoutByLots",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "a",
        "type": "uint256"
      }
    ],
    "name": "calculateGrossSellPayoutByUnits",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "claimCreatorFees",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "name": "creatorWallet",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "name": "customGasLimit",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "defaultTransferGasLimit",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "offset",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "limit",
        "type": "uint256"
      }
    ],
    "name": "getAllPlayers",
    "outputs": [
      {
        "internalType": "uint256[]",
        "name": "ids",
        "type": "uint256[]"
      },
      {
        "internalType": "string[]",
        "name": "names",
        "type": "string[]"
      },
      {
        "internalType": "bool[]",
        "name": "tradingEnableds",
        "type": "bool[]"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "numLots",
        "type": "uint256"
      }
    ],
    "name": "getBuyPriceByLots",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "amountUnits",
        "type": "uint256"
      }
    ],
    "name": "getBuyPriceByUnits",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "a",
        "type": "uint256"
      }
    ],
    "name": "getBuyPriceRaw",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "recipient",
        "type": "address"
      }
    ],
    "name": "getEffectiveGasLimit",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "gasLimit",
        "type": "uint256"
      },
      {
        "internalType": "bool",
        "name": "isCustom",
        "type": "bool"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "getFractionalRemainder",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "remainder",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "estimatedGrossPayout",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "estimatedNetPayout",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "getIpoPrizeFeeEndTime",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "offset",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "limit",
        "type": "uint256"
      }
    ],
    "name": "getPortfolioFractionalRemainders",
    "outputs": [
      {
        "internalType": "uint256[]",
        "name": "playerIds",
        "type": "uint256[]"
      },
      {
        "internalType": "uint256[]",
        "name": "remainders",
        "type": "uint256[]"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "offset",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "limit",
        "type": "uint256"
      }
    ],
    "name": "getPortfolioHoldingsInLots",
    "outputs": [
      {
        "internalType": "uint256[]",
        "name": "playerIds",
        "type": "uint256[]"
      },
      {
        "internalType": "uint256[]",
        "name": "quantities",
        "type": "uint256[]"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "offset",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "limit",
        "type": "uint256"
      }
    ],
    "name": "getPortfolioHoldingsInUnits",
    "outputs": [
      {
        "internalType": "uint256[]",
        "name": "playerIds",
        "type": "uint256[]"
      },
      {
        "internalType": "uint256[]",
        "name": "quantities",
        "type": "uint256[]"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "role",
        "type": "bytes32"
      }
    ],
    "name": "getRoleAdmin",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "",
        "type": "bytes32"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "getUserPlayerHoldingInFullShares",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "getUserPlayerHoldingInLots",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "getUserPlayerHoldingInUnits",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "role",
        "type": "bytes32"
      },
      {
        "internalType": "address",
        "name": "account",
        "type": "address"
      }
    ],
    "name": "grantRole",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "role",
        "type": "bytes32"
      },
      {
        "internalType": "address",
        "name": "account",
        "type": "address"
      }
    ],
    "name": "hasRole",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "isIpoPrizeFeeActive",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "nextPlayerId",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "owner",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "string",
        "name": "reason",
        "type": "string"
      }
    ],
    "name": "pause",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "pauseReason",
    "outputs": [
      {
        "internalType": "string",
        "name": "",
        "type": "string"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "paused",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "pendingOwner",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "name": "players",
    "outputs": [
      {
        "internalType": "string",
        "name": "name",
        "type": "string"
      },
      {
        "internalType": "bool",
        "name": "tradingEnabled",
        "type": "bool"
      },
      {
        "internalType": "uint256",
        "name": "ipoWindowStartTimestamp",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "ipoWindowEndTimestamp",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "prizeWallet",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "protocolWallet",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "winner",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      },
      {
        "internalType": "string",
        "name": "description",
        "type": "string"
      }
    ],
    "name": "recordEthPrizeAwarded",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "winner",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      },
      {
        "internalType": "string",
        "name": "description",
        "type": "string"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "recordEthPrizeAwarded",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "name": "referrerOf",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "renounceOwnership",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "role",
        "type": "bytes32"
      },
      {
        "internalType": "address",
        "name": "callerConfirmation",
        "type": "address"
      }
    ],
    "name": "renounceRole",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "role",
        "type": "bytes32"
      },
      {
        "internalType": "address",
        "name": "account",
        "type": "address"
      }
    ],
    "name": "revokeRole",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "minNetPayout",
        "type": "uint256"
      }
    ],
    "name": "sellFractionalRemainder",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "numLots",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "minNetPayout",
        "type": "uint256"
      }
    ],
    "name": "sellSharesByLots",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "amountUnits",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "minNetPayout",
        "type": "uint256"
      }
    ],
    "name": "sellSharesByUnits",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "_creatorFeeBps",
        "type": "uint256"
      }
    ],
    "name": "setCreatorFee",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "address",
        "name": "wallet",
        "type": "address"
      }
    ],
    "name": "setCreatorWallet",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "recipient",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "gasLimit",
        "type": "uint256"
      }
    ],
    "name": "setCustomGasLimit",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address[]",
        "name": "recipients",
        "type": "address[]"
      },
      {
        "internalType": "uint256[]",
        "name": "gasLimits",
        "type": "uint256[]"
      }
    ],
    "name": "setCustomGasLimitBatch",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "newLimit",
        "type": "uint256"
      }
    ],
    "name": "setDefaultTransferGasLimit",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "_sellPrizeFeeBps",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_protocolFeeGrossBps",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_ipoPrizeFeeBps",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_ipoProtocolFeeBps",
        "type": "uint256"
      }
    ],
    "name": "setFees",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "_ipoFeeDuration",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_ipoLotsPerCallMin",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_ipoLotsPerCallMax",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_ipoMaxLotsPerWallet",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_ipoTradesPerSecond",
        "type": "uint256"
      }
    ],
    "name": "setIpoParameters",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address[]",
        "name": "users",
        "type": "address[]"
      },
      {
        "internalType": "address[]",
        "name": "referrers",
        "type": "address[]"
      }
    ],
    "name": "setMultipleUserReferrers",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "_prize",
        "type": "address"
      }
    ],
    "name": "setPrizeWallet",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "_protocol",
        "type": "address"
      }
    ],
    "name": "setProtocolWallet",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "_lotSizeUnits",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_lotsPerCallMin",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "_lotsPerCallMax",
        "type": "uint256"
      }
    ],
    "name": "setTradingParameters",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "bool",
        "name": "enabled",
        "type": "bool"
      }
    ],
    "name": "setTradingStatus",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256[]",
        "name": "playerIds",
        "type": "uint256[]"
      },
      {
        "internalType": "bool",
        "name": "enabled",
        "type": "bool"
      }
    ],
    "name": "setTradingStatusBulk",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "updatedCount",
        "type": "uint256"
      }
    ],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "user",
        "type": "address"
      },
      {
        "internalType": "address",
        "name": "referrer",
        "type": "address"
      }
    ],
    "name": "setUserReferrer",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      },
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "name": "sharesBalance",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "name": "sharesSupply",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "bytes4",
        "name": "interfaceId",
        "type": "bytes4"
      }
    ],
    "name": "supportsInterface",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "totalAccruedCreatorFeesWei",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "totalEthPrizesAwarded",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "to",
        "type": "address"
      }
    ],
    "name": "transferAllSharesInWallet",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "to",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      }
    ],
    "name": "transferAllSharesOfIndividualPlayer",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "newOwner",
        "type": "address"
      }
    ],
    "name": "transferOwnership",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "to",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "numLots",
        "type": "uint256"
      }
    ],
    "name": "transferSharesByLots",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "to",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "playerId",
        "type": "uint256"
      },
      {
        "internalType": "uint256",
        "name": "amountUnits",
        "type": "uint256"
      }
    ],
    "name": "transferSharesByUnits",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "unpause",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "oldReferrer",
        "type": "address"
      },
      {
        "internalType": "address",
        "name": "newReferrer",
        "type": "address"
      },
      {
        "internalType": "address[]",
        "name": "referredUsers",
        "type": "address[]"
      }
    ],
    "name": "updateReferrerForUsers",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  }
]

Source code


// File: @openzeppelin/contracts/utils/Context.sol


// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// File: @openzeppelin/contracts/access/Ownable.sol


// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;


/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/access/Ownable2Step.sol


// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;


/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

// File: @openzeppelin/contracts/utils/StorageSlot.sol


// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol


// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;


/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

// File: @openzeppelin/contracts/utils/Pausable.sol


// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;


/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// File: @openzeppelin/contracts/access/IAccessControl.sol


// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol


// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: @openzeppelin/contracts/utils/introspection/ERC165.sol


// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;


/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// File: @openzeppelin/contracts/access/AccessControl.sol


// OpenZeppelin Contracts (last updated v5.6.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;




/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc ERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

// File: @openzeppelin/contracts/utils/Panic.sol


// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

// File: @openzeppelin/contracts/utils/math/SafeCast.sol


// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev A uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

// File: @openzeppelin/contracts/utils/math/Math.sol


// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;



/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory buffer) private pure returns (bool) {
        uint256 chunk;
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            // See _unsafeReadBytesOffset from utils/Bytes.sol
            assembly ("memory-safe") {
                chunk := mload(add(add(buffer, 0x20), i))
            }
            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

// File: Hoodfrensv2.sol


pragma solidity ^0.8.20;










/// @title HoodFrens
/// @author TopStrike Team
/// @notice This contract enables trading of player shares using a quadratic bonding curve with IPO mechanics
/// @dev Inherits from Ownable2Step, ReentrancyGuard, Pausable, and AccessControl for security and governance
contract HoodFrens is Ownable2Step, ReentrancyGuard, Pausable, AccessControl {
    ////////////////////////////////////////////////////////////////////
    // ROLES
    ////////////////////////////////////////////////////////////////////
    /// @notice Role for enabling/disabling trading for players
    bytes32 public constant ROLE_TRADING_TOGGLER =
        keccak256("ROLE_TRADING_TOGGLER");
    /// @notice Role for managing cards: adding players, sniping shares, and binding creator wallets
    bytes32 public constant ROLE_CARD_MANAGER =
        keccak256("ROLE_CARD_MANAGER");
    /// @notice Role for sending card (share) prizes to users
    bytes32 public constant ROLE_CARD_SENDER =
        keccak256("ROLE_CARD_SENDER");
    /// @notice Role for distributing ETH prizes to users and managing ETH transfer gas limits
    bytes32 public constant ROLE_ETH_PRIZE_MANAGER =
        keccak256("ROLE_ETH_PRIZE_MANAGER");
    /// @notice Role for managing user referrers
    bytes32 public constant ROLE_REFERRER_MANAGER =
        keccak256("ROLE_REFERRER_MANAGER");
    /// @notice Role for cleaning up stale storage slots
    bytes32 public constant ROLE_STORAGE_CLEANER =
        keccak256("ROLE_STORAGE_CLEANER");

    ////////////////////////////////////////////////////////////////////
    // Wallets for prize and protocol fees
    ////////////////////////////////////////////////////////////////////
    /// @notice Address that receives prize pool fees
    address public prizeWallet;
    /// @notice Address that receives protocol fees
    address public protocolWallet;

    ////////////////////////////////////////////////////////////////////
    // Constants and fee configurations
    ////////////////////////////////////////////////////////////////////

    /// @notice Basis points denominator
    uint256 public constant BPS = 10000;

    /// @notice Decimal precision for shares (18 decimals, similar to ERC20)
    uint8 public constant SHARES_DECIMALS = 18;
    /// @notice One full share in smallest units (1e18)
    uint256 public constant ONE_FULL_SHARE_IN_UNITS = 10 ** SHARES_DECIMALS; // 1 full share

    /// @notice Denominator for the quadratic bonding curve formula
    uint256 public constant BONDING_CURVE_DENOMINATOR = 32000;

    // Precalculated helper constants for overflow safety
    uint256 private constant ONE_FULL_SHARE_IN_UNITS2 =
        ONE_FULL_SHARE_IN_UNITS * ONE_FULL_SHARE_IN_UNITS;
    uint256 private constant ONE_FULL_SHARE_IN_UNITS3 =
        ONE_FULL_SHARE_IN_UNITS2 * ONE_FULL_SHARE_IN_UNITS;

    /// @notice Total commission on sells in basis points (auto-calculated from prize + protocol + creator fees)
    uint256 public COMMISSION_BPS = 940; // 9.4% total commission
    /// @notice Prize pool fee on sells in basis points (4.5% of gross sale)
    uint256 public SELL_PRIZE_FEE_BPS = 450; // 4.5% of gross sale (to prize pool)
    /// @notice Protocol fee on sells in basis points before referral deduction (1.5% of gross sale)
    uint256 public PROTOCOL_FEE_GROSS_BPS = 150; // 1.5% of gross sale (to protocol, reduced by 0.5% for referrer)
    /// @notice Referral fee in basis points (0.5% deducted from protocol fee if referrer exists)
    uint256 public constant REFERRAL_FEE_BPS = 50; // 0.5% referrer fee
    /// @notice Creator fee on sells in basis points (3.4% of gross sale, ringfenced per card)
    uint256 public CREATOR_FEE_BPS = 340; // 3.4% of gross sale (to the card's creator)
    /// @notice Maximum allowed creator fee (10%)
    uint256 public constant MAX_CREATOR_FEE_BPS = 1000;

    /// @notice Protocol fee charged during IPO buys in basis points (1.9%)
    uint256 public IPO_PROTOCOL_FEE_BPS = 190; // 1.9% to protocol
    /// @notice Prize fee charged during IPO buys in basis points (2.0%)
    uint256 public IPO_PRIZE_FEE_BPS = 200; // 2.0% to prize
    /// @notice Duration of IPO window where special fees apply
    uint256 public IPO_FEE_DURATION = 24 hours;

    /// @notice Maximum allowed prize fee on sells (10%)
    uint256 public constant MAX_SELL_PRIZE_FEE_BPS = 1000; // Max 10% for prize on sell
    /// @notice Maximum allowed protocol fee (5%)
    uint256 public constant MAX_PROTOCOL_FEE_BPS = 500; // Max 5% for protocol
    /// @notice Maximum allowed total commission on sells (15%)
    uint256 public constant MAX_TOTAL_COMMISSION_BPS = 1500; // Max 15% total commission
    /// @notice Maximum allowed IPO prize fee (10%)
    uint256 public constant MAX_IPO_PRIZE_FEE_BPS = 1000; // Max 10%
    /// @notice Maximum allowed IPO protocol fee (10%)
    uint256 public constant MAX_IPO_PROTOCOL_FEE_BPS = 1000; // Max 10%
    /// @notice Maximum allowed IPO fee duration (7 days)
    uint256 public constant MAX_IPO_FEE_DURATION = 7 days; // Max 7 days
    /// @notice Minimum allowed IPO fee duration (0 = disabled)
    uint256 public constant MIN_IPO_FEE_DURATION = 0; // Min 0 (disabled)

    /// @notice Size of one trading lot in units (0.1 shares)
    uint256 public LOT_SIZE_UNITS = ONE_FULL_SHARE_IN_UNITS / 10; // 0.1 shares, in 18-decimal units

    /// @notice Minimum lots per regular trade call
    uint256 public LOTS_PER_CALL_MIN = 1; // Min 1 lot per call
    /// @notice Maximum lots per regular trade call
    uint256 public LOTS_PER_CALL_MAX = 1; // Max 1 lot per call

    /// @notice Minimum lots per IPO trade call
    uint256 public IPO_LOTS_PER_CALL_MIN = 1; // Min 1 lot per IPO call
    /// @notice Maximum lots per IPO trade call
    uint256 public IPO_LOTS_PER_CALL_MAX = 1; // Max 1 lot per IPO call

    /// @notice Maximum total lots per wallet during IPO
    uint256 public IPO_MAX_LOTS_PER_WALLET = 5; // Max 5 lots per wallet during IPO
    /// @notice IPO rate limit in trades per second (linear accumulation)
    uint256 public IPO_TRADES_PER_SECOND = 3; // Linear rate: 3 trades/sec

    ////////////////////////////////////////////////////////////////////
    // Player structure
    ////////////////////////////////////////////////////////////////////
    /// @notice Player data structure
    /// @param name Player's name
    /// @param tradingEnabled Whether trading is enabled for this player
    /// @param ipoWindowStartTimestamp Timestamp when IPO window started
    /// @param ipoWindowEndTimestamp Timestamp when IPO window ended (0 if ongoing)
    struct Player {
        string name;
        bool tradingEnabled;
        uint256 ipoWindowStartTimestamp;
        uint256 ipoWindowEndTimestamp;
    }

    ////////////////////////////////////////////////////////////////////
    // Storage Cleanup - Struct
    ////////////////////////////////////////////////////////////////////
    /// @notice Struct for specifying cleanup targets
    /// @param playerId The player ID
    /// @param user The user address
    struct CleanupTarget {
        uint256 playerId;
        address user;
    }

    ////////////////////////////////////////////////////////////////////
    // Constants for change reasons
    ////////////////////////////////////////////////////////////////////
    
    /// @notice Reasons for balance and supply changes
    /// @dev Used to differentiate the cause of UserSharesChanged and PlayerSharesSupplyChanged events for off-chain indexing
    string constant REASON_BUY = "Buy";
    string constant REASON_SELL = "Sell";
    string constant REASON_PRIZE_AWARD = "PrizeAward";
    string constant REASON_TRANSFER = "Transfer";
    string constant REASON_PRIZE_WALLET_SNIPE = "PrizeWalletNewPlayerSnipe";

    ////////////////////////////////////////////////////////////////////
    // Player and shares management state
    ////////////////////////////////////////////////////////////////////
    /// @notice Mapping of player ID to Player data
    mapping(uint256 => Player) public players;
    /// @notice Counter for next player ID to assign
    uint256 public nextPlayerId;
    /// @notice Mapping of player ID and user address to share balance in units
    mapping(uint256 => mapping(address => uint256)) public sharesBalance; // In 18-decimal units
    /// @notice Mapping of player ID to total share supply in units
    mapping(uint256 => uint256) public sharesSupply; // In 18-decimal units
    /// @notice Mapping of user address to their referrer address
    mapping(address => address) public referrerOf;
    /// @notice Registered payout wallet per creator card (playerId => wallet)
    mapping(uint256 => address) public creatorWallet;
    /// @notice Creator fees accrued on-chain while no wallet is registered (playerId => wei)
    mapping(uint256 => uint256) public accruedCreatorFeesWei;
    /// @notice Total unclaimed creator fees ringfenced in the contract
    uint256 public totalAccruedCreatorFeesWei;
    /// @notice Mapping of player ID and user address to total IPO lots purchased
    mapping(uint256 => mapping(address => uint256)) private _ipoLotsUsed; // Total IPO lots used per user
    /// @notice Mapping of player ID and user address to total IPO trades consumed (for rate limiting)
    mapping(uint256 => mapping(address => uint256)) private _ipoTradesUsed; // Total IPO trades consumed
    ////////////////////////////////////////////////////////////////////
    // Pause functionality
    ////////////////////////////////////////////////////////////////////
    /// @notice Reason string for why the contract is paused
    string public pauseReason;
    ////////////////////////////////////////////////////////////////////
    // New state variables
    ////////////////////////////////////////////////////////////////////
    /// @notice Total ETH prizes awarded to users
    uint256 public totalEthPrizesAwarded;

    ////////////////////////////////////////////////////////////////////
    // ETH Transfer Gas Limit Configuration
    ////////////////////////////////////////////////////////////////////
    /// @notice Default gas limit for ETH transfers
    uint256 public defaultTransferGasLimit;
    /// @notice Custom gas limits for specific recipients
    mapping(address => uint256) public customGasLimit;
    /// @notice Minimum allowed gas limit for transfers
    uint256 public constant MIN_TRANSFER_GAS = 2300;
    /// @notice Maximum allowed gas limit for transfers
    uint256 public constant MAX_TRANSFER_GAS = 100000;

    ////////////////////////////////////////////////////////////////////
    // Events
    ////////////////////////////////////////////////////////////////////
    /// @notice Emitted when a new player is added to the contract
    /// @param playerId The unique ID of the player
    /// @param name The name of the player
    /// @param snipeAmountInUnits The initial amount of shares sniped in units
    event PlayerAdded(
        uint256 indexed playerId,
        string name,
        uint256 snipeAmountInUnits
    );
    /// @notice Emitted when a player's IPO window status changes
    /// @param playerId The unique ID of the player
    /// @param name The name of the player
    /// @param startTimestamp The timestamp when IPO started
    /// @param endTimestamp The timestamp when IPO ended (0 if ongoing)
    /// @param currentSupply The current total supply for the player
    event PlayerIPO(
        uint256 indexed playerId,
        string name,
        uint256 startTimestamp,
        uint256 endTimestamp,
        uint256 currentSupply
    );
    /// @notice Emitted when a trade (buy or sell) occurs
    /// @dev priceInWei is wallet-facing value (NOT spot price):
    ///      - Buy: total ETH paid by trader (includes IPO fees if active)
    ///      - Sell: net ETH received by trader after sell fees
    ///      feeInWei is total fees charged for the trade:
    ///      - Buy: IPO fees only (prize + protocol), otherwise 0
    ///      - Sell: prize + protocol + creator + optional referrer
    ///      For sells, gross pre-fee value can be derived as: gross = priceInWei + feeInWei.
    /// @param trader The address executing the trade
    /// @param playerId The player whose shares are being traded
    /// @param isBuy True if buying, false if selling
    /// @param amountInUnits The amount of shares traded in units
    /// @param priceInWei Wallet-facing ETH value:
    ///        - Buy: totalCost (base + IPO fees)
    ///        - Sell: netPayout (after fees)
    /// @param feeInWei Total fees charged in wei for this trade
    /// @param newSupplyInUnits The new total supply after the trade
    /// @param isIPOWindow True if trade occurred during IPO window
    event Trade(
        address indexed trader,
        uint256 indexed playerId,
        bool isBuy,
        uint256 amountInUnits,
        uint256 priceInWei,
        uint256 feeInWei,
        uint256 newSupplyInUnits,
        bool isIPOWindow
    );
    /// @notice Emitted when trading is enabled or disabled for a player
    /// @param playerId The player whose trading status changed
    /// @param enabled True if trading is enabled, false if disabled
    event TradingStatusUpdated(uint256 indexed playerId, bool enabled);
    /// @notice Emitted when shares are transferred between users
    /// @param from The address transferring shares
    /// @param to The address receiving shares
    /// @param playerId The player whose shares are being transferred
    /// @param amountInUnits The amount of shares transferred in units
    event SharesTransferred(
        address indexed from,
        address indexed to,
        uint256 indexed playerId,
        uint256 amountInUnits
    );
    /// @notice Emitted when ETH is deposited to the prize pool
    /// @param amountInWei The amount of ETH deposited in wei
    event EthPrizeDeposited(uint256 amountInWei);
    /// @notice Emitted when an ETH prize is awarded to a winner
    /// @param winner The address receiving the prize
    /// @param playerId The player associated with the prize
    /// @param amountInWei The amount of ETH awarded in wei
    /// @param description Description of the prize
    event EthPrizeAwarded(
        address indexed winner,
        uint256 indexed playerId,
        uint256 amountInWei,
        string description
    );
    /// @notice Emitted when share prizes are deposited for a player
    /// @param playerId The player whose shares are being deposited
    /// @param amountInUnits The amount of shares deposited in units
    event SharePrizeDeposited(uint256 indexed playerId, uint256 amountInUnits);
    /// @notice Emitted when share prizes are awarded to a winner
    /// @param winner The address receiving the shares
    /// @param playerId The player whose shares are being awarded
    /// @param amountInUnits The amount of shares awarded in units
    /// @param description Description of the prize
    event SharePrizeAwarded(
        address indexed winner,
        uint256 indexed playerId,
        uint256 amountInUnits,
        string description
    );
    /// @notice Emitted when a user's share balance changes for any reason
    /// @dev The 'reason' field enables off-chain tracking of share acquisition source:
    /// - "Buy": Shares purchased via buySharesByUnits/buySharesByLots
    /// - "Transfer": Shares received via transferSharesByUnits/transferSharesByLots
    /// - "PrizeAward": Shares received as prizes via awardSharePrize functions
    /// - "Sell": Shares sold (negative amountChangeInUnits)
    /// - "PrizeWalletNewPlayerSnipe": Initial prize pool snipe when player is added
    /// 
    /// This tracking allows competitions to differentiate between purchased shares
    /// vs transferred/gifted shares (which could be used to game eligibility requirements).
    /// 
    /// @param user The address whose balance changed
    /// @param playerId The player whose shares changed
    /// @param amountChangeInUnits The change in shares (positive for increase, negative for decrease)
    /// @param newUserBalanceInUnits The user's new total balance for this player
    /// @param totalCostInWei The total cost/proceeds in wei (for buys/sells)
    /// @param totalFeesInWei The total fees paid in wei (for buys/sells)
    /// @param netAmountInWei The net amount in wei after fees
    /// @param reason The reason for the balance change (for off-chain indexing)
    event UserSharesChanged(
        address indexed user,
        uint256 indexed playerId,
        int256 amountChangeInUnits,
        uint256 newUserBalanceInUnits,
        uint256 totalCostInWei,
        uint256 totalFeesInWei,
        uint256 netAmountInWei,
        string reason
    );
    /// @notice Emitted when a player's total share supply changes
    /// @param playerId The player whose supply changed
    /// @param supplyChangeInUnits The change in total supply (positive for increase, negative for decrease)
    /// @param newTotalSupplyInUnits The new total supply for this player
    /// @param currentPriceInWei The current price per share after the change
    /// @param marketCapInWei The total market cap after the change
    /// @param reason The reason for the supply change (for off-chain indexing)
    event PlayerSharesSupplyChanged(
        uint256 indexed playerId,
        int256 supplyChangeInUnits,
        uint256 newTotalSupplyInUnits,
        uint256 currentPriceInWei,
        uint256 marketCapInWei,
        string reason
    );
    /// @notice Emitted when a referrer is set for a user
    /// @param user The user whose referrer was set
    /// @param referrer The referrer address
    event ReferrerSet(address indexed user, address indexed referrer);
    /// @notice Emitted when all referrals are migrated from one address to another
    /// @param oldReferrer The old referrer address
    /// @param newReferrer The new referrer address
    /// @param referralCount The number of referrals migrated
    event ReferrerMigrated(address indexed oldReferrer, address indexed newReferrer, uint256 referralCount);
    /// @notice Emitted when a referral fee is paid
    /// @param referrer The address receiving the fee
    /// @param user The user whose trade generated the fee
    /// @param amountInWei The amount of the fee in wei
    event ReferralFeePaid(
        address indexed referrer,
        address indexed user,
        uint256 amountInWei
    );
    /// @notice Emitted when a creator's payout wallet is set or changed
    event CreatorWalletSet(uint256 indexed playerId, address indexed wallet);
    /// @notice Emitted when a creator fee is paid directly to a registered wallet
    event CreatorFeePaid(uint256 indexed playerId, address indexed wallet, uint256 amountInWei);
    /// @notice Emitted when a creator fee is accrued on-chain (no wallet registered yet)
    event CreatorFeeAccrued(uint256 indexed playerId, uint256 amountInWei);
    /// @notice Emitted when accrued creator fees are claimed
    event CreatorFeesClaimed(uint256 indexed playerId, address indexed wallet, uint256 amountInWei);
    /// @notice Emitted when the creator fee bps is updated
    event CreatorFeeUpdated(uint256 newCreatorFeeBps);
    /// @notice Emitted when prize or protocol wallet addresses are updated
    /// @param newPrizeWallet The new prize wallet address
    /// @param newProtocolWallet The new protocol wallet address
    event WalletsUpdated(address newPrizeWallet, address newProtocolWallet);
    /// @notice Emitted when fee parameters are updated
    /// @param newSellPrizeFeeBps The new sell prize fee in basis points
    /// @param newProtocolFeeBps The new protocol fee in basis points
    /// @param newIpoPrizeFeeBps The new IPO prize fee in basis points
    /// @param newIpoProtocolFeeBps The new IPO protocol fee in basis points
    /// @param currentCreatorFeeBps The current creator fee in basis points (changed via
    ///        setCreatorFee / CreatorFeeUpdated; included here so indexers see the full sell split)
    event FeesUpdated(
        uint256 newSellPrizeFeeBps,
        uint256 newProtocolFeeBps,
        uint256 newIpoPrizeFeeBps,
        uint256 newIpoProtocolFeeBps,
        uint256 currentCreatorFeeBps
    );
    /// @notice Emitted when trading parameters are updated
    /// @param newLotSizeUnits The new lot size in units
    /// @param newLotsPerCallMin The new minimum lots per call
    /// @param newLotsPerCallMax The new maximum lots per call
    event TradingParametersUpdated(
        uint256 newLotSizeUnits,
        uint256 newLotsPerCallMin,
        uint256 newLotsPerCallMax
    );
    /// @notice Emitted when IPO parameters are updated
    /// @param newIpoFeeDuration The new IPO fee duration
    /// @param newIpoLotsPerCallMin The new minimum IPO lots per call
    /// @param newIpoLotsPerCallMax The new maximum IPO lots per call
    /// @param newIpoMaxLotsPerWallet The new maximum IPO lots per wallet
    /// @param newIpoTradesPerSecond The new IPO trades per second rate limit
    event IpoParametersUpdated(
        uint256 newIpoFeeDuration,
        uint256 newIpoLotsPerCallMin,
        uint256 newIpoLotsPerCallMax,
        uint256 newIpoMaxLotsPerWallet,
        uint256 newIpoTradesPerSecond
    );
    /// @notice Emitted when the contract is paused
    /// @param reason The reason for pausing
    event ContractPaused(string reason);
    /// @notice Emitted when the contract is unpaused
    event ContractUnpaused();
    /// @notice Emitted when IPO buy fees are applied to a transaction
    /// @param user The user making the purchase
    /// @param playerId The player being purchased
    /// @param baseCostInWei The base cost before fees
    /// @param prizeFeeInWei The prize fee amount
    /// @param protocolFeeInWei The protocol fee amount
    /// @param totalCostInWei The total cost including fees
    event IpoBuyFeesApplied(
        address indexed user,
        uint256 indexed playerId,
        uint256 baseCostInWei,
        uint256 prizeFeeInWei,
        uint256 protocolFeeInWei,
        uint256 totalCostInWei
    );
    /// @notice Emitted when the default transfer gas limit is updated
    /// @param oldLimit The previous gas limit
    /// @param newLimit The new gas limit
    event DefaultTransferGasLimitUpdated(uint256 oldLimit, uint256 newLimit);
    /// @notice Emitted when a custom gas limit is set for a recipient
    /// @param recipient The address with the custom limit
    /// @param gasLimit The new gas limit
    event CustomGasLimitSet(address indexed recipient, uint256 gasLimit);
    /// @notice Emitted when a custom gas limit is removed for a recipient
    /// @param recipient The address whose custom limit was removed
    event CustomGasLimitRemoved(address indexed recipient);
    /// @notice Emitted when referral fee transfer fails and is redirected to protocol wallet
    /// @param intendedRecipient The referrer who should have received the fee
    /// @param seller The user whose sale generated the referral fee
    /// @param amount The amount redirected to protocol wallet
    event ReferralFeeRedirectedToProtocol(
        address indexed intendedRecipient,
        address indexed seller,
        uint256 amount
    );
    /// @notice Emitted when prize transfer fails and is refunded to sender
    /// @param intendedRecipient The winner who should have received the prize
    /// @param amount The amount refunded to the prize manager
    /// @param description The prize description
    event PrizeTransferFailed(
        address indexed intendedRecipient,
        uint256 amount,
        string description
    );

    ////////////////////////////////////////////////////////////////////
    // Storage Cleanup - Events
    ////////////////////////////////////////////////////////////////////
    /// @notice Emitted when a zero-balance storage slot is cleaned up
    /// @dev Off-chain indexers should deduplicate by [playerId, user] pair
    /// @param playerId The player whose balance slot was cleaned
    /// @param user The user whose zero balance was cleaned
    event ZeroBalanceCleaned(uint256 indexed playerId, address indexed user);

    /// @notice Emitted when IPO tracking data is cleaned up
    /// @param playerId The player whose IPO data was cleaned
    /// @param user The user whose IPO data was cleaned
    /// @param lotsUsed The lots value that was cleared (0 if already cleaned)
    /// @param tradesUsed The trades value that was cleared (0 if already cleaned)
    event IpoTrackingCleaned(
        uint256 indexed playerId,
        address indexed user,
        uint256 lotsUsed,
        uint256 tradesUsed
    );

    /// @notice Emitted after a batch cleanup operation completes
    /// @param cleanupType The type of cleanup performed ("ZeroBalances" or "IpoTracking")
    /// @param processed The number of targets processed
    event BatchCleanupCompleted(string cleanupType, uint256 processed);

    ////////////////////////////////////////////////////////////////////
    // Modifiers
    ////////////////////////////////////////////////////////////////////
    modifier playerExists(uint256 playerId) {
        require(playerId < nextPlayerId, "Player does not exist");
        _;
    }
    modifier onlyCardManager() {
        require(
            hasRole(ROLE_CARD_MANAGER, msg.sender),
            "Caller is not card manager"
        );
        _;
    }
    modifier onlyCardSender() {
        require(
            hasRole(ROLE_CARD_SENDER, msg.sender),
            "Caller is not card sender"
        );
        _;
    }
    modifier onlyEthPrizeManager() {
        require(
            hasRole(ROLE_ETH_PRIZE_MANAGER, msg.sender),
            "Caller is not eth prize manager"
        );
        _;
    }
    modifier onlyReferrerManager() {
        require(
            hasRole(ROLE_REFERRER_MANAGER, msg.sender),
            "Caller is not referrer manager"
        );
        _;
    }
    modifier onlyTradingToggler() {
        require(
            hasRole(ROLE_TRADING_TOGGLER, msg.sender),
            "Caller is not trading toggler"
        );
        _;
    }
    modifier onlyStorageCleaner() {
        require(
            hasRole(ROLE_STORAGE_CLEANER, msg.sender),
            "Caller is not storage cleaner"
        );
        _;
    }

    ////////////////////////////////////////////////////////////////////
    // Constructor
    ////////////////////////////////////////////////////////////////////
    constructor(
        address _prizeWallet,
        address _protocolWallet
    ) Ownable(msg.sender) {
        require(
            _prizeWallet != address(0),
            "Prize wallet cannot be zero address"
        );
        require(
            _protocolWallet != address(0),
            "Protocol wallet cannot be zero address"
        );
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(ROLE_TRADING_TOGGLER, msg.sender);
        _grantRole(ROLE_CARD_MANAGER, msg.sender);
        _grantRole(ROLE_CARD_SENDER, msg.sender);
        _grantRole(ROLE_ETH_PRIZE_MANAGER, msg.sender);
        _grantRole(ROLE_REFERRER_MANAGER, msg.sender);
        _grantRole(ROLE_STORAGE_CLEANER, msg.sender);
        prizeWallet = _prizeWallet;
        protocolWallet = _protocolWallet;
        defaultTransferGasLimit = MIN_TRANSFER_GAS;
    }

    ////////////////////////////////////////////////////////////////////
    // Admin functions - Contract Control
    ////////////////////////////////////////////////////////////////////
    function pause(string calldata reason) external onlyOwner {
        require(bytes(reason).length > 0, "Reason required");
        _pause();
        pauseReason = reason;
        emit ContractPaused(reason);
    }

    function unpause() external onlyOwner {
        _unpause();
        pauseReason = "";
        emit ContractUnpaused();
    }

    ////////////////////////////////////////////////////////////////////
    // Admin functions - Wallet Configuration
    ////////////////////////////////////////////////////////////////////
    /// @notice Sets the prize wallet address
    /// @param _prize New prize wallet address
    function setPrizeWallet(address _prize) external onlyOwner {
        require(_prize != address(0), "Invalid address");
        prizeWallet = _prize;
        emit WalletsUpdated(_prize, protocolWallet);
    }

    /// @notice Sets the protocol wallet address
    /// @param _protocol New protocol wallet address
    function setProtocolWallet(address _protocol) external onlyOwner {
        require(_protocol != address(0), "Invalid address");
        protocolWallet = _protocol;
        emit WalletsUpdated(prizeWallet, _protocol);
    }

    ////////////////////////////////////////////////////////////////////
    // Admin functions - Transfer Gas Limit Configuration
    ////////////////////////////////////////////////////////////////////
    /// @notice Updates the global default gas limit for ETH transfers
    /// @param newLimit New default gas limit value
    function setDefaultTransferGasLimit(uint256 newLimit) external onlyEthPrizeManager {
        require(newLimit >= MIN_TRANSFER_GAS, "Below minimum gas limit");
        require(newLimit <= MAX_TRANSFER_GAS, "Exceeds maximum gas limit");

        uint256 oldLimit = defaultTransferGasLimit;
        defaultTransferGasLimit = newLimit;

        emit DefaultTransferGasLimitUpdated(oldLimit, newLimit);
    }

    /// @notice Sets a custom gas limit for a specific recipient
    /// @param recipient Address to set custom limit for
    /// @param gasLimit Custom gas limit (0 to use default)
    function setCustomGasLimit(address recipient, uint256 gasLimit) external onlyEthPrizeManager {
        require(recipient != address(0), "Invalid recipient");

        if (gasLimit == 0) {
            delete customGasLimit[recipient];
            emit CustomGasLimitRemoved(recipient);
        } else {
            require(gasLimit >= MIN_TRANSFER_GAS, "Below minimum gas limit");
            require(gasLimit <= MAX_TRANSFER_GAS, "Exceeds maximum gas limit");
            customGasLimit[recipient] = gasLimit;
            emit CustomGasLimitSet(recipient, gasLimit);
        }
    }

    /// @notice Sets custom gas limits for multiple recipients in one transaction
    /// @param recipients Array of addresses
    /// @param gasLimits Array of gas limits (0 to remove/use default)
    function setCustomGasLimitBatch(
        address[] calldata recipients,
        uint256[] calldata gasLimits
    ) external onlyEthPrizeManager {
        require(recipients.length == gasLimits.length, "Length mismatch");

        for (uint256 i = 0; i < recipients.length; i++) {
            address recipient = recipients[i];
            uint256 gasLimit = gasLimits[i];

            require(recipient != address(0), "Invalid recipient");

            if (gasLimit == 0) {
                delete customGasLimit[recipient];
                emit CustomGasLimitRemoved(recipient);
            } else {
                require(gasLimit >= MIN_TRANSFER_GAS, "Below minimum gas limit");
                require(gasLimit <= MAX_TRANSFER_GAS, "Exceeds maximum gas limit");
                customGasLimit[recipient] = gasLimit;
                emit CustomGasLimitSet(recipient, gasLimit);
            }
        }
    }

    /// @notice Returns the effective gas limit for a recipient
    /// @param recipient Address to check
    /// @return gasLimit The gas limit that will be used
    /// @return isCustom Whether this is a custom limit or the default
    function getEffectiveGasLimit(address recipient) external view returns (
        uint256 gasLimit,
        bool isCustom
    ) {
        uint256 custom = customGasLimit[recipient];
        if (custom > 0) {
            return (custom, true);
        }
        return (defaultTransferGasLimit, false);
    }

    ////////////////////////////////////////////////////////////////////
    // Admin functions - Fee Configuration
    ////////////////////////////////////////////////////////////////////
    /// @notice Sets fee parameters for the contract
    /// @param _sellPrizeFeeBps Prize fee on sells in basis points
    /// @param _protocolFeeGrossBps Protocol fee on sells in basis points (before referral deduction)
    /// @param _ipoPrizeFeeBps Prize fee on IPO buys in basis points
    /// @param _ipoProtocolFeeBps Protocol fee on IPO buys in basis points
    function setFees(
        uint256 _sellPrizeFeeBps,
        uint256 _protocolFeeGrossBps,
        uint256 _ipoPrizeFeeBps,
        uint256 _ipoProtocolFeeBps
    ) external onlyOwner {
        require(
            _sellPrizeFeeBps <= MAX_SELL_PRIZE_FEE_BPS,
            "Sell prize fee too high"
        );
        require(
            _protocolFeeGrossBps <= MAX_PROTOCOL_FEE_BPS,
            "Protocol fee too high"
        );
        require(
            _ipoPrizeFeeBps <= MAX_IPO_PRIZE_FEE_BPS,
            "IPO prize fee too high"
        );
        require(
            _ipoProtocolFeeBps <= MAX_IPO_PROTOCOL_FEE_BPS,
            "IPO protocol fee too high"
        );
        require(
            _protocolFeeGrossBps >= REFERRAL_FEE_BPS,
            "Protocol fee below referral fee"
        );
        uint256 totalCommission = _sellPrizeFeeBps + _protocolFeeGrossBps + CREATOR_FEE_BPS;
        require(
            totalCommission <= MAX_TOTAL_COMMISSION_BPS,
            "Commission exceeds max"
        );
        SELL_PRIZE_FEE_BPS = _sellPrizeFeeBps;
        PROTOCOL_FEE_GROSS_BPS = _protocolFeeGrossBps;
        COMMISSION_BPS = totalCommission;
        IPO_PRIZE_FEE_BPS = _ipoPrizeFeeBps;
        IPO_PROTOCOL_FEE_BPS = _ipoProtocolFeeBps;
        emit FeesUpdated(
            SELL_PRIZE_FEE_BPS,
            PROTOCOL_FEE_GROSS_BPS,
            IPO_PRIZE_FEE_BPS,
            IPO_PROTOCOL_FEE_BPS,
            CREATOR_FEE_BPS
        );
    }

    ////////////////////////////////////////////////////////////////////
    // Admin functions - Trading Parameters
    ////////////////////////////////////////////////////////////////////
    /// @notice Sets trading parameters for the contract
    /// @param _lotSizeUnits Size of one lot in units
    /// @param _lotsPerCallMin Minimum lots per call
    /// @param _lotsPerCallMax Maximum lots per call
    function setTradingParameters(
        uint256 _lotSizeUnits,
        uint256 _lotsPerCallMin,
        uint256 _lotsPerCallMax
    ) external onlyOwner {
        require(
            _lotSizeUnits >= ONE_FULL_SHARE_IN_UNITS / 10000 &&
                _lotSizeUnits <= 10 * ONE_FULL_SHARE_IN_UNITS,
            "Lot size out of range"
        );
        require(
            ONE_FULL_SHARE_IN_UNITS % _lotSizeUnits == 0,
            "lot size must divide ONE_FULL_SHARE_IN_UNITS"
        );
        require(
            _lotsPerCallMin >= 1 && _lotsPerCallMin <= 100,
            "lots per call minimum out of range"
        );
        require(
            _lotsPerCallMax >= _lotsPerCallMin && _lotsPerCallMax <= 100,
            "lots per call maximum out of range"
        );

        LOT_SIZE_UNITS = _lotSizeUnits;
        LOTS_PER_CALL_MIN = _lotsPerCallMin;
        LOTS_PER_CALL_MAX = _lotsPerCallMax;
        emit TradingParametersUpdated(
            LOT_SIZE_UNITS,
            LOTS_PER_CALL_MIN,
            LOTS_PER_CALL_MAX
        );
    }

    ////////////////////////////////////////////////////////////////////
    // Admin functions - IPO Parameters
    ////////////////////////////////////////////////////////////////////
    /// @notice Sets IPO-specific parameters
    /// @param _ipoFeeDuration Duration of IPO fee window
    /// @param _ipoLotsPerCallMin Minimum IPO lots per call
    /// @param _ipoLotsPerCallMax Maximum IPO lots per call
    /// @param _ipoMaxLotsPerWallet Maximum total IPO lots per wallet
    /// @param _ipoTradesPerSecond IPO rate limit in trades per second
    function setIpoParameters(
        uint256 _ipoFeeDuration,
        uint256 _ipoLotsPerCallMin,
        uint256 _ipoLotsPerCallMax,
        uint256 _ipoMaxLotsPerWallet,
        uint256 _ipoTradesPerSecond
    ) external onlyOwner {
        require(
            _ipoFeeDuration >= MIN_IPO_FEE_DURATION && _ipoFeeDuration <= MAX_IPO_FEE_DURATION,
            "IPO fee duration out of range"
        );
        require(
            _ipoLotsPerCallMin >= 1 && _ipoLotsPerCallMin <= 100,
            "IPO lots per call minimum out of range"
        );
        require(
            _ipoLotsPerCallMax >= _ipoLotsPerCallMin && _ipoLotsPerCallMax <= 100,
            "IPO lots per call maximum out of range"
        );
        require(
            _ipoMaxLotsPerWallet >= 1 && _ipoMaxLotsPerWallet <= 1000,
            "IPO total lots per wallet maximum out of range"
        );
        require(
            _ipoTradesPerSecond >= 1 && _ipoTradesPerSecond <= 20,
            "IPO trades per second out of range"
        );

        IPO_FEE_DURATION = _ipoFeeDuration;
        IPO_LOTS_PER_CALL_MIN = _ipoLotsPerCallMin;
        IPO_LOTS_PER_CALL_MAX = _ipoLotsPerCallMax;
        IPO_MAX_LOTS_PER_WALLET = _ipoMaxLotsPerWallet;
        IPO_TRADES_PER_SECOND = _ipoTradesPerSecond;
        emit IpoParametersUpdated(
            IPO_FEE_DURATION,
            IPO_LOTS_PER_CALL_MIN,
            IPO_LOTS_PER_CALL_MAX,
            IPO_MAX_LOTS_PER_WALLET,
            IPO_TRADES_PER_SECOND
        );
    }

    ////////////////////////////////////////////////////////////////////
    // Creator fee management
    ////////////////////////////////////////////////////////////////////

    /// @notice Updates the creator fee (owner only, bounded)
    function setCreatorFee(uint256 _creatorFeeBps) external onlyOwner {
        require(_creatorFeeBps <= MAX_CREATOR_FEE_BPS, "Creator fee too high");
        uint256 totalCommission = SELL_PRIZE_FEE_BPS + PROTOCOL_FEE_GROSS_BPS + _creatorFeeBps;
        require(totalCommission <= MAX_TOTAL_COMMISSION_BPS, "Commission exceeds max");
        CREATOR_FEE_BPS = _creatorFeeBps;
        COMMISSION_BPS = totalCommission;
        emit CreatorFeeUpdated(_creatorFeeBps);
    }

    /// @notice Binds a card to its creator's payout wallet (identity verified off-chain).
    /// @dev address(0) unbinds — future fees accrue on-chain again.
    function setCreatorWallet(
        uint256 playerId,
        address wallet
    ) external playerExists(playerId) onlyCardManager {
        creatorWallet[playerId] = wallet;
        emit CreatorWalletSet(playerId, wallet);
    }

    /// @notice Pays all accrued fees for a card to its registered creator wallet. Anyone can call.
    function claimCreatorFees(uint256 playerId) external nonReentrant playerExists(playerId) {
        address wallet = creatorWallet[playerId];
        require(wallet != address(0), "Creator wallet not registered");
        uint256 amount = accruedCreatorFeesWei[playerId];
        require(amount > 0, "Nothing to claim");
        accruedCreatorFeesWei[playerId] = 0;
        totalAccruedCreatorFeesWei -= amount;
        (bool ok, ) = payable(wallet).call{value: amount}("");
        require(ok, "Claim transfer failed");
        emit CreatorFeesClaimed(playerId, wallet, amount);
    }

    ////////////////////////////////////////////////////////////////////
    // Referrer management functions
    ////////////////////////////////////////////////////////////////////
    
    /// @dev REFERRAL SYSTEM DESIGN PHILOSOPHY:
    /// 
    /// Referral attribution is wallet-based. This design intentionally allows the the user
    /// to transfer shares to new wallets if their original wallet is compromised,
    /// or if the platform migrates away from the current wallet provider
    /// The referrer manager can relink the referrer relationship using updateReferrerForUsers().
    ///
    /// COMPETITION ELIGIBILITY:
    /// Transferred shares are tracked separately from purchased shares via the "reason"
    /// field in UserSharesChanged events ("Transfer" vs "Buy"). Off-chain systems can
    /// differentiate between shares acquired via purchase vs transfer. This allows 
    /// competitions to require purchased shares only, preventing users from gaining 
    /// eligibility advantages by transferring shares between wallets.
    
    /// @notice Sets a referrer for a user
    /// @param user The user address
    /// @param referrer The referrer address
    function setUserReferrer(
        address user,
        address referrer
    ) external onlyReferrerManager {
        require(referrer != address(0), "Invalid referrer");
        require(
            referrerOf[user] == address(0),
            "Referrer already set for user"
        );
        require(user != address(0), "Invalid user address");
        require(
            referrer != user && referrer != address(this),
            "Invalid referrer - Cannot self refer"
        );
        referrerOf[user] = referrer;
        emit ReferrerSet(user, referrer);
    }

    /// @notice Sets referrers for multiple users in a single transaction
    /// @param users Array of user addresses
    /// @param referrers Array of referrer addresses (must match users length)
    function setMultipleUserReferrers(
        address[] calldata users,
        address[] calldata referrers
    ) external onlyReferrerManager {
        require(
            users.length == referrers.length,
            "Arrays must be equal length"
        );
        for (uint256 i = 0; i < users.length; i++) {
            address user = users[i];
            address referrer = referrers[i];
            require(
                user != address(0) && referrer != address(0),
                "Invalid address"
            );
            require(
                referrer != user && referrer != address(this),
                "Invalid referrer"
            );
            require(
                referrerOf[user] == address(0),
                "Referrer already set for user"
            );
            referrerOf[user] = referrer;
            emit ReferrerSet(user, referrer);
        }
    }

    /// @notice Migrate referrals from an old wallet to a new wallet when a user migrates wallets
    /// @dev This function handles relinking referrals should a user migrate to a new wallet address
    /// @param oldReferrer The old referrer address being migrated from
    /// @param newReferrer The new referrer address to migrate to
    /// @param referredUsers Array of users who were referred by the old referrer (can be single user or multiple users)
    function updateReferrerForUsers(
        address oldReferrer,
        address newReferrer,
        address[] calldata referredUsers
    ) external onlyReferrerManager {
        require(oldReferrer != address(0), "Invalid old referrer");
        require(newReferrer != address(0), "Invalid new referrer");
        require(oldReferrer != newReferrer, "Old and new referrer must be different");
        require(newReferrer != address(this), "Cannot refer to contract");
        require(referredUsers.length > 0, "Must provide at least one referred user");

        uint256 migratedCount = 0;
        for (uint256 i = 0; i < referredUsers.length; i++) {
            address user = referredUsers[i];
            require(user != address(0), "Invalid user address");
            require(referrerOf[user] == oldReferrer, "User not referred by old referrer");
            require(user != newReferrer, "Cannot self refer");
            
            referrerOf[user] = newReferrer;
            emit ReferrerSet(user, newReferrer);
            migratedCount++;
        }

        emit ReferrerMigrated(oldReferrer, newReferrer, migratedCount);
    }

    ////////////////////////////////////////////////////////////////////
    // Player and trading functions
    ////////////////////////////////////////////////////////////////////
    
    /// @notice Internal helper function to add a player and optionally snipe shares
    /// @param name The name of the player
    /// @param snipeAmountUnits The amount of shares to snipe in units (can be 0)
    function _addPlayerAndSnipeByUnits(
        string memory name,
        uint256 snipeAmountUnits
    ) internal nonReentrant {
        uint256 playerId = nextPlayerId;
        players[playerId] = Player(name, false, 0, 0);
        nextPlayerId++;
        emit PlayerAdded(playerId, name, snipeAmountUnits);
        if (snipeAmountUnits > 0) {
            require(snipeAmountUnits % LOT_SIZE_UNITS == 0, "bad step");
            uint256 cost = getBuyPriceRaw(playerId, snipeAmountUnits);
            require(msg.value >= cost, "Insufficient ETH for snipe");
            sharesBalance[playerId][msg.sender] += snipeAmountUnits;
            sharesSupply[playerId] += snipeAmountUnits;
            emit Trade(
                msg.sender,
                playerId,
                true,
                snipeAmountUnits,
                cost,
                0,
                sharesSupply[playerId],
                false
            );
            _emitUserSharesChanged(
                msg.sender,
                playerId,
                int256(snipeAmountUnits),
                cost,
                0,
                REASON_PRIZE_WALLET_SNIPE
            );
            _emitPlayerSupplyChanged(playerId, int256(snipeAmountUnits), REASON_PRIZE_WALLET_SNIPE);
            emit SharePrizeDeposited(playerId, snipeAmountUnits);
            if (msg.value > cost) {
                (bool success, ) = payable(msg.sender).call{
                    value: msg.value - cost
                }("");
                require(success, "Refund failed");
            }
        }

        // Refund if zero-snipe with ETH attached
        if (snipeAmountUnits == 0 && msg.value > 0) {
            (bool success, ) = payable(msg.sender).call{value: msg.value}("");
            require(success, "Refund failed");
        }
    }

    /// @notice Adds a new player and optionally snipes shares by units
    /// @param name The name of the player
    /// @param snipeAmountUnits The amount of shares to snipe in units (can be 0)
    function addPlayerAndSnipeByUnits(
        string memory name,
        uint256 snipeAmountUnits
    ) public payable onlyCardManager {
        _addPlayerAndSnipeByUnits(name, snipeAmountUnits);
    }

    /// @notice Adds a new player and optionally snipes shares by lots
    /// @param name The name of the player
    /// @param numLots The number of lots to snipe (can be 0)
    function addPlayerAndSnipeByLots(
        string memory name,
        uint256 numLots
    ) public payable onlyCardManager {
        require(numLots >= 0, "numLots must be positive");
        uint256 snipeAmountUnits = numLots * LOT_SIZE_UNITS;
        _addPlayerAndSnipeByUnits(name, snipeAmountUnits);
    }

    /// @notice Enables or disables trading for a player (starts IPO if first time enabled)
    /// @param playerId The player ID
    /// @param enabled True to enable trading, false to disable
    function setTradingStatus(
        uint256 playerId,
        bool enabled
    ) public playerExists(playerId) onlyTradingToggler {
        if (
            enabled &&
            !players[playerId].tradingEnabled &&
            players[playerId].ipoWindowStartTimestamp == 0
        ) {
            players[playerId].ipoWindowStartTimestamp = block.timestamp - 1;
            players[playerId].ipoWindowEndTimestamp =
                block.timestamp - 1 +
                IPO_FEE_DURATION;
            emit PlayerIPO(
                playerId,
                players[playerId].name,
                players[playerId].ipoWindowStartTimestamp,
                players[playerId].ipoWindowEndTimestamp,
                sharesSupply[playerId]
            );
        }
        players[playerId].tradingEnabled = enabled;
        emit TradingStatusUpdated(playerId, enabled);
    }

    /// @notice Enable or disable trading for multiple players at once
    /// @param playerIds Array of player IDs to update
    /// @param enabled true to enable trading (and start IPO if first time), false to disable
    /// @return updatedCount The number of players successfully updated
    function setTradingStatusBulk(
        uint256[] calldata playerIds,
        bool enabled
    ) external onlyTradingToggler returns (uint256 updatedCount) {
        require(playerIds.length > 0, "Must provide at least one player ID");
        
        for (uint256 i = 0; i < playerIds.length; i++) {
            uint256 playerId = playerIds[i];
            require(playerId < nextPlayerId, "Player does not exist");
            
            if (
                enabled &&
                !players[playerId].tradingEnabled &&
                players[playerId].ipoWindowStartTimestamp == 0
            ) {
                players[playerId].ipoWindowStartTimestamp = block.timestamp - 1;
                players[playerId].ipoWindowEndTimestamp =
                    block.timestamp - 1 +
                    IPO_FEE_DURATION;
                emit PlayerIPO(
                    playerId,
                    players[playerId].name,
                    players[playerId].ipoWindowStartTimestamp,
                    players[playerId].ipoWindowEndTimestamp,
                    sharesSupply[playerId]
                );
            }
            players[playerId].tradingEnabled = enabled;
            emit TradingStatusUpdated(playerId, enabled);
            updatedCount++;
        }
        
        return updatedCount;
    }

    /// @notice Buy fractional shares for a player in 18-decimal units
    /// @param playerId The ID of the player
    /// @param amountUnits The number of shares to buy in 18-decimal units
    function buySharesByUnits(
        uint256 playerId,
        uint256 amountUnits
    ) external payable whenNotPaused playerExists(playerId) {
        _buySharesUnits(playerId, amountUnits);
    }

    /// @notice Buy shares by specifying number of lots
    /// @param playerId The ID of the player
    /// @param numLots The number of lots to buy
    function buySharesByLots(
        uint256 playerId,
        uint256 numLots
    ) external payable whenNotPaused playerExists(playerId) {
        require(numLots > 0, "numLots must be positive");
        uint256 amountUnits = numLots * LOT_SIZE_UNITS;
        _buySharesUnits(playerId, amountUnits);
    }

    function _buySharesUnits(
        uint256 playerId,
        uint256 amountUnits
    ) internal nonReentrant {
        require(amountUnits > 0, "amount=0");
        require(amountUnits >= LOT_SIZE_UNITS, "below min size");
        require(amountUnits % LOT_SIZE_UNITS == 0, "bad step");
        uint256 lots = amountUnits / LOT_SIZE_UNITS;
        uint256 baseCost = getBuyPriceRaw(playerId, amountUnits);
        require(
            players[playerId].tradingEnabled || hasRole(ROLE_CARD_MANAGER, msg.sender),
            "Trading disabled"
        );

        if (
            isIpoPrizeFeeActive(playerId) &&
            !hasRole(ROLE_CARD_MANAGER, msg.sender)
        ) {
            // IPO-specific checks
            require(
                lots >= IPO_LOTS_PER_CALL_MIN && lots <= IPO_LOTS_PER_CALL_MAX,
                "IPO lots per call out of range"
            );
            require(
                _ipoLotsUsed[playerId][msg.sender] + lots <= IPO_MAX_LOTS_PER_WALLET,
                "Exceeds IPO lots per wallet limit"
            );
            // Linear rate limit: allowance accumulates from IPO start
            uint256 start = players[playerId].ipoWindowStartTimestamp;
            uint256 allowance = (block.timestamp - start) *
                IPO_TRADES_PER_SECOND; // floor by integer math
            require(
                _ipoTradesUsed[playerId][msg.sender] + 1 <= allowance,
                "IPO rate limit exceeded"
            );
            _ipoTradesUsed[playerId][msg.sender] += 1; // consume 1 from time-based budget
            _ipoLotsUsed[playerId][msg.sender] += lots; // consume lots from total-lots budget
        } else if (!hasRole(ROLE_CARD_MANAGER, msg.sender)) {
            // Non-IPO checks
            require(
                lots >= LOTS_PER_CALL_MIN && lots <= LOTS_PER_CALL_MAX,
                "Lots per call out of range"
            );
        }

        uint256 prizeFee = isIpoPrizeFeeActive(playerId)
            ? (baseCost * IPO_PRIZE_FEE_BPS) / BPS
            : 0;
        uint256 protFee = isIpoPrizeFeeActive(playerId)
            ? (baseCost * IPO_PROTOCOL_FEE_BPS) / BPS
            : 0;
        uint256 totalCost = baseCost + prizeFee + protFee;
        require(msg.value >= totalCost, "Insufficient ETH");

        sharesBalance[playerId][msg.sender] += amountUnits;
        sharesSupply[playerId] += amountUnits;
        emit Trade(
            msg.sender,
            playerId,
            true,
            amountUnits,
            totalCost,
            prizeFee + protFee,
            sharesSupply[playerId],
            isIpoPrizeFeeActive(playerId)
        );
        _emitUserSharesChanged(
            msg.sender,
            playerId,
            int256(amountUnits),
            totalCost,
            prizeFee + protFee,
            REASON_BUY
        );
        _emitPlayerSupplyChanged(playerId, int256(amountUnits), REASON_BUY);

        if (prizeFee > 0) {
            (bool ok1, ) = payable(prizeWallet).call{value: prizeFee}("");
            require(ok1, "Prize fee transfer failed");
            emit EthPrizeDeposited(prizeFee);
        }
        if (protFee > 0) {
            (bool ok2, ) = payable(protocolWallet).call{value: protFee}("");
            require(ok2, "Protocol IPO fee transfer failed");
        }
        if (prizeFee + protFee > 0) {
            emit IpoBuyFeesApplied(
                msg.sender,
                playerId,
                baseCost,
                prizeFee,
                protFee,
                totalCost
            );
        }
        if (msg.value > totalCost) {
            (bool success, ) = payable(msg.sender).call{
                value: msg.value - totalCost
            }("");
            require(success, "Refund failed");
        }
    }

    /// @notice Calculates the cost to buy `amountUnits` shares for a player, including IPO fees if applicable
    /// @param playerId The ID of the player
    /// @param amountUnits The number of shares to buy in 18-decimal units
    /// @return The total cost in wei, including base cost and any applicable IPO fees
    function getBuyPriceByUnits(
        uint256 playerId,
        uint256 amountUnits
    ) public view playerExists(playerId) returns (uint256) {
        uint256 baseCost = getBuyPriceRaw(playerId, amountUnits);
        if (isIpoPrizeFeeActive(playerId)) {
            uint256 prizeFee = (baseCost * IPO_PRIZE_FEE_BPS) / BPS;
            uint256 protFee = (baseCost * IPO_PROTOCOL_FEE_BPS) / BPS;
            return baseCost + prizeFee + protFee;
        }
        return baseCost;
    }

    /// @notice Calculates the raw cost to buy shares without fees (using bonding curve integral)
    /// @param playerId The ID of the player
    /// @param a The amount of shares in units
    /// @return The raw cost in wei (without fees)
    function getBuyPriceRaw(
        uint256 playerId,
        uint256 a
    ) public view playerExists(playerId) returns (uint256) {
        require(a > 0, "amount=0");
        uint256 s = sharesSupply[playerId]; // units (18d)
        uint256 num = _cube(s + a) - _cube(s);
        uint256 denom = 3 *
            BONDING_CURVE_DENOMINATOR *
            ONE_FULL_SHARE_IN_UNITS3;
        return Math.mulDiv(num, 1 ether, denom, Math.Rounding.Ceil);
    }

    /// @notice Calculates the gross payout for selling shares without fees (using bonding curve integral)
    /// @param playerId The ID of the player
    /// @param a The amount of shares in units
    /// @return The gross payout in wei (before fees)
    function calculateGrossSellPayoutByUnits(
        uint256 playerId,
        uint256 a
    ) public view playerExists(playerId) returns (uint256) {
        require(a > 0, "amount=0");
        uint256 s = sharesSupply[playerId];
        require(s >= a, "Not enough supply");
        uint256 num = _cube(s) - _cube(s - a);
        uint256 denom = 3 *
            BONDING_CURVE_DENOMINATOR *
            ONE_FULL_SHARE_IN_UNITS3;
        return Math.mulDiv(num, 1 ether, denom);
    }

    /// @notice Get the price to buy a specific number of lots
    /// @param playerId The ID of the player
    /// @param numLots The number of lots
    /// @return The total cost in wei, including any applicable IPO fees
    function getBuyPriceByLots(
        uint256 playerId,
        uint256 numLots
    ) external view playerExists(playerId) returns (uint256) {
        require(numLots > 0, "numLots must be positive");
        uint256 amountUnits = numLots * LOT_SIZE_UNITS;
        return getBuyPriceByUnits(playerId, amountUnits);
    }

    /// @notice Get the gross payout for selling a specific number of lots
    /// @param playerId The ID of the player
    /// @param numLots The number of lots
    /// @return The gross payout in wei (before fees)
    function calculateGrossSellPayoutByLots(
        uint256 playerId,
        uint256 numLots
    ) external view playerExists(playerId) returns (uint256) {
        require(numLots > 0, "numLots must be positive");
        uint256 amountUnits = numLots * LOT_SIZE_UNITS;
        return calculateGrossSellPayoutByUnits(playerId, amountUnits);
    }


    function _square(uint256 x) internal pure returns (uint256) {
        return Math.mulDiv(x, x, 1); // 512-bit intermediate, no overflow
    }

    function _cube(uint256 x) internal pure returns (uint256) {
        return Math.mulDiv(_square(x), x, 1); // 512-bit intermediate, no overflow
    }

    /// @notice Sell fractional shares for a player in 18-decimal units
    /// @param playerId The ID of the player
    /// @param amountUnits The number of shares to sell in 18-decimal units
    /// @param minNetPayout Minimum net payout (after fees) the seller is willing to accept
    function sellSharesByUnits(
        uint256 playerId,
        uint256 amountUnits,
        uint256 minNetPayout
    ) external whenNotPaused playerExists(playerId) {
        _sellSharesUnits(playerId, amountUnits, minNetPayout);
    }

    /// @notice Sell shares by specifying number of lots
    /// @param playerId The ID of the player
    /// @param numLots The number of lots to sell
    /// @param minNetPayout Minimum net payout (after fees) the seller is willing to accept
    function sellSharesByLots(
        uint256 playerId,
        uint256 numLots,
        uint256 minNetPayout
    ) external whenNotPaused playerExists(playerId) {
        require(numLots > 0, "numLots must be positive");
        uint256 amountUnits = numLots * LOT_SIZE_UNITS;
        _sellSharesUnits(playerId, amountUnits, minNetPayout);
    }

    /// @notice Core sell logic without lot size validation
    /// @dev Internal function that executes the actual sell mechanics
    /// @param playerId The ID of the player
    /// @param amountUnits The amount to sell in units
    /// @param minNetPayout Minimum net payout after fees
    function _executeSell(
        uint256 playerId,
        uint256 amountUnits,
        uint256 minNetPayout
    ) internal {
        require(amountUnits > 0, "amount=0");
        require(
            players[playerId].tradingEnabled || hasRole(ROLE_CARD_MANAGER, msg.sender),
            "Trading disabled"
        );
        require(
            sharesBalance[playerId][msg.sender] >= amountUnits,
            "Not enough shares"
        );

        uint256 grossPayout = calculateGrossSellPayoutByUnits(playerId, amountUnits);

        sharesBalance[playerId][msg.sender] -= amountUnits;
        sharesSupply[playerId] -= amountUnits;

        uint256 toPrize = (grossPayout * SELL_PRIZE_FEE_BPS) / BPS;
        uint256 toProtocol = (grossPayout * PROTOCOL_FEE_GROSS_BPS) / BPS;
        uint256 toCreator = (grossPayout * CREATOR_FEE_BPS) / BPS;
        uint256 toReferrer = 0;

        address referrer = (referrerOf[msg.sender] != address(0) &&
            referrerOf[msg.sender] != msg.sender)
            ? referrerOf[msg.sender]
            : protocolWallet;

        if (referrer != protocolWallet) {
            toReferrer = (grossPayout * REFERRAL_FEE_BPS) / BPS;
            toProtocol -= toReferrer;
        }

        uint256 netPayout = grossPayout - toPrize - toProtocol - toReferrer - toCreator;
        require(netPayout >= minNetPayout, "Slippage: payout below minimum");
        require(
            address(this).balance >= toPrize + toProtocol + toReferrer + toCreator + netPayout,
            "Insufficient balance"
        );

        uint256 supplyAfter = sharesSupply[playerId];
        uint256 totalFees = toPrize + toProtocol + toReferrer + toCreator;
        bool ipoActive = isIpoPrizeFeeActive(playerId);

        emit Trade(
            msg.sender,
            playerId,
            false,
            amountUnits,
            netPayout,
            totalFees,
            supplyAfter,
            ipoActive
        );

        _emitUserSharesChanged(
            msg.sender,
            playerId,
            -int256(amountUnits),
            grossPayout,
            totalFees,
            REASON_SELL
        );
        _emitPlayerSupplyChanged(playerId, -int256(amountUnits), REASON_SELL);

        emit EthPrizeDeposited(toPrize);

        (bool s1, ) = payable(prizeWallet).call{value: toPrize}("");
        require(s1, "Prize collection failed");
        (bool s2, ) = payable(protocolWallet).call{value: toProtocol}("");
        require(s2, "Protocol payout failed");
        if (toReferrer > 0) {
            bool referralSuccess = _transferReferralFee(referrer, toReferrer, msg.sender);
            if (referralSuccess) {
                emit ReferralFeePaid(referrer, msg.sender, toReferrer);
            }
        }
        if (toCreator > 0) {
            _payOrAccrueCreatorFee(playerId, toCreator);
        }
        (bool s4, ) = payable(msg.sender).call{value: netPayout}("");
        require(s4, "User payout failed");
    }

    /// @notice Sells shares with lot size validation
    function _sellSharesUnits(
        uint256 playerId,
        uint256 amountUnits,
        uint256 minNetPayout
    ) internal nonReentrant {
        require(amountUnits >= LOT_SIZE_UNITS, "below min size");
        require(amountUnits % LOT_SIZE_UNITS == 0, "bad step");

        uint256 lots = amountUnits / LOT_SIZE_UNITS;
        if (!hasRole(ROLE_CARD_MANAGER, msg.sender)) {
            require(
                lots >= LOTS_PER_CALL_MIN && lots <= LOTS_PER_CALL_MAX,
                "Lots out of range"
            );
        }

        _executeSell(playerId, amountUnits, minNetPayout);
    }

    /// @notice Sells only the fractional remainder that doesn't align with current LOT_SIZE_UNITS
    /// @dev Allows users to clean up balances that became misaligned after LOT_SIZE_UNITS changes
    /// @param playerId The ID of the player
    /// @param minNetPayout Minimum net payout (after fees) the seller is willing to accept
    function sellFractionalRemainder(
        uint256 playerId,
        uint256 minNetPayout
    ) external whenNotPaused playerExists(playerId) nonReentrant {
        uint256 balance = sharesBalance[playerId][msg.sender];
        uint256 remainder = balance % LOT_SIZE_UNITS;
        require(remainder > 0, "No fractional remainder");

        _executeSell(playerId, remainder, minNetPayout);
    }

    /// @notice Transfer fractional shares to another address in 18-decimal units
    /// @dev This supports wallet migration.
    /// 
    /// COMPETITION ELIGIBILITY: Transferred shares are flagged with reason="Transfer" in
    /// UserSharesChanged events, allowing off-chain systems to distinguish them from 
    /// purchased shares (reason="Buy"). Competitions may require purchased shares only,
    /// preventing users from gaining eligibility by transferring shares between wallets.
    /// 
    /// @param to The recipient address
    /// @param playerId The ID of the player
    /// @param amountUnits The number of shares to transfer in 18-decimal units
    function transferSharesByUnits(
        address to,
        uint256 playerId,
        uint256 amountUnits
    ) public whenNotPaused playerExists(playerId) {
        require(to != address(0), "Cannot transfer to zero address");
        require(to != msg.sender, "Cannot transfer to self");
        require(to != address(this), "Cannot transfer to contract");
        require(amountUnits > 0, "amount=0");
        require(amountUnits >= LOT_SIZE_UNITS, "below min size");
        require(amountUnits % LOT_SIZE_UNITS == 0, "bad step");
        require(
            sharesBalance[playerId][msg.sender] >= amountUnits,
            "Not enough shares"
        );
        sharesBalance[playerId][msg.sender] -= amountUnits;
        sharesBalance[playerId][to] += amountUnits;
        emit SharesTransferred(msg.sender, to, playerId, amountUnits);
        _emitTransferSharesChanged(msg.sender, to, playerId, amountUnits, REASON_TRANSFER);
    }

    /// @notice Transfer shares by specifying number of lots
    /// @param to The recipient address
    /// @param playerId The ID of the player
    /// @param numLots The number of lots to transfer
    function transferSharesByLots(
        address to,
        uint256 playerId,
        uint256 numLots
    ) external whenNotPaused playerExists(playerId) {
        require(numLots > 0, "numLots must be positive");
        uint256 amountUnits = numLots * LOT_SIZE_UNITS;
        transferSharesByUnits(to, playerId, amountUnits);
    }

    /// @notice Awards share prizes to a winner in 18-decimal units (internal function)
    /// @param winner The recipient address
    /// @param playerId The ID of the player
    /// @param amountUnits The number of shares to award in 18-decimal units
    /// @param description The prize description
    function awardSharePrizeByUnits(
        address winner,
        uint256 playerId,
        uint256 amountUnits,
        string calldata description
    ) internal whenNotPaused playerExists(playerId) onlyCardSender {
        require(amountUnits > 0, "amount=0");
        require(amountUnits >= LOT_SIZE_UNITS, "below min size");
        require(amountUnits % LOT_SIZE_UNITS == 0, "bad step");
        require(
            sharesBalance[playerId][msg.sender] >= amountUnits,
            "Not enough shares"
        );
        sharesBalance[playerId][msg.sender] -= amountUnits;
        sharesBalance[playerId][winner] += amountUnits;
        emit SharesTransferred(msg.sender, winner, playerId, amountUnits);
        emit SharePrizeAwarded(winner, playerId, amountUnits, description);
        _emitTransferSharesChanged(msg.sender, winner, playerId, amountUnits, REASON_PRIZE_AWARD);
    }

    /// @notice Award share prizes by specifying number of lots
    /// @param winner The recipient address
    /// @param playerId The ID of the player
    /// @param numLots The number of lots to award
    /// @param description The prize description
    function awardSharePrizeByLots(
        address winner,
        uint256 playerId,
        uint256 numLots,
        string calldata description
    ) external {
        require(numLots > 0, "numLots must be positive");
        uint256 amountUnits = numLots * LOT_SIZE_UNITS;
        awardSharePrizeByUnits(winner, playerId, amountUnits, description);
    }

    /// @notice Award share prizes from multiple players to multiple winners
    /// @param playerIds Array of player IDs (must match other arrays length)
    /// @param winners Array of winner addresses (must match other arrays length)
    /// @param amountUnits Array of share amounts in 18-decimal units (must match other arrays length)
    /// @param descriptions Array of prize descriptions (must match other arrays length)
    function awardSharePrizeBatchMultiPlayerMultiUser(
        uint256[] calldata playerIds,
        address[] calldata winners,
        uint256[] calldata amountUnits,
        string[] calldata descriptions
    ) external whenNotPaused onlyCardSender nonReentrant {
        require(playerIds.length > 0, "Must provide at least one prize");
        require(
            playerIds.length == winners.length &&
            playerIds.length == amountUnits.length &&
            playerIds.length == descriptions.length,
            "Arrays must be equal length"
        );

        for (uint256 i = 0; i < playerIds.length; i++) {
            uint256 playerId = playerIds[i];
            address winner = winners[i];
            uint256 amount = amountUnits[i];
            string calldata description = descriptions[i];

            require(playerId < nextPlayerId, "Player does not exist");
            require(winner != address(0), "Invalid winner address");
            require(amount > 0, "amount=0");
            require(amount >= LOT_SIZE_UNITS, "below min size");
            require(amount % LOT_SIZE_UNITS == 0, "bad step");
            
            require(
                sharesBalance[playerId][msg.sender] >= amount,
                "Not enough shares"
            );

            sharesBalance[playerId][msg.sender] -= amount;
            sharesBalance[playerId][winner] += amount;
            
            emit SharesTransferred(msg.sender, winner, playerId, amount);
            emit SharePrizeAwarded(winner, playerId, amount, description);
            _emitTransferSharesChanged(msg.sender, winner, playerId, amount, REASON_PRIZE_AWARD);
        }
    }

    /// @notice Award share prizes from multiple players to multiple winners (by lots)
    /// @param playerIds Array of player IDs (must match other arrays length)
    /// @param winners Array of winner addresses (must match other arrays length)
    /// @param numLots Array of number of lots (must match other arrays length)
    /// @param descriptions Array of prize descriptions (must match other arrays length)
    function awardSharePrizeBatchMultiPlayerMultiUserByLots(
        uint256[] calldata playerIds,
        address[] calldata winners,
        uint256[] calldata numLots,
        string[] calldata descriptions
    ) external whenNotPaused onlyCardSender nonReentrant {
        require(playerIds.length > 0, "Must provide at least one prize");
        require(
            playerIds.length == winners.length &&
            playerIds.length == numLots.length &&
            playerIds.length == descriptions.length,
            "Arrays must be equal length"
        );

        for (uint256 i = 0; i < playerIds.length; i++) {
            uint256 playerId = playerIds[i];
            address winner = winners[i];
            uint256 lots = numLots[i];
            string calldata description = descriptions[i];

            require(playerId < nextPlayerId, "Player does not exist");
            require(winner != address(0), "Invalid winner address");
            require(lots > 0, "numLots must be positive");
            
            uint256 amount = lots * LOT_SIZE_UNITS;
            
            require(
                sharesBalance[playerId][msg.sender] >= amount,
                "Not enough shares"
            );

            sharesBalance[playerId][msg.sender] -= amount;
            sharesBalance[playerId][winner] += amount;
            
            emit SharesTransferred(msg.sender, winner, playerId, amount);
            emit SharePrizeAwarded(winner, playerId, amount, description);
            _emitTransferSharesChanged(msg.sender, winner, playerId, amount, REASON_PRIZE_AWARD);
        }
    }

    ////////////////////////////////////////////////////////////////////
    // Prize management functions
    ////////////////////////////////////////////////////////////////////
    /// @notice Awards ETH prize to a winner (with player association)
    /// @param winner The address receiving the prize
    /// @param amount The amount of ETH to award in wei
    /// @param description Description of the prize
    /// @param playerId The player ID to associate the prize with
    function awardEthPrize(
        address winner,
        uint256 amount,
        string calldata description,
        uint256 playerId
    ) external payable whenNotPaused onlyEthPrizeManager nonReentrant {
        require(winner != address(0), "Invalid winner address");
        require(msg.value == amount, "ETH sent must match prize amount");
        bool success = _transferPrize(winner, amount, description);
        if (success) {
            totalEthPrizesAwarded += amount;
            emit EthPrizeAwarded(winner, playerId, amount, description);
        }
        // If failed, ETH is refunded to sender and PrizeTransferFailed was emitted
    }

    /// @notice Awards ETH prize to a winner (without player association)
    /// @param winner The address receiving the prize
    /// @param amount The amount of ETH to award in wei
    /// @param description Description of the prize
    function awardEthPrize(
        address winner,
        uint256 amount,
        string calldata description
    ) external payable whenNotPaused onlyEthPrizeManager nonReentrant {
        require(winner != address(0), "Invalid winner address");
        require(msg.value == amount, "ETH sent must match prize amount");
        bool success = _transferPrize(winner, amount, description);
        if (success) {
            totalEthPrizesAwarded += amount;
            emit EthPrizeAwarded(winner, 0, amount, description);
        }
        // If failed, ETH is refunded to sender and PrizeTransferFailed was emitted
    }

    /// @notice Records an ETH prize that was awarded externally (with player association)
    /// @param winner The address that received the prize
    /// @param amount The amount of ETH awarded in wei
    /// @param description Description of the prize
    /// @param playerId The player ID to associate the prize with
    function recordEthPrizeAwarded(
        address winner,
        uint256 amount,
        string calldata description,
        uint256 playerId
    ) external onlyEthPrizeManager {
        emit EthPrizeAwarded(winner, playerId, amount, description);
        totalEthPrizesAwarded += amount;
    }

    /// @notice Records an ETH prize that was awarded externally (without player association)
    /// @param winner The address that received the prize
    /// @param amount The amount of ETH awarded in wei
    /// @param description Description of the prize
    function recordEthPrizeAwarded(
        address winner,
        uint256 amount,
        string calldata description
    ) external onlyEthPrizeManager {
        emit EthPrizeAwarded(winner, 0, amount, description);
        totalEthPrizesAwarded += amount;
    }

    /// @notice Award ETH prizes to multiple winners in a single transaction
    /// @param winners Array of winner addresses
    /// @param amounts Array of prize amounts in wei (must match winners length)
    /// @param descriptions Array of prize descriptions (must match winners length)
    /// @param playerId The player ID to associate prizes with (0 for global/non-player prizes)
    function awardEthPrizeBatch(
        address[] calldata winners,
        uint256[] calldata amounts,
        string[] calldata descriptions,
        uint256 playerId
    ) external payable whenNotPaused onlyEthPrizeManager nonReentrant {
        require(winners.length > 0, "Must provide at least one winner");
        require(
            winners.length == amounts.length && winners.length == descriptions.length,
            "Arrays must be equal length"
        );

        uint256 totalAmount = 0;
        for (uint256 i = 0; i < amounts.length; i++) {
            totalAmount += amounts[i];
        }
        require(msg.value == totalAmount, "ETH sent must match total prize amount");

        for (uint256 i = 0; i < winners.length; i++) {
            address winner = winners[i];
            uint256 amount = amounts[i];
            string calldata description = descriptions[i];

            require(winner != address(0), "Invalid winner address");
            require(amount > 0, "Prize amount must be positive");

            bool success = _transferPrize(winner, amount, description);
            if (success) {
                totalEthPrizesAwarded += amount;
                emit EthPrizeAwarded(winner, playerId, amount, description);
            }
            // If failed, ETH is refunded to sender and PrizeTransferFailed was emitted
        }
    }

    /// @notice Awards ETH prizes to multiple winners in a single transaction (without player association)
    /// @param winners Array of winner addresses
    /// @param amounts Array of prize amounts in wei (must match winners length)
    /// @param descriptions Array of prize descriptions (must match winners length)
    function awardEthPrizeBatch(
        address[] calldata winners,
        uint256[] calldata amounts,
        string[] calldata descriptions
    ) external payable whenNotPaused onlyEthPrizeManager nonReentrant {
        require(winners.length > 0, "Must provide at least one winner");
        require(
            winners.length == amounts.length && winners.length == descriptions.length,
            "Arrays must be equal length"
        );

        uint256 totalAmount = 0;
        for (uint256 i = 0; i < amounts.length; i++) {
            totalAmount += amounts[i];
        }
        require(msg.value == totalAmount, "ETH sent must match total prize amount");

        for (uint256 i = 0; i < winners.length; i++) {
            address winner = winners[i];
            uint256 amount = amounts[i];
            string calldata description = descriptions[i];

            require(winner != address(0), "Invalid winner address");
            require(amount > 0, "Prize amount must be positive");

            bool success = _transferPrize(winner, amount, description);
            if (success) {
                totalEthPrizesAwarded += amount;
                emit EthPrizeAwarded(winner, 0, amount, description);
            }
            // If failed, ETH is refunded to sender and PrizeTransferFailed was emitted
        }
    }

    ////////////////////////////////////////////////////////////////////
    // Transfer functions
    ////////////////////////////////////////////////////////////////////
    
    /// @notice Transfer all shares of a specific player from caller to a specified address
    /// @param to The recipient address
    /// @param playerId The ID of the player whose shares to transfer
    function transferAllSharesOfIndividualPlayer(address to, uint256 playerId) external whenNotPaused nonReentrant playerExists(playerId) {
        require(to != address(0), "Cannot transfer to zero address");
        require(to != msg.sender, "Cannot transfer to self");
        require(to != address(this), "Cannot transfer to contract");
        
        uint256 balance = sharesBalance[playerId][msg.sender];
        require(balance > 0, "No shares to transfer");
        
        sharesBalance[playerId][msg.sender] = 0;
        sharesBalance[playerId][to] += balance;
        
        emit SharesTransferred(msg.sender, to, playerId, balance);
        _emitTransferSharesChanged(msg.sender, to, playerId, balance, REASON_TRANSFER);
    }
    
    /// @notice Transfer all shares from caller to a specified address
    /// @param to The recipient address
    function transferAllSharesInWallet(address to) external whenNotPaused nonReentrant {
        require(to != address(0), "Cannot transfer to zero address");
        require(to != msg.sender, "Cannot transfer to self");
        require(to != address(this), "Cannot transfer to contract");
        
        uint256 transferCount = 0;
        for (uint256 playerId = 0; playerId < nextPlayerId; playerId++) {
            uint256 balance = sharesBalance[playerId][msg.sender];
            if (balance > 0) {
                sharesBalance[playerId][msg.sender] = 0;
                sharesBalance[playerId][to] += balance;
                emit SharesTransferred(msg.sender, to, playerId, balance);
                _emitTransferSharesChanged(msg.sender, to, playerId, balance, REASON_TRANSFER);
                transferCount++;
            }
        }
        
        require(transferCount > 0, "No shares to transfer");
    }

    ////////////////////////////////////////////////////////////////////
    // Internal ETH Transfer Helpers
    ////////////////////////////////////////////////////////////////////
    /// @notice Gets the effective gas limit for a recipient
    /// @param recipient Address to get gas limit for
    /// @return Gas limit to use (custom if set, otherwise default)
    function _getGasLimitFor(address recipient) internal view returns (uint256) {
        uint256 custom = customGasLimit[recipient];
        return custom > 0 ? custom : defaultTransferGasLimit;
    }

    /// @notice Transfers referral fee with gas limit, redirects to protocol wallet if transfer fails
    /// @param referrer Referrer address
    /// @param amount Amount in wei
    /// @param seller The user whose sale generated the referral fee
    /// @return success Whether the transfer to the referrer succeeded
    function _transferReferralFee(
        address referrer,
        uint256 amount,
        address seller
    ) internal returns (bool success) {
        uint256 gasLimit = _getGasLimitFor(referrer);
        (success, ) = payable(referrer).call{value: amount, gas: gasLimit}("");

        if (!success) {
            // Redirect to protocol wallet
            (bool protocolSuccess, ) = payable(protocolWallet).call{value: amount}("");
            require(protocolSuccess, "Protocol fallback failed");
            emit ReferralFeeRedirectedToProtocol(referrer, seller, amount);
        }
    }

    /// @notice Pays a creator fee directly if a wallet is registered, else accrues it on-chain.
    /// @dev Gas-capped send using the per-recipient configurable limit (customGasLimit /
    ///      defaultTransferGasLimit, same system as referral and prize transfers); on failure
    ///      falls back to accrual so a bad wallet can never block sells.
    function _payOrAccrueCreatorFee(uint256 playerId, uint256 amount) internal {
        address wallet = creatorWallet[playerId];
        if (wallet != address(0)) {
            (bool ok, ) = payable(wallet).call{value: amount, gas: _getGasLimitFor(wallet)}("");
            if (ok) {
                emit CreatorFeePaid(playerId, wallet, amount);
                return;
            }
        }
        accruedCreatorFeesWei[playerId] += amount;
        totalAccruedCreatorFeesWei += amount;
        emit CreatorFeeAccrued(playerId, amount);
    }

    /// @notice Transfers prize with gas limit, refunds sender if transfer fails
    /// @param winner Winner address
    /// @param amount Amount in wei
    /// @param description Prize description for event
    /// @return success Whether the transfer succeeded
    function _transferPrize(
        address winner,
        uint256 amount,
        string calldata description
    ) internal returns (bool success) {
        uint256 gasLimit = _getGasLimitFor(winner);
        (success, ) = payable(winner).call{value: amount, gas: gasLimit}("");

        if (!success) {
            // Refund to sender (prize manager)
            (bool refundSuccess, ) = payable(msg.sender).call{value: amount}("");
            require(refundSuccess, "Prize refund failed");
            emit PrizeTransferFailed(winner, amount, description);
        }
    }

    ////////////////////////////////////////////////////////////////////
    // Utility functions
    ////////////////////////////////////////////////////////////////////
    /// @notice Gets a user's share balance for a player in units
    /// @param user The user address
    /// @param playerId The player ID
    /// @return The share balance in 18-decimal units
    function getUserPlayerHoldingInUnits(
        address user,
        uint256 playerId
    ) public view playerExists(playerId) returns (uint256) {
        return sharesBalance[playerId][user];
    }

    /// @notice Gets a user's share balance for a player in full shares
    /// @param user The user address
    /// @param playerId The player ID
    /// @return The share balance in full shares (units / 1e18)
    function getUserPlayerHoldingInFullShares(
        address user,
        uint256 playerId
    ) public view playerExists(playerId) returns (uint256) {
        return sharesBalance[playerId][user] / ONE_FULL_SHARE_IN_UNITS; // Convert to user-friendly units (18 decimals to whole shares)
    }

    /// @notice Gets a user's share balance for a player in lots
    /// @param user The user address
    /// @param playerId The player ID
    /// @return The share balance in lots
    function getUserPlayerHoldingInLots(
        address user,
        uint256 playerId
    ) public view playerExists(playerId) returns (uint256) {
        return sharesBalance[playerId][user] / LOT_SIZE_UNITS; // Return in lots
    }

    /// @notice Gets players with pagination
    /// @param offset The starting index
    /// @param limit The maximum number of players to return
    /// @return ids Array of player IDs
    /// @return names Array of player names
    /// @return tradingEnableds Array of trading enabled flags
    function getAllPlayers(
        uint256 offset,
        uint256 limit
    )
        public
        view
        returns (
            uint256[] memory ids,
            string[] memory names,
            bool[] memory tradingEnableds
        )
    {
        uint256 total = nextPlayerId;
        if (offset >= total || limit == 0) {
            return (new uint256[](0), new string[](0), new bool[](0));
        }
        uint256 end = offset + limit;
        if (end > total) {
            end = total;
        }
        uint256 count = end - offset;
        ids = new uint256[](count);
        names = new string[](count);
        tradingEnableds = new bool[](count);
        for (uint256 i = 0; i < count; i++) {
            uint256 playerId = offset + i;
            Player storage p = players[playerId];
            ids[i] = playerId;
            names[i] = p.name;
            tradingEnableds[i] = p.tradingEnabled;
        }
        return (ids, names, tradingEnableds);
    }

    /// @notice Checks if IPO prize fee is currently active for a player
    /// @param playerId The player ID
    /// @return True if within IPO fee window, false otherwise
    function isIpoPrizeFeeActive(
        uint256 playerId
    ) public view playerExists(playerId) returns (bool) {
        return
            block.timestamp >= players[playerId].ipoWindowStartTimestamp &&
            block.timestamp <= players[playerId].ipoWindowEndTimestamp;
    }

    /// @notice Gets the end time of IPO prize fee window for a player
    /// @param playerId The player ID
    /// @return The timestamp when IPO fee window ends
    function getIpoPrizeFeeEndTime(
        uint256 playerId
    ) public view playerExists(playerId) returns (uint256) {
        return players[playerId].ipoWindowEndTimestamp;
    }

    /// @notice Gets a user's portfolio holdings in units with pagination
    /// @param user The user address
    /// @param offset The starting index (in terms of holdings found, not player IDs)
    /// @param limit The maximum number of holdings to return
    /// @return playerIds Array of player IDs where user has holdings
    /// @return quantities Array of quantities in units (18 decimals)
    function getPortfolioHoldingsInUnits(
        address user,
        uint256 offset,
        uint256 limit
    )
        public
        view
        returns (uint256[] memory playerIds, uint256[] memory quantities)
    {
        if (limit == 0) {
            return (new uint256[](0), new uint256[](0));
        }
        // Single pass: skip `offset` holdings, then collect up to `limit`
        playerIds = new uint256[](limit);
        quantities = new uint256[](limit);
        uint256 found = 0;
        uint256 added = 0;
        for (uint256 i = 0; i < nextPlayerId && added < limit; i++) {
            uint256 balance = sharesBalance[i][user];
            if (balance > 0) {
                if (found >= offset) {
                    playerIds[added] = i;
                    quantities[added] = balance;
                    added++;
                }
                found++;
            }
        }
        // Trim arrays if we found fewer than limit
        if (added < limit) {
            assembly {
                mstore(playerIds, added)
                mstore(quantities, added)
            }
        }
        return (playerIds, quantities);
    }

    /// @notice Gets a user's portfolio holdings in lots with pagination
    /// @param user The user address
    /// @param offset The starting index (in terms of holdings found, not player IDs)
    /// @param limit The maximum number of holdings to return
    /// @return playerIds Array of player IDs where user has holdings
    /// @return quantities Array of quantities in lots
    function getPortfolioHoldingsInLots(
        address user,
        uint256 offset,
        uint256 limit
    )
        public
        view
        returns (uint256[] memory playerIds, uint256[] memory quantities)
    {
        if (limit == 0) {
            return (new uint256[](0), new uint256[](0));
        }
        // Single pass: skip `offset` holdings, then collect up to `limit`
        playerIds = new uint256[](limit);
        quantities = new uint256[](limit);
        uint256 found = 0;
        uint256 added = 0;
        for (uint256 i = 0; i < nextPlayerId && added < limit; i++) {
            uint256 balance = sharesBalance[i][user];
            if (balance > 0) {
                if (found >= offset) {
                    playerIds[added] = i;
                    quantities[added] = balance / LOT_SIZE_UNITS;
                    added++;
                }
                found++;
            }
        }
        // Trim arrays if we found fewer than limit
        if (added < limit) {
            assembly {
                mstore(playerIds, added)
                mstore(quantities, added)
            }
        }
        return (playerIds, quantities);
    }

    /// @notice Gets a user's fractional remainders with pagination
    /// @param user The user address
    /// @param offset The starting index (in terms of holdings with remainders found, not player IDs)
    /// @param limit The maximum number of holdings to return
    /// @return playerIds Array of player IDs where user has fractional remainders
    /// @return remainders Array of fractional remainder amounts in units
    function getPortfolioFractionalRemainders(
        address user,
        uint256 offset,
        uint256 limit
    )
        public
        view
        returns (uint256[] memory playerIds, uint256[] memory remainders)
    {
        if (limit == 0) {
            return (new uint256[](0), new uint256[](0));
        }
        // Single pass: skip `offset` holdings with remainders, then collect up to `limit`
        playerIds = new uint256[](limit);
        remainders = new uint256[](limit);
        uint256 found = 0;
        uint256 added = 0;
        for (uint256 i = 0; i < nextPlayerId && added < limit; i++) {
            uint256 remainder = sharesBalance[i][user] % LOT_SIZE_UNITS;
            if (remainder > 0) {
                if (found >= offset) {
                    playerIds[added] = i;
                    remainders[added] = remainder;
                    added++;
                }
                found++;
            }
        }
        // Trim arrays if we found fewer than limit
        if (added < limit) {
            assembly {
                mstore(playerIds, added)
                mstore(remainders, added)
            }
        }
        return (playerIds, remainders);
    }

    /// @notice Gets the fractional remainder for a user's balance that doesn't align with LOT_SIZE_UNITS
    /// @param user The user address
    /// @param playerId The player ID
    /// @return remainder The non-lot-aligned remainder in units
    /// @return estimatedGrossPayout Estimated gross payout before fees
    /// @return estimatedNetPayout Estimated net payout after fees
    function getFractionalRemainder(
        address user,
        uint256 playerId
    ) external view playerExists(playerId) returns (
        uint256 remainder,
        uint256 estimatedGrossPayout,
        uint256 estimatedNetPayout
    ) {
        uint256 balance = sharesBalance[playerId][user];
        remainder = balance % LOT_SIZE_UNITS;

        if (remainder > 0 && sharesSupply[playerId] >= remainder) {
            estimatedGrossPayout = calculateGrossSellPayoutByUnits(playerId, remainder);
            uint256 totalFees = (estimatedGrossPayout * COMMISSION_BPS) / BPS;
            estimatedNetPayout = estimatedGrossPayout - totalFees;
        }
    }

    ////////////////////////////////////////////////////////////////////
    // Storage Cleanup - Functions
    ////////////////////////////////////////////////////////////////////

    /// @notice Cleans up sharesBalance storage slots where balance is zero
    /// @dev Idempotent - safe to call multiple times on same targets.
    ///      Off-chain indexers should deduplicate events by [playerId, user].
    ///      This function cannot distinguish between:
    ///      - Ghost data (user traded, now has 0)
    ///      - Already cleaned slots
    ///      - Never-traded slots
    ///      All three cases will emit events. Deduplication must happen off-chain.
    ///      Invalid player IDs are skipped rather than causing a revert.
    /// @param targets Array of [playerId, user] pairs to clean up
    /// @return processed Number of zero-balance targets processed
    /// @return skippedInvalidPlayer Number skipped because player doesn't exist
    /// @return skippedNonZeroBalance Number skipped because balance is not zero
    function batchCleanupZeroBalances(
        CleanupTarget[] calldata targets
    ) external onlyStorageCleaner returns (
        uint256 processed,
        uint256 skippedInvalidPlayer,
        uint256 skippedNonZeroBalance
    ) {
        require(targets.length > 0, "Empty targets array");

        for (uint256 i = 0; i < targets.length; i++) {
            uint256 playerId = targets[i].playerId;
            address user = targets[i].user;

            // Skip if player doesn't exist
            if (playerId >= nextPlayerId) {
                skippedInvalidPlayer++;
                continue;
            }

            // Skip if balance is not zero (user has active holding)
            if (sharesBalance[playerId][user] != 0) {
                skippedNonZeroBalance++;
                continue;
            }

            // Delete the storage slot
            delete sharesBalance[playerId][user];

            emit ZeroBalanceCleaned(playerId, user);
            processed++;
        }

        emit BatchCleanupCompleted("ZeroBalances", processed);
        return (processed, skippedInvalidPlayer, skippedNonZeroBalance);
    }

    /// @notice Cleans up IPO tracking data for completed IPOs
    /// @dev Only processes slots where:
    ///      - Player exists
    ///      - IPO has ended (ipoWindowEndTimestamp > 0 && block.timestamp > ipoWindowEndTimestamp)
    ///      - At least one of lotsUsed or tradesUsed is non-zero
    ///      This function IS properly idempotent - already-cleaned slots are skipped.
    ///      Invalid player IDs are skipped rather than causing a revert.
    /// @param targets Array of [playerId, user] pairs to clean up
    /// @return processed Number of slots successfully cleaned
    /// @return skippedInvalidPlayer Number skipped because player doesn't exist
    /// @return skippedActiveIpo Number skipped because IPO still active or not started
    /// @return skippedAlreadyClean Number skipped because already zero
    function batchCleanupIpoTracking(
        CleanupTarget[] calldata targets
    ) external onlyStorageCleaner returns (
        uint256 processed,
        uint256 skippedInvalidPlayer,
        uint256 skippedActiveIpo,
        uint256 skippedAlreadyClean
    ) {
        require(targets.length > 0, "Empty targets array");

        for (uint256 i = 0; i < targets.length; i++) {
            uint256 playerId = targets[i].playerId;
            address user = targets[i].user;

            // Skip if player doesn't exist
            if (playerId >= nextPlayerId) {
                skippedInvalidPlayer++;
                continue;
            }

            // Skip if IPO hasn't started or is still active
            uint256 ipoEnd = players[playerId].ipoWindowEndTimestamp;
            if (ipoEnd == 0 || block.timestamp <= ipoEnd) {
                skippedActiveIpo++;
                continue;
            }

            // Read current values
            uint256 lotsUsed = _ipoLotsUsed[playerId][user];
            uint256 tradesUsed = _ipoTradesUsed[playerId][user];

            // Skip if both values are already zero (nothing to clean)
            if (lotsUsed == 0 && tradesUsed == 0) {
                skippedAlreadyClean++;
                continue;
            }

            // Delete the storage slots
            delete _ipoLotsUsed[playerId][user];
            delete _ipoTradesUsed[playerId][user];

            emit IpoTrackingCleaned(playerId, user, lotsUsed, tradesUsed);
            processed++;
        }

        emit BatchCleanupCompleted("IpoTracking", processed);
        return (processed, skippedInvalidPlayer, skippedActiveIpo, skippedAlreadyClean);
    }

    ////////////////////////////////////////////////////////////////////
    // Internal helper functions
    ////////////////////////////////////////////////////////////////////
    function _emitUserSharesChanged(
        address user,
        uint256 playerId,
        int256 amountChange,
        uint256 totalCost,
        uint256 totalFees,
        string memory reason
    ) internal {
        uint256 netAmount = 0;
        require(amountChange != 0, "Amount change cannot be zero");
        if (amountChange != 0) {
            netAmount = amountChange > 0 ? totalCost : totalCost - totalFees;
        }
        emit UserSharesChanged(
            user,
            playerId,
            amountChange,
            sharesBalance[playerId][user],
            totalCost,
            totalFees,
            netAmount,
            reason
        );
    }

    function _emitTransferSharesChanged(
        address from,
        address to,
        uint256 playerId,
        uint256 amount,
        string memory reason
    ) internal {
        _emitUserSharesChanged(from, playerId, -int256(amount), 0, 0, reason);
        _emitUserSharesChanged(to, playerId, int256(amount), 0, 0, reason);
    }

    function _emitPlayerSupplyChanged(
        uint256 playerId,
        int256 supplyChange,
        string memory reason
    ) internal {
        uint256 s = sharesSupply[playerId];
        uint256 currentPrice = s > 0
            ? Math.mulDiv(
                _square(s),
                1 ether,
                BONDING_CURVE_DENOMINATOR * ONE_FULL_SHARE_IN_UNITS2
            )
            : 0;
        uint256 marketCap = Math.mulDiv(
            currentPrice,
            s,
            ONE_FULL_SHARE_IN_UNITS
        ); // exact with fractions
        emit PlayerSharesSupplyChanged(
            playerId,
            supplyChange,
            s,
            currentPrice,
            marketCap,
            reason
        );
    }

    /// @notice Disables the renounceOwnership function to prevent accidental ownership loss
    function renounceOwnership() public override onlyOwner {
        revert("renounceOwnership is disabled");
    }
}
Chain explorer3983msChain node147ms