// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @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);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
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` to `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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "../interfaces/utils/IAccessHandler.sol";
import "./BaseInitializer.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
/**
* @title Access Handler
* @author BetBase Dev Team
* @notice An access control contract. It restricts access to otherwise public
* methods, by checking for assigned roles. its meant to be extended
* and holds all the predefined role type for the derrived contracts.
* @notice This is a util contract for the BookieMain app.
*/
abstract contract AccessHandler is IAccessHandler, BaseInitializer, AccessControl, Pausable {
/**
* @notice Simple constructor, just sets the admin.
* Allows for AccessHandler to be inherited by non-upgradeable contracts
* that are normally deployed, with a contructor call.
*/
constructor() {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(OPERATION_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
}
/**
* @notice Adds another admin.
* @param newAdmin is the addresse of the new admin.
*/
function addAdmin(address newAdmin) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
}
/**
* @notice Removes an admin.
* @param inAdmin is the addresse of the admin to remove.
*/
function removeAdmin(address inAdmin) external override onlyRole(DEFAULT_ADMIN_ROLE) {
// We want at least 1 admin, so admins cannot renounce their own role.
if (inAdmin != _msgSender())
_revokeRole(DEFAULT_ADMIN_ROLE, inAdmin);
}
/**
* @notice Puts the contract in pause state, for emergency control.
*/
function pause() external override onlyRole(PAUSER_ROLE) {
_pause();
}
/**
* @notice Puts the contract in operational state, after being paused.
*/
function unpause() external override onlyRole(PAUSER_ROLE) {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
abstract contract BaseInitializer is Initializable {
/**
* Error for call to a contract that is not yet initialized.
*/
error NotInitialized();
/**
* Error for call to a contract that is already initialized.
*/
error AlreadyInitialized();
/**
* @notice Throws if this contract has not been initialized.
*/
modifier isInitialized() {
if (!getInitialized()) {
revert NotInitialized();
}
_;
}
/**
* @notice Initialize and remember this state to avoid repeating.
*/
function initialize() internal virtual initializer {}
/**
* @notice Get the state of initialization.
* @return bool true if initialized.
*/
function getInitialized() internal view returns (bool) {
return _getInitializedVersion() != 0 && !_isInitializing();
}
/**
* @notice Get the state of initialization.
* @return bool true if initialized.
*/
function getInitializedVersion() external view returns (uint64) {
return _getInitializedVersion();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
// For debugging only
/**
* @title BetData
* @author BetBase Dev Team
* @notice Central definition for what a bet is with utilities to make/check etc.
*/
library BetData {
uint256 internal constant ODDS_PRECISION = 1e10;
uint256 private constant MAX_ODDS = 1e3;
struct Bet {
bytes32 marketHash;
address token;
uint256 amount;
uint256 decimalOdds;
uint256 expiry;
address owner;
}
struct BetSettleResult {
address better;
address tokenAdd;
uint256 paidToBetter;
uint256 paidToLP;
uint256 paidToFee;
}
/**
* @notice Error for Invaid bet.
* @param reason is the reason of the error.
* @param bet is the bet details.
*/
error InvalidBet(string reason, Bet bet);
/**
* @notice Checks the parameters of a bet to see if they are valid.
* @notice Throws an error if the check does not validate.
* @param bet The bet to check.
*/
function checkParamValidity(Bet memory bet) internal view {
if (bet.amount == 0)
revert InvalidBet({reason: "BET_AMOUNT_ZERO", bet: bet});
if (bet.decimalOdds <= ODDS_PRECISION || bet.decimalOdds > ODDS_PRECISION * MAX_ODDS)
revert InvalidBet({reason: "INVALID_DECIMAL_ODDS", bet: bet});
if (bet.expiry < block.timestamp)
revert InvalidBet({reason: "BET_EXPIRED", bet: bet});
if (bet.token == address(0))
revert InvalidBet({reason: "INVALID_TOKEN", bet: bet});
}
/**
* @notice Computes the hash of a bet. Packs the arguments in order
* of the Bet struct.
* @param bet The Bet to compute the hash of.
* @return bytes32 The calculated hash of of the bet.
*/
function getBetHash(Bet memory bet) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
bet.marketHash,
bet.token,
bet.amount,
bet.decimalOdds,
bet.expiry,
bet.owner
)
);
}
/**
* @notice Logs the content of a bet to the Hardhat console log.
* @param bet The Bet to log the content of.
*/
function logBet(Bet storage bet) internal view {
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "./interfaces/IBookieMain.sol";
import "./utils/AccessHandler.sol";
import "./libs/BetData.sol";
import "./libs/TokenAmountValidator.sol";
// For debugging only
/**
* @title Bookie Main contract
* @author BetBase Dev Team
* @notice This is the main contract for the app: BookieMain.
* @notice Multi contract app taking bets and locking tokens until bets settle.
* @notice Token bets are matched from a liquidity pool (LP) of same token type.
* @notice The LP holds tokens of a certain type, and issues LP tokens as
* proof of deposit.
* @notice It has a simple node.js react app for easy interfacing.
* @notice Accesshandler is Initializable.
*/
contract BookieMain is IBookieMain, AccessHandler {
using BetData for BetData.Bet;
using TokenAmountValidator for address;
IBetHelper private lp;
IBetHistory private betHistory;
IMarketHistory private marketHistory;
IBonusDistribution private bonusHandler;
ITokenTransferProxy private tokenTransferProxy; // Just used as an address
constructor() AccessHandler() {}
/**
* @notice Initializes this contract with reference to other contracts.
* @param inLP The Liquidity Pool contract address, for matching bets.
* @param inBetHistory The bet history contract address for storing bets.
* @param inMarketHistory The market history contract address.
* @param inTokenTransferProxy The TokenTransferProxy contract address.
*/
function init(
IBetHelper inLP,
IBetHistory inBetHistory,
IMarketHistory inMarketHistory,
ITokenTransferProxy inTokenTransferProxy
) external onlyRole(DEFAULT_ADMIN_ROLE) {
lp = inLP;
betHistory = inBetHistory;
marketHistory = inMarketHistory;
tokenTransferProxy = inTokenTransferProxy;
BaseInitializer.initialize();
}
/**
* @notice Setter to change the referenced LiquidityPool contract.
* @param inLP The Liquidity Pool contract, to match bets.
*/
function setLiquidityPool(IBetHelper inLP) external onlyRole(OPERATION_ADMIN_ROLE) {
lp = inLP;
}
/**
* @notice Setter to change the referenced BetHistory contract.
* @param inBetHistory The bet history contract for storing bets.
*/
function setBetHistory(IBetHistory inBetHistory) external onlyRole(OPERATION_ADMIN_ROLE) {
betHistory = inBetHistory;
}
/**
* @notice Setter to change the referenced MarketHistory contract.
* @param inMarketHistory The market history contract address.
*/
function setMarketHistory(
IMarketHistory inMarketHistory
) external onlyRole(OPERATION_ADMIN_ROLE) {
marketHistory = inMarketHistory;
}
/**
* @notice Setter to change the referenced BonusDistribution contract.
* @param inBonusDistribution The bonus handler contract address.
*/
function setBonusDistribution(
IBonusDistribution inBonusDistribution
) external onlyRole(OPERATION_ADMIN_ROLE) {
bonusHandler = inBonusDistribution;
}
/**
* @notice Setter to change the referenced TokenTransferProxy contract.
* @param inTokenTransferProxy The TokenTransferProxy contract address.
*/
function setTokenTransferProxy(
ITokenTransferProxy inTokenTransferProxy
) external onlyRole(OPERATION_ADMIN_ROLE) {
tokenTransferProxy = inTokenTransferProxy;
}
/**
* @notice Check bet data and signature against a stored signer account.
* Create the bet if it validates.
* @param token The token type to bet.
* @param amount The amount to bet.
* @param odds The odds of the bet in decimal notation.
* @param expiry The epoch representation of expiry time of the request.
* @param marketHash Is the market hash to identify the market.
* @param signature The signature to compare to the signer.
*/
function makeBet(
address token,
uint256 amount,
uint256 odds,
uint256 expiry,
bytes32 marketHash,
bytes calldata signature
) external override isInitialized whenNotPaused {
address better = msg.sender;
BetData.Bet memory bet = BetData.Bet({
marketHash: marketHash,
token: token,
amount: amount,
decimalOdds: odds,
expiry: expiry,
owner: better
});
bytes32 betHash = bet.getBetHash();
// string memory betHashStr = Strings.toHexString(uint256(betHash), 32);
bytes32 betDigest = MessageHashUtils.toEthSignedMessageHash(betHash);
address signer = ECDSA.recover(betDigest, signature);
if (!hasRole(SIGNER_ROLE, signer)) {
revert InvalidSignature({betHash: betHash});
}
createBet(bet);
}
/**
* @notice Creates the bet and locks the betters and the LPs tokens.
* @param bet is a struct that holds all the bet details
*/
function createBet(BetData.Bet memory bet) private {
bet.checkParamValidity();
bytes32 betHash = bet.getBetHash();
if (betHistory.getBetExists(betHash))
revert BetData.InvalidBet({reason: "BET_ALREADY_EXISTS", bet: bet});
// Make sure there is a valid market
if (marketHistory.getMarketState(bet.marketHash) == MarketState.Undefined)
marketHistory.addMarket(bet.marketHash);
else
marketHistory.assertMarketIsActive(bet.marketHash);
// Check balances
bet.owner.checkAllowanceAndBalance(bet.amount, bet.token, address(tokenTransferProxy));
uint256 liquidityBetBalance = lp.getLiquidityAvailableForBet(bet.token);
uint256 matchedAmount =
((bet.amount * bet.decimalOdds) / BetData.ODDS_PRECISION) - bet.amount;
if (liquidityBetBalance < matchedAmount) {
revert InsufficientLiquidityBalance({
available: liquidityBetBalance,
required: matchedAmount
});
}
//Now match, persist, transfer and token-lock the bet
betHistory.createBet(bet);
// Report the bet to the bonus handler
if (address(bonusHandler) != address(0))
bonusHandler.updateProgress(bet.owner, bet.amount);
emit BetWagered(
bet.owner,
betHash,
bet.marketHash,
bet.amount,
bet.token,
bet.decimalOdds
);
}
/**
* @notice Settle a bet and pay the pot to the winner or to our LP
* @param betHash The key/hash of the bet settle.
*/
function settleBet(bytes32 betHash) external override whenNotPaused {
BetData.BetSettleResult memory res = betHistory.settleBet(betHash);
if (res.paidToBetter == 0 && res.paidToLP == 0) {
emit BetNothingToSettle(res.better, betHash);
return;
}
emit BetSettled(res.better, betHash, res.tokenAdd, res.paidToBetter);
}
/**
* @notice Let the admin of this contract cancel an active bet
* @param betHash The key/hash of the bet cancel.
*/
function cancelBetAsAdmin(bytes32 betHash) external override onlyRole(CANCEL_ROLE) {
BetData.BetSettleResult memory res = betHistory.cancelBet(betHash);
if (res.paidToBetter == 0 && res.paidToLP == 0) {
emit BetNothingToCancel(res.better, betHash);
return;
}
emit BetCanceled(res.better, betHash, res.tokenAdd, res.paidToBetter);
}
}
// SPDX-License-Identifier: MIT
// 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 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 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 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 signaling 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, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
bytes32 constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes32 constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
bytes32 constant BETTER_ROLE = keccak256("BETTER_ROLE");
bytes32 constant CANCEL_ROLE = keccak256("CANCEL_ROLE");
bytes32 constant LOCKBOX_ROLE = keccak256("LOCKBOX_ROLE");
bytes32 constant REPORTER_ROLE = keccak256("REPORTER_ROLE");
bytes32 constant ADD_ROLE = keccak256("ADD_ROLE");
bytes32 constant REWARDER_ROLE = keccak256("REWARDER_ROLE");
bytes32 constant REWARD_ADMIN_ROLE = keccak256("REWARD_ADMIN_ROLE");
bytes32 constant OPERATION_ADMIN_ROLE = keccak256("OPERATION_ADMIN_ROLE");
bytes32 constant SIGNER_ROLE = keccak256("SIGNER_ROLE");
bytes32 constant TOKEN_ROLE = keccak256("TOKEN_ROLE");
bytes32 constant BONUS_REPORTER_ROLE = keccak256("BONUS_REPORTER_ROLE");
bytes32 constant BONUS_CONTROLLER_ROLE = keccak256("BONUS_CONTROLLER_ROLE");
bytes32 constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 constant VETO_ROLE = keccak256("VETO_ROLE");
interface IAccessHandler {
function addAdmin(address) external;
function removeAdmin(address) external;
function pause() external;
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
interface IBetHelper {
function matchBet(address, uint256) external;
function setLpBetPercent(uint8) external;
function getLiquidityAvailableForBet(address) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "./IMarketHistory.sol";
import "./utils/ILockBox.sol";
import "./utils/IFeeHandler.sol";
import "./utils/IBetHelper.sol";
import "../libs/BetData.sol";
interface IBetHistory is IFeeHandler {
function allBets(
bytes32
) external view returns (bytes32, address, uint256, uint256, uint256, address);
function unsettledPots(bytes32) external view returns (uint256);
function marketBetted(bytes32, address) external view returns (uint256);
function marketMatched(bytes32, address) external view returns (uint256);
function setLiquidityPool(IBetHelper) external;
function setBetLockBox(ILockBox) external;
function setMarketHistory(IMarketHistory) external;
function createBet(BetData.Bet calldata) external;
function settleBet(bytes32) external returns (BetData.BetSettleResult memory);
function cancelBet(bytes32) external returns (BetData.BetSettleResult memory);
function getBetExists(bytes32) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "../utils/ITokenTransferProxy.sol";
interface IBonusDistribution {
enum BonusState {Undefined, Pending, Active, Completed, Released} // Enum
struct BonusPortion {
uint8 id;
BonusState state;
address tokenAdd;
uint256 amount;
uint256 released;
uint256 progress;
uint256 progressTarget;
}
struct CombinedBonusData {
uint8 numPortions;
uint8 currentPortion;
uint256 claimedBonus;
uint256 addedBonus;
uint256 releasedBonus;
BonusPortion[] portions;
}
struct UserBonusData {
uint256 progress;
uint256 availableBonus;
}
/**
* @notice Event fires when bonus is claimed, including 0 claims.
* @param owner is the owner of the bonus/claim.
* @param token is the token contract address.
* @param amount is the token amount claimed.
*/
event BonusClaimed(address indexed owner, address token, uint256 amount);
/**
* @notice Event fires when bonus progress is increased.
* @param id is the id of the portion.
* @param account is the provider of the progress (future bonus recipient).
* @param amount is the new progress increase.
*/
event BonusProgress(uint8 indexed id, address indexed account, uint256 amount);
/**
* @notice Event fires when portion changes state.
* @param id is the id of the portion changing.
* @param state is the new state of the portion.
*/
event BonusPortionState(uint8 indexed id, BonusState state);
/**
* @notice Event fires when portion reaches the target progress.
* @param id is the id of the portion completed.
* @param progress is the progress reached.
*/
event BonusPortionCompleted(uint8 indexed id, uint256 progress);
/**
* @notice Event fires when a part of a portion is released.
* @param id is the id of the portion affected.
* @param token is the bonus token contract address.
* @param amount is the bonus token amount released.
* @param recipients is the number of bonus recipients.
*/
event BonusReleased(uint8 indexed id, address token, uint256 amount, uint256 recipients);
/**
* Error invalid bonus portion input.
*/
error InvalidBonusPortion(string reason);
/**
* Error invalid state change.
*/
error InvalidState(uint8 id, BonusState oldState, BonusState requestedState);
/**
* Error not enough bonus available for release.
*/
error InsufficientBonus(uint8 id, uint256 required, uint256 available);
function addPortion(uint8 id, address tokenAdd, uint256 amount, uint256 target) external;
function claimBonus(address tokenAdd) external;
function updateProgress(address inAccount, uint256 inNewProgress) external;
function releaseBonus(address[] calldata inRecipients) external;
function setPortionState(uint8 inId, BonusState inState) external;
function getPortion(uint8 id) external view returns (BonusPortion memory);
function getCombinedData(address tokenAdd) external view returns (CombinedBonusData memory);
function getUserData(
address inAccount,
address tokenAdd
) external view returns (UserBonusData memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "./utils/IBetHelper.sol";
import "./IBetHistory.sol";
import "./IMarketHistory.sol";
import "./utils/IBonusDistribution.sol";
import "./utils/ITokenTransferProxy.sol";
interface IBookieMain {
/**
* @notice Event that fires when a bet is accepted.
* @param better is the address that made the bet.
* @param betHash is calculated hash of the bet data.
* @param marketHash is the hash of the market betted.
* @param amount is the betters amount wagered.
* @param token is the token contract address.
* @param decimalOdds is the odds of the bet in decimal format.
*/
event BetWagered(
address indexed better,
bytes32 indexed betHash,
bytes32 indexed marketHash,
uint256 amount,
address token,
uint256 decimalOdds
);
/**
* @notice Event that fires when a bet is decided/settled.
* @param better is the address that won the bet.
* @param betHash is calculated hash of the bet data.
* @param token is the token contract address
* @param paid is the prize paid out (0 if its a loss).
*/
event BetSettled(address indexed better, bytes32 indexed betHash, address token, uint256 paid);
/**
* @notice Event that fires when a bet is canceled.
* Can be due to a canceled market or an admin action.
* @param better is the address made the bet.
* @param betHash is calculated hash of the bet data.
* @param token is the token contract address
* @param paid is the amount paid back.
*/
event BetCanceled(
address indexed better,
bytes32 indexed betHash,
address token,
uint256 paid
);
/**
* @notice Event fires when there is no bet to settle.
* @param better is the owner of the bet.
* @param betHash is calculated hash of the bet data.
*/
event BetNothingToSettle(address indexed better, bytes32 indexed betHash);
/**
* @notice Event fires there is no bet to cancel
* @param better is the owner of the bet.
* @param betHash is calculated hash of the bet data.
*/
event BetNothingToCancel(address indexed better, bytes32 indexed betHash);
/**
* @notice Error for Insufficient liquidity to match a bet.
* Needed `required` but only `available` available.
* @param available balance available.
* @param required requested amount to transfer.
*/
error InsufficientLiquidityBalance(uint256 available, uint256 required);
/**
* @notice Error for a non matching signature.
* @param betHash is the calculated hash of the bet details.
*/
error InvalidSignature(bytes32 betHash);
function setLiquidityPool(IBetHelper) external;
function setBetHistory(IBetHistory) external;
function setMarketHistory(IMarketHistory) external;
function setBonusDistribution(IBonusDistribution) external;
function setTokenTransferProxy(ITokenTransferProxy) external;
function makeBet(address, uint256, uint256, uint256, bytes32, bytes calldata) external;
function settleBet(bytes32) external;
function cancelBetAsAdmin(bytes32) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* 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[EIP 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "./ITokenTransferProxy.sol";
interface IFeeHandler {
struct FeeReceiver {
address receiverAdd;
uint8 feePercent;
bool isRewardHandler;
}
/**
* @notice Event fires when fees are set.
* @param feePermille is the fee permille to charge.
* @param feeSplit is the fee split percentages.
*/
event FeesSet(uint8 feePermille, uint8[4] feeSplit);
/**
* @notice Event fires when fees are set.
* @param id is the id (1-4) of the receiver.
* @param receiver is the new address.
*/
event FeesReceiverSet(uint8 id, address receiver);
/**
* @notice Event fires when fees are set.
* @param id is the id (1-4) of the receiver.
* @param isRewardHandler is true if the receiver is a RewardHandler contract.
*/
event FeesIsRewardHandlerSet(uint8 id, bool isRewardHandler);
/**
* @notice Error is thrown when invalid fees are set.
* @param feePermille is the fee permille to charge.
* @param receivers is the full receiver list.
*/
error InvalidFees(uint8 feePermille, FeeReceiver[4] receivers);
/**
* @notice Error is thrown when fees are assigned to address 0.
* @param id is the id of the receiver (1-4).
*/
error InvalidFeeReceiver(uint8 id);
function setFeeReceiverAddress(uint8, address) external;
function setIsRewardHandler(uint8, bool) external;
function setTokenTransferProxy(ITokenTransferProxy) external;
function setFees(uint8, uint8[4] calldata) external;
function feePermille() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
interface ILockBox {
/**
* Event that fires when tokens are locked.
* @param owner is the address got the tokens locked.
* @param token is the token contract address
* @param lockedAmount is the amount locked.
*/
event TokensLocked(address indexed owner, address indexed token, uint256 lockedAmount);
/**
* Event that fires when tokens are unlocked.
* @param owner is the address got the tokens unlocked.
* @param token is the token contract address
* @param unlockedAmount is the amount unlocked.
*/
event TokensUnlocked(address indexed owner, address indexed token, uint256 unlockedAmount);
/**
* Error for token unlock failure,
* although balance should always be available.
* Needed `required` but only `available` available.
* @param owner is the address that want to unlock tokens.
* @param token is the token contract address.
* @param available balance available.
* @param required requested amount to unlock.
*/
error InsufficientLockedTokens(
address owner,
address token,
uint256 available,
uint256 required
);
function lockAmount(address, address, uint256) external;
function unlockAmount(address, address, uint256) external;
function unlockAmountTo(address, address, address, uint256) external;
function getLockedAmount(address, address) external view returns (uint256);
function hasLockedAmount(address, address, uint256) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// State is all possible, only Completed has a defined outcome.
enum MarketState { Undefined, Active, Playing, Completed } // Enum
// Outcomes are defined as seen for better.
enum MarketOutcome { Undefined, Win, HalfWin, Void, HalfLoss, Loss, Cancel } // Enum
interface IMarketHistory {
/**
* @notice Event that fires when a market is added.
* @param marketHash is the hash used to identify the market.
*/
event MarketAdded(bytes32 indexed marketHash);
/**
* @notice Event that fires when a market is playing.
* @param marketHash is the hash used to identify the market.
*/
event MarketPlaying(bytes32 indexed marketHash);
/**
* @notice Event that fires when a market is settled.
* @param marketHash is the hash used to identify the market.
* @param outcome is the outcome of the market.
*/
event MarketSettled(bytes32 indexed marketHash, MarketOutcome outcome);
/**
* @notice Error when trying to add a market that already exists.
* @param marketHash is the hash of the existing market.
*/
error DuplicateMarket(bytes32 marketHash);
/**
* @notice Error when trying to access a market that has the wrong state.
* @param expected is the expected state of the requested market.
* @param current is the actual state of the requested market.
*/
error InvalidMarketState(MarketState expected, MarketState current);
function addMarket(bytes32 hash) external;
function setMarketPlaying(bytes32) external;
function settleMarket(bytes32, MarketOutcome) external;
function assertMarketIsActive(bytes32) external view;
function assertMarketIsCompleted(bytes32) external view;
function getMarketState(bytes32) external view returns (MarketState);
function isMarketOutcome(bytes32, MarketOutcome) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
interface ITokenTransferProxy {
function transferFrom(address, address, address, uint256) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return 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) {
// (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.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev 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 {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 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 prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, 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 {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
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^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// 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^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice 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) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @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 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @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 Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @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());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
enum TokenAvailability {
InsufficientBalance,
InsufficientAllowance,
OK
}
/**
* @title TokenAmountValidator
* @author BetBase Dev Team
* @notice Lib to help with checking token balances, allowance etc.
*/
library TokenAmountValidator {
/**
* Error for Insufficient token balance for an operation.
* Needed `required` but only `available` available.
* @param owner is the address that owns the tokens.
* @param tokenAdd is the token contract address.
* @param available balance available.
* @param required requested amount to transfer.
*/
error InsufficientBalance(
address owner,
address tokenAdd,
uint256 available,
uint256 required
);
/**
* Error for Insufficient token allowance for an operation.
* Needed `required` but only `available` available.
* @param owner is the address that owns the tokens.
* @param receiver is the address to receive the allowance.
* @param tokenAdd is the token contract address.
* @param available allowance available.
* @param required required amount.
*/
error InsufficientAllowance(
address owner,
address receiver,
address tokenAdd,
uint256 available,
uint256 required
);
/** @notice Checks an address balance and allowance for a given amount.
* @param owner The owner of the token balance and allowance.
* @param amount Is amount to check for.
* @param tokenAddress The token to check the availability for.
* @param receiver The address to check allowance for.
*/
function checkAllowanceAndBalance(
address owner,
uint256 amount,
address tokenAddress,
address receiver
) internal view {
IERC20 token = IERC20(tokenAddress);
uint256 balance = token.allowance(owner, address(receiver));
if (balance < amount) {
revert InsufficientAllowance({
owner: owner,
receiver: receiver,
tokenAdd: tokenAddress,
available: balance,
required: amount
});
}
balance = token.balanceOf(owner);
if (balance < amount) {
revert InsufficientBalance({
owner: owner,
tokenAdd: tokenAddress,
available: balance,
required: amount
});
}
}
/** @notice Checks an address balance for a given amount.
* @param owner The owner of the token balance.
* @param amount Is amount to check for.
* @param tokenAddress The token to check the availability for.
*/
function checkBalance(address owner, uint256 amount, address tokenAddress) internal view {
IERC20 token = IERC20(tokenAddress);
uint256 balance = token.balanceOf(owner);
if (balance < amount) {
revert InsufficientBalance({
owner: owner,
tokenAdd: tokenAddress,
available: balance,
required: amount
});
}
}
}
{
"compilationTarget": {
"contracts/BookieMain.sol": "BookieMain"
},
"evmVersion": "cancun",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 10000
},
"remappings": [],
"viaIR": true
}
[{"inputs":[],"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":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"tokenAdd","type":"address"},{"internalType":"uint256","name":"available","type":"uint256"},{"internalType":"uint256","name":"required","type":"uint256"}],"name":"InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"tokenAdd","type":"address"},{"internalType":"uint256","name":"available","type":"uint256"},{"internalType":"uint256","name":"required","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[{"internalType":"uint256","name":"available","type":"uint256"},{"internalType":"uint256","name":"required","type":"uint256"}],"name":"InsufficientLiquidityBalance","type":"error"},{"inputs":[{"internalType":"string","name":"reason","type":"string"},{"components":[{"internalType":"bytes32","name":"marketHash","type":"bytes32"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"decimalOdds","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"address","name":"owner","type":"address"}],"internalType":"struct BetData.Bet","name":"bet","type":"tuple"}],"name":"InvalidBet","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[{"internalType":"bytes32","name":"betHash","type":"bytes32"}],"name":"InvalidSignature","type":"error"},{"inputs":[],"name":"NotInitialized","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"better","type":"address"},{"indexed":true,"internalType":"bytes32","name":"betHash","type":"bytes32"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"paid","type":"uint256"}],"name":"BetCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"better","type":"address"},{"indexed":true,"internalType":"bytes32","name":"betHash","type":"bytes32"}],"name":"BetNothingToCancel","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"better","type":"address"},{"indexed":true,"internalType":"bytes32","name":"betHash","type":"bytes32"}],"name":"BetNothingToSettle","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"better","type":"address"},{"indexed":true,"internalType":"bytes32","name":"betHash","type":"bytes32"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"paid","type":"uint256"}],"name":"BetSettled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"better","type":"address"},{"indexed":true,"internalType":"bytes32","name":"betHash","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"marketHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"decimalOdds","type":"uint256"}],"name":"BetWagered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","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":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newAdmin","type":"address"}],"name":"addAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"betHash","type":"bytes32"}],"name":"cancelBetAsAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getInitializedVersion","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"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":"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":"contract IBetHelper","name":"inLP","type":"address"},{"internalType":"contract IBetHistory","name":"inBetHistory","type":"address"},{"internalType":"contract IMarketHistory","name":"inMarketHistory","type":"address"},{"internalType":"contract ITokenTransferProxy","name":"inTokenTransferProxy","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"odds","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"bytes32","name":"marketHash","type":"bytes32"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"makeBet","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"inAdmin","type":"address"}],"name":"removeAdmin","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":"contract IBetHistory","name":"inBetHistory","type":"address"}],"name":"setBetHistory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IBonusDistribution","name":"inBonusDistribution","type":"address"}],"name":"setBonusDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IBetHelper","name":"inLP","type":"address"}],"name":"setLiquidityPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IMarketHistory","name":"inMarketHistory","type":"address"}],"name":"setMarketHistory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ITokenTransferProxy","name":"inTokenTransferProxy","type":"address"}],"name":"setTokenTransferProxy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"betHash","type":"bytes32"}],"name":"settleBet","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"}]