// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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 v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode 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 {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]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
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);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode 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 {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
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]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
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.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// 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);
}
// 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);
}
return (signer, RecoverError.NoError);
}
/**
* @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) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {IGameImplementation} from "../pvh/interfaces/IGameImplementation.sol";
import {IGamePlayer} from "../pvh/interfaces/IGame.sol";
import {IBank} from "../pvh/interfaces/IBank.sol";
import {IFreeBet} from "./interfaces/IFreeBet.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/// @title Freebet contract
/// @author Kinco_dev
/// @notice Extension contract enabling an affiliate to deposit/withdraw funds in order to distribute freebets (off-chain).
/// This is also the contract that players who have received freebets will have to call to play via wager function.
/// The contract is based on a trust system. Affiliates could create freebets without depositing funds, or withdrawing funds before all freebets are used.
/// @dev Only one freebet contract per chain (it means the freebet contract is common to all affiliates).
/// Rebasing tokens or transfer-fee tokens are not taken in charge.
contract FreeBet is Ownable, ReentrancyGuard, IFreeBet {
using SafeERC20 for IERC20;
using ECDSA for bytes32;
/// @notice Maps freebet ids to its data (id => freebet).
mapping(uint256 => FreeBet_) public freeBets;
/// @notice Affiliate's balances (affiliate => token => amount).
mapping(address => mapping(address => uint256)) public affiliateBalances;
/// @notice Maps token addresses to its balance (token => balance).
mapping(address => uint256) public totalAffiliateBalance;
/// @notice The account that signs the freebets and acts as the authority.
address public manager;
/// @notice Bank address that helps to authorize only Betswirl games to bet on
IBank public bank;
/// @notice Role associated to Games smart contracts.
bytes32 public constant GAME_ROLE = keccak256("GAME_ROLE");
/// @notice Initialize contract's state variables.
/// @param manager_ Address of the manager.
/// @param bank_ Address of the bank.
constructor(address manager_, address bank_) {
setManager(manager_);
setBank(bank_);
}
/// @notice Uses a freebet on a game.
/// @param game Address of the game.
/// @param input The encoded input data (eg. the face for cointoss game).
/// @param freeBetData Freebet data.
/// @param signature The encoded freebet data signed by the manager.
/// @param maxHouseEdge The maximum authorized house edge.
/// @return betId Bet ID.
/// @dev Only games which owns GAME_ROLE can be used to wager.
/// The chainId allows to avoid cross-chain replay attacks.
/// The freebetAddress allows to avoid re-deploy replay attacks.
/// If the ERC20 amount used in wagerAmountWithData is different from the initial freebet amount,
/// it means the max bet amount has been reached. In this case, the difference between the 2 amounts
/// is not decreased from the affiliate balance. However, it's not the case for gas token.
/// Overpaid VRF fees are not refunded to the user.
function wager(
address game,
bytes calldata input,
FreeBetData calldata freeBetData,
bytes memory signature,
uint16 maxHouseEdge
) external payable nonReentrant returns (uint256 betId) {
// Check signature
_verifySignature(freeBetData, signature);
uint256 amount = freeBetData.amount;
// Cannot put freeBetData.token, freeBetData.affiliate & freeBetData.token == address(0) in local variable because of stack too deep error.
// Check freebet data
if (freeBetData.chainId != _getChainId()) revert WrongChainId();
if (freeBetData.freebetAddress != address(this))
revert WrongFreebetAddress();
if (freeBetData.player != msg.sender) revert WagerDenied();
if (freeBetData.expiresAt <= block.timestamp) revert BetExpired();
if (freeBets[freeBetData.freeBetId].player != address(0))
revert BetAlreadyWagered();
if (!bank.hasRole(GAME_ROLE, game)) revert UnauthorizedGame();
if (
affiliateBalances[freeBetData.affiliate][freeBetData.token] < amount
) revert BalanceTooLow();
uint256 balanceBefore;
if (freeBetData.token != address(0)) {
balanceBefore = IERC20(freeBetData.token).balanceOf(address(this));
IERC20(freeBetData.token).forceApprove(game, amount);
}
betId = IGameImplementation(game).wagerWithData{
value: freeBetData.token == address(0)
? msg.value + amount
: msg.value
}(
input,
freeBetData.player,
freeBetData.affiliate,
IGamePlayer.BetData(
freeBetData.token,
amount,
1,
0,
0,
maxHouseEdge
)
);
// The real amount used could be not the same in the case where maxBetAmount has been reached
if (freeBetData.token != address(0)) {
amount =
balanceBefore -
IERC20(freeBetData.token).balanceOf(address(this));
// Put allowance to 0
if (amount != freeBetData.amount) {
IERC20(freeBetData.token).safeApprove(game, 0);
}
}
// Decrease balances
unchecked {
affiliateBalances[freeBetData.affiliate][
freeBetData.token
] -= amount;
totalAffiliateBalance[freeBetData.token] -= amount;
}
freeBets[freeBetData.freeBetId] = FreeBet_(
freeBetData.freeBetId,
msg.sender,
betId,
amount,
freeBetData.token,
game,
freeBetData.affiliate
);
emit PlaceFreeBet(
freeBetData.freeBetId,
freeBetData.player,
freeBetData.affiliate,
betId,
freeBetData.token,
amount,
game
);
}
/// @notice Update the manager address.
/// @param manager_ The new manager address.
function setManager(address manager_) public onlyOwner {
if (manager_ == address(0)) revert InvalidAddress();
address oldManager = manager;
manager = manager_;
emit ManagerSet(oldManager, manager_);
}
/// @notice Update the bank address.
/// @param bank_ The new bank address.
function setBank(address bank_) public onlyOwner {
if (bank_ == address(0)) revert InvalidAddress();
address oldBank = address(bank);
bank = IBank(bank_);
emit BankSet(oldBank, bank_);
}
/// @notice Deposit funds in the contract to allow players to wager with.
/// @param affiliate Address of the affiliate.
/// @param token Address of the token.
/// @param amount Amount of tokens.
function deposit(
address affiliate,
address token,
uint256 amount
) external payable nonReentrant {
if (token == address(0)) {
if (amount != msg.value) revert InvalidValue();
} else {
if (msg.value > 0) revert InvalidValue();
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
amount = balanceAfter - balanceBefore;
}
if (amount == 0) revert InvalidAmount();
unchecked {
affiliateBalances[affiliate][token] += amount;
totalAffiliateBalance[token] += amount;
}
emit Deposit(affiliate, token, amount);
}
/// @notice Withdraw affiliate funds of the contract.
/// @param token Address of the token.
/// @param amount Amount of tokens.
/// @param to Address of the destination.
function withdraw(
address token,
uint256 amount,
address to
) external nonReentrant {
if (to == address(0)) revert InvalidAddress();
address affiliate = msg.sender;
uint256 maxAmount = affiliateBalances[affiliate][token];
if (amount > maxAmount) amount = maxAmount;
if (amount == 0) revert BalanceTooLow();
unchecked {
affiliateBalances[affiliate][token] -= amount;
totalAffiliateBalance[token] -= amount;
}
if (token == address(0)) {
Address.sendValue(payable(to), amount);
} else {
IERC20(token).safeTransfer(to, amount);
}
emit Withdraw(affiliate, token, amount, to);
}
/// @notice Withdraw lost funds of the contract.
/// @param token Address of the token.
/// @param amount Amount of tokens.
/// @param to Address of the receiver.
/// @dev It allows to recover funds sent directly in the smart contract without using the deposit function.
function withdrawStuckFunds(
address token,
uint256 amount,
address to
) external onlyOwner nonReentrant {
if (to == address(0)) revert InvalidAddress();
bool isGasToken = token == address(0);
uint256 totalBalance = isGasToken
? address(this).balance
: IERC20(token).balanceOf(address(this));
unchecked {
uint256 maxAmount = totalBalance - totalAffiliateBalance[token];
if (amount > maxAmount) amount = maxAmount;
}
if (amount == 0) revert BalanceTooLow();
if (isGasToken) {
Address.sendValue(payable(to), amount);
} else {
IERC20(token).safeTransfer(to, amount);
}
emit WithdrawStuckFunds(to, token, amount);
}
/// @notice Verifies the signature of the oracle response.
/// @param freeBetData The freebet data to be verified.
/// @param signature The manager signature to be validated.
function _verifySignature(
FreeBetData memory freeBetData,
bytes memory signature
) internal view {
bytes32 message = keccak256(abi.encode(freeBetData));
bytes32 hash = message.toEthSignedMessageHash();
address signer = hash.recover(signature);
if (manager != signer) revert InvalidSignature();
}
/// @notice Gets the current chain ID.
/// @return The chain ID.
///
function _getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
// @notice Allow the contract to receive VRF cost surplus from game contracts when wagering.
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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.
*
* _Available since v3.1._
*/
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 `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {IAccessControlEnumerable} from "@openzeppelin/contracts/access/IAccessControlEnumerable.sol";
/// @notice Defines common functionalities used across IBankAdmin & IBankAffiliate interfaces.
interface IBankCommon {
/// @notice Reverting error when trying to do an action with a non added token.
error TokenNotExists();
/// @notice Reverting error when param is not valid or not in range
error InvalidParam();
/// @notice Reverting error when team wallet or treasury is the zero address.
error InvalidAddress();
}
/// @notice Defines affiliate functionalities, essentially withdrawing house edge amount.
interface IBankAffiliate is IBankCommon {
/// @notice Emitted after the token's affiliate allocation is distributed.
/// @param token Address of the token.
/// @param affiliate Address of the affiliate.
/// @param affiliateAmount The number of tokens sent to the affiliate.
event AffiliateRevenuesDistribution(
address indexed token,
address affiliate,
uint256 affiliateAmount
);
/// @notice Distributes the token's affiliate allocation amount.
/// @param tokenAddress Address of the token.
/// @param to Address on which to send the tokens.
function withdrawAffiliateRevenues(
address tokenAddress,
address to
) external;
}
/// @notice Defines administrative functionalities.
interface IBankAdmin is IBankCommon {
/// @notice Emitted after the team wallet is set.
/// @notice previousTeamWallet Old team wallet address.
/// @param teamWallet The team wallet address.
event SetTeamWallet(address previousTeamWallet, address teamWallet);
/// @notice Emitted after the max call gas is set.
/// @param previousMaxCallGas The old max call gas value.
/// @param maxCallGas The max call gas value.
event SetMaxCallGas(uint256 previousMaxCallGas, uint256 maxCallGas);
/// @notice Emitted after a token is added or removed.
/// @param token Address of the token.
/// @param added Whether the token must be added or removed.
event AddToken(address token, bool added);
/// @notice Emitted after the token's house edge allocations for bet payout is set.
/// @param token Address of the token.
/// @param bank Rate to be allocated to the bank, on bet payout.
/// @param dividend Rate to be allocated as staking rewards, on bet payout.
/// @param affiliate Rate to be allocated to the affiliate, on bet payout.
/// @param treasury Rate to be allocated to the treasury, on bet payout.
/// @param team Rate to be allocated to the team, on bet payout.
event SetTokenHouseEdgeSplit(
address indexed token,
uint16 bank,
uint16 dividend,
uint16 affiliate,
uint16 treasury,
uint16 team
);
/// @notice Emitted after a token is allowed.
/// @param token Address of the token.
/// @param allowed Whether the token is allowed for betting.
event SetAllowedToken(address indexed token, bool allowed);
/// @notice Emitted after the token's treasury and team allocations are distributed.
/// @param token Address of the token.
/// @param treasuryAmount The number of tokens sent to the treasury.
/// @param teamAmount The number of tokens sent to the team.
event ProtocolRevenuesDistribution(
address indexed token,
uint256 treasuryAmount,
uint256 teamAmount
);
/// @notice Emitted after the token's dividend allocation is distributed.
/// @param token Address of the token.
/// @param amount The number of tokens sent to the dividend manager.
event WithdrawDividend(address indexed token, uint256 amount);
/// @notice Token's house edge allocations & splits struct.
/// The games house edge is divided into several allocations and splits.
/// The allocated amounts stays in the bank until authorized parties withdraw. They are subtracted from the balance.
/// @param bank Rate to be allocated to the bank, on bet payout.
/// @param dividend Rate to be allocated as staking rewards, on bet payout.
/// @param affiliate Rate to be allocated to the affiliate, on bet payout.
/// @param treasury Rate to be allocated to the treasury, on bet payout.
/// @param team Rate to be allocated to the team, on bet payout.
/// @param dividendAmount The number of tokens to be sent as staking rewards.
/// @param affiliateAmount The total number of tokens to be sent to the affiliates.
/// @param treasuryAmount The number of tokens to be sent to the treasury.
/// @param teamAmount The number of tokens to be sent to the team.
struct HouseEdgeSplitAndAllocation {
uint16 bank;
uint16 dividend;
uint16 affiliate;
uint16 treasury;
uint16 team;
uint256 dividendAmount;
uint256 affiliateAmount;
uint256 treasuryAmount;
uint256 teamAmount;
}
/// @notice Token struct.
/// List of tokens to bet on games.
/// @param allowed Whether the token is allowed for bets.
/// @param paused Whether the token is paused for bets.
/// @param balanceRisk Defines the maximum bank payout, used to calculate the max bet amount.
/// @param bankrollProvider Address of the bankroll manager to manage the token.
/// @param pendingBankrollProvider Address of the elected new bankroll manager during transfer
/// @param houseEdgeSplit House edge allocations.
struct Token {
bool allowed;
bool paused;
uint16 balanceRisk;
address bankrollProvider;
address pendingBankrollProvider;
HouseEdgeSplitAndAllocation houseEdgeSplitAndAllocation;
}
/// @notice Token's metadata struct. It contains additional information from the ERC20 token.
/// @dev Only used on the `getTokens` getter for the front-end.
/// @param decimals Number of token's decimals.
/// @param tokenAddress Contract address of the token.
/// @param name Name of the token.
/// @param symbol Symbol of the token.
/// @param token Token data.
struct TokenMetadata {
uint8 decimals;
address tokenAddress;
string name;
string symbol;
Token token;
}
/// @notice Adds or removes a token that'll be visible for the games' betting.
/// @param token Address of the token.
/// @param added Whether the token must be added or removed.
function addToken(address token, bool added) external;
/// @notice Changes the token's bet permission.
/// @param token Address of the token.
/// @param allowed Whether the token is enabled for bets.
function setAllowedToken(address token, bool allowed) external;
/// @notice Sets the token's house edge allocations for bet payout.
/// @param token Address of the token.
/// @param bank Rate to be allocated to the bank, on bet payout.
/// @param dividend Rate to be allocated as staking rewards, on bet payout.
/// @param affiliate Rate to be allocated to the affiliate, on bet payout.
/// @param treasury Rate to be allocated to the treasury, on bet payout.
/// @param team Rate to be allocated to the team, on bet payout.
/// @dev `bank`, `dividend`, `treasury` and `team` rates sum must equals 10000.
function setHouseEdgeSplit(
address token,
uint16 bank,
uint16 dividend,
uint16 affiliate,
uint16 treasury,
uint16 team
) external;
/// @notice Withdraws token dividends.
/// @param tokenAddress Address of the token.
function withdrawDividend(address tokenAddress) external;
/// @notice Withdraws all tokens dividends.
function withdrawDividends() external;
/// @notice Sets the new team wallet.
/// @param teamWallet_ The team wallet address.
function setTeamWallet(address teamWallet_) external;
/// @notice Sets the new max call gas value.
/// @param maxCallGas_ The max call gas value.
function setMaxCallGas(uint256 maxCallGas_) external;
/// @notice Distributes the token's treasury and team allocations amounts.
/// @param tokenAddress Address of the token.
function withdrawProtocolRevenues(address tokenAddress) external;
/// @notice Calculates the max bet amount based on the token balance, the balance risk, and the game multiplier.
/// @param token Address of the token.
/// @param multiplier The bet amount leverage determines the user's profit amount. 10000 = 100% = no profit.
/// @return Maximum bet amount for the token.
/// @dev The multiplier should be at least 10000 in theory.
function getMaxBetAmount(
address token,
uint256 multiplier
) external view returns (uint256);
/// @notice Reverting error when trying to add an existing token.
error TokenExists();
/// @notice Reverting error when setting the house edge allocations, but the sum isn't 100%.
/// @param splitSum Sum of the house edge allocations rates.
error WrongHouseEdgeSplit(uint16 splitSum);
}
/// @notice Defines bankroll provider functionalities.
interface IBankBankrollProvider {
/// @notice Emitted after the balance risk is set.
/// @param previousBalanceRisk Old balance risk value.
/// @param balanceRisk Rate defining the balance risk.
event SetBalanceRisk(
address indexed token,
uint16 previousBalanceRisk,
uint16 balanceRisk
);
/// @notice Emitted after a token is paused.
/// @param token Address of the token.
/// @param paused Whether the token is paused for betting.
event SetPausedToken(address indexed token, bool paused);
/// @notice Emitted after a token deposit.
/// @param token Address of the token.
/// @param amount The number of token deposited.
event Deposit(address indexed token, uint256 amount);
/// @notice Emitted after a token withdrawal.
/// @param token Address of the token.
/// @param amount The number of token withdrawn.
/// @param to who gets the funds.
event Withdraw(address indexed token, uint256 amount, address indexed to);
/// @notice emitted when starting a token's bankroll manager transfer
/// @param token Address of the token.
/// @param newBankrollProvider The new bankroll provider address.
event TokenBankrollProviderTransferStarted(
address token,
address newBankrollProvider
);
/// @notice emitted when accepting a token's bankroll manager transfer
/// @param token Address of the token.
/// @param previousBankrollProvider Old bankroll provider address.
/// @param bankrollProvider The bankroll provider address.
event TokenBankrollProviderTransferAccepted(
address token,
address previousBankrollProvider,
address bankrollProvider
);
/// @notice Deposit funds in the bank to allow gamers to win more.
/// ERC20 token allowance should be given prior to deposit.
/// @param token Address of the token.
/// @param amount Number of tokens.
function deposit(address token, uint256 amount) external payable;
/// @notice Withdraw funds from the bank. Token has to be paused and no pending bet resolution on games.
/// @param token Address of the token.
/// @param amount Number of tokens.
function withdraw(address token, uint256 amount) external;
/// @notice Sets the new token balance risk.
/// @param token Address of the token.
/// @param balanceRisk Risk rate.
function setBalanceRisk(address token, uint16 balanceRisk) external;
/// @notice Changes the token's paused status.
/// @param token Address of the token.
/// @param paused Whether the token is paused.
function setPausedToken(address token, bool paused) external;
/// @notice Gets the token's bankrollProvider.
/// @param token Address of the token.
/// @return Address of the bankrollProvider.
function getBankrollProvider(address token) external view returns (address);
/// @notice starts a token's bankroll manager transfer
/// @param token address to tranfer
/// @param to sets the new bankroll manager
function setTokenBankrollProviderTransfer(
address token,
address to
) external;
/// @notice accepts a token's bankrollProvider transfer
/// @param token address to tranfer
function acceptTokenBankrollProviderTransfer(address token) external;
/// @notice Reverting error when sender isn't allowed.
error AccessDenied();
/// @notice Reverting error when withdrawing a non paused token.
error TokenNotPaused();
/// @notice Reverting error when token has pending bets on a game.
error TokenHasPendingBets();
/// @notice Reverting error when value sent is not valid
error InvalidValue();
}
/// @notice Defines functionalities used by game contracts.
interface IBankGame {
/// @notice Emitted after the token's house edge is allocated.
/// @param token Address of the token.
/// @param bank The number of tokens allocated to bank.
/// @param dividend The number of tokens allocated as staking rewards.
/// @param treasury The number of tokens allocated to the treasury.
/// @param team The number of tokens allocated to the team.
/// @param affiliate The number of tokens allocated to the affiliate.
/// @param affiliateAddress The address of the affiliate.
event AllocateHouseEdgeAmount(
address indexed token,
uint256 bank,
uint256 dividend,
uint256 treasury,
uint256 team,
uint256 affiliate,
address affiliateAddress
);
/// @notice Emitted after the bet profit amount is sent to the user.
/// @param token Address of the token.
/// @param newBalance New token balance.
/// @param profit Bet profit amount sent.
event Payout(address indexed token, uint256 newBalance, uint256 profit);
/// @notice Emitted after the bet amount is collected from the game smart contract.
/// @param token Address of the token.
/// @param newBalance New token balance.
/// @param amount Bet amount collected.
event CashIn(address indexed token, uint256 newBalance, uint256 amount);
/// @notice Payouts a winning bet, and allocate the house edge fee.
/// @param user Address of the player.
/// @param token Address of the token.
/// @param profit Number of tokens to be sent to the player.
/// @param fees Bet amount and bet profit fees amount.
/// @param affiliate Address of the affiliate
function payout(
address user,
address token,
uint256 profit,
uint256 fees,
address affiliate
) external payable;
/// @notice Accounts a loss bet.
/// @dev In case of an ERC20, the bet amount should be transfered prior to this tx.
/// @dev In case of the gas token, the bet amount is sent along with this tx.
/// @param tokenAddress Address of the token.
/// @param amount Loss bet amount.
/// @param fees Bet amount and bet profit fees amount.
/// @param affiliate Address of the affiliate
function cashIn(
address tokenAddress,
uint256 amount,
uint256 fees,
address affiliate
) external payable;
/// @notice Calculates the max bet amount based on the token balance, the balance risk, and the game multiplier.
/// @param tokenAddress Address of the token.
/// @param multiplier The bet amount leverage determines the user's profit amount. 10000 = 100% = no profit.
/// @notice Gets the token's min bet amount.
/// @return isAllowedToken Whether the token is enabled for bets.
/// @return maxBetAmount Maximum bet amount for the token.
/// @return maxBetCount Maximum bet count for the token/multiplier.
/// @dev The multiplier should be at least 10000 in theory.
function getBetRequirements(
address tokenAddress,
uint256 multiplier
)
external
view
returns (
bool isAllowedToken,
uint256 maxBetAmount,
uint256 maxBetCount
);
/// @notice Gets the token's balance.
/// The token's house edge allocation amounts are subtracted from the balance.
/// @param token Address of the token.
/// @return The amount of token available for profits.
function getBalance(address token) external view returns (uint256);
/// @notice Calculates the max bet count based the balance risk, and the game multiplier.
/// The formula has been designed so that the player cannot win more than the entire bankroll
/// in the case all their bets are won.
/// @param token Address of the token.
/// @param multiplier The bet amount leverage determines the user's profit amount. 10000 = 100% = no profit.
/// @return Maximum bet count for the token/multiplier.
/// @dev The multiplier should be at least 10000 in theory.
function getMaxBetCount(
address token,
uint256 multiplier
) external view returns (uint256);
}
/// @notice Aggregates all functionalities from IBankAdmin, IBankBankrollProvider, IBankGame, IBankAffiliate & IAccessControlEnumerable interfaces.
interface IBank is
IBankAdmin,
IBankBankrollProvider,
IBankGame,
IBankAffiliate,
IAccessControlEnumerable
{
/// @dev For the front-end
function getTokens() external view returns (TokenMetadata[] memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
/// @notice Defines common functionalities used across IFreeBetAffiliate, IFreeBetAdmin & IFreeBetPlayer interfaces.
interface IFreeBetCommon {
/// @notice Reverting error when there is not enough funds to withdraw or to wager with.
error BalanceTooLow();
/// @notice Reverting error when a address passed in params is the zero adress.
error InvalidAddress();
}
/// @notice Defines affiliate functionalities, essentially depositing and withdrawing funds.
interface IFreeBetAffiliate is IFreeBetCommon {
/// @notice Emitted after some funds have been deposited by an affiliate.
/// @param affiliate Address of the affiliate.
/// @param token Address of the token.
/// @param amount The deposited amount.
event Deposit(
address indexed affiliate,
address indexed token,
uint256 amount
);
/// @notice Emitted after some funds have been withdrawn by an affiliate.
/// @param affiliate Address of the affiliate.
/// @param token Address of the token.
/// @param amount The withdrawn amount.
/// @param to Address of the destination.
event Withdraw(
address indexed affiliate,
address indexed token,
uint256 amount,
address to
);
/// @notice Deposit funds in the contract to allow players to wager with.
/// @param affiliate Address of the affiliate.
/// @param token Address of the token.
/// @param amount Amount of tokens.
function deposit(
address affiliate,
address token,
uint256 amount
) external payable;
/// @notice Withdraw affiliate funds of the contract.
/// @param token Address of the token.
/// @param amount Amount of tokens.
/// @param to Address of the destination.
function withdraw(address token, uint256 amount, address to) external;
/// @notice Reverting error when a value passed is not valid.
error InvalidValue();
/// @notice Reverting error when the amount passed in deposit function is 0.
error InvalidAmount();
}
/// @notice Defines administrative functionalities.
interface IFreeBetAdmin is IFreeBetCommon {
/// @notice Emitted after the owner has withdrawn some lost funds.
/// @param to Address of the receiver.
/// @param token Address of the token.
/// @param amount The withdrawn amount.
event WithdrawStuckFunds(
address indexed to,
address indexed token,
uint256 amount
);
/// @notice Emitted after the manager address has been updated.
/// @param previousManager Address of the previous manager.
/// @param manager Address of the new manager.
event ManagerSet(address previousManager, address manager);
/// @notice Emitted after the bank address has been updated.
/// @param previousBank Address of the previous bank.
/// @param bank Address of the new bank.
event BankSet(address previousBank, address bank);
/// @notice Update the manager address.
/// @param manager_ The new manager address.
function setManager(address manager_) external;
/// @notice Update the bank address.
/// @param bank_ The new bank address.
function setBank(address bank_) external;
/// @notice Withdraw lost funds of the contract.
/// @param token Address of the token.
/// @param amount Amount of tokens.
/// @param to Address of the receiver.
/// @dev It allows to recover funds sent directly in the smart contract without using the deposit function.
function withdrawStuckFunds(
address token,
uint256 amount,
address to
) external;
}
/// @notice Defines player functionalities, essentially wager a freebet.
interface IFreeBetPlayer is IFreeBetCommon {
/// @notice Emitted after a freebet has been placed.
/// @param freeBetId Freebet ID (generated off-chain).
/// @param player Address of the player (receiver).
/// @param affiliate Address of the affiliate who offers the freebet.
/// @param betId Bet ID generated by the game contract.
/// @param token Address of the token.
/// @param amount The bet amount.
/// @param game Address of the game.
event PlaceFreeBet(
uint256 indexed freeBetId,
address indexed player,
address indexed affiliate,
uint256 betId,
address token,
uint256 amount,
address game
);
/// @notice Freebet information struct.
/// @param freeBetId Freebet ID (generated off-chain)
/// @param player Address of the player (receiver).
/// @param betId Bet ID generated by the game contract.
/// @param amount The bet amount.
/// @param token Address of the token.
/// @param game Address of the game.
/// @param affiliate Address of the affiliate who offers the freebet.
struct FreeBet_ {
uint256 freeBetId;
address player;
uint256 betId;
uint256 amount;
address token;
address game;
address affiliate;
}
/// @notice Signed Freebet information struct.
/// @param chainId Chain ID.
/// @param freeBetId Freebet ID (generated off-chain).
/// @param player Address of the player (receiver).
/// @param amount The bet amount.
/// @param token Address of the token.
/// @param expiresAt Expiration date timestamp.
/// @param affiliate Address of the affiliate who offers the freebet.
/// @param freebetAddress Address of the Freebet contract.
struct FreeBetData {
uint256 chainId;
uint256 freeBetId;
address player;
uint256 amount;
address token;
uint64 expiresAt;
address affiliate;
address freebetAddress;
}
/// @notice Uses a freebet on a game.
/// @param game Address of the game.
/// @param input The encoded input data (eg. the face for cointoss game).
/// @param freeBetData Freebet data .
/// @param signature The encoded freebet data signed by the manager.
/// @param maxHouseEdge The maximum authorized house edge.
/// @return betId Bet ID.
/// @dev Only games which owns GAME_ROLE can be used to wager.
/// The chain_id allows to avoid cross-chain replay attacks.
function wager(
address game,
bytes calldata input,
FreeBetData calldata freeBetData,
bytes memory signature,
uint16 maxHouseEdge
) external payable returns (uint256 betId);
/// @notice Reverting error when sender isn't the player who owns the freebet.
error WagerDenied();
/// @notice Reverting error when the freebet's deadline is expired.
error BetExpired();
/// @notice Reverting error when the freebet has already been wagered.
error BetAlreadyWagered();
/// @notice Reverting error when the signature and the freebet data do not match.
error InvalidSignature();
/// @notice Reverting error when the chain ID is not the same as the contract.
error WrongChainId();
/// @notice Reverting error when the contract address is not the same as the current contract.
error WrongFreebetAddress();
/// @notice Reverting error when the game contract is not authorized from Bank.
error UnauthorizedGame();
}
/// @notice Aggregates all functionalities from IFreeBetAdmin, IFreeBetAffiliate & IFreeBetPlayer interfaces.
interface IFreeBet is IFreeBetAdmin, IFreeBetAffiliate, IFreeBetPlayer {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {IVRFV2PlusWrapperCustom} from "../../shared/interfaces/IVRFV2PlusWrapperCustom.sol";
import {IVRFCoordinatorV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2Plus.sol";
import {IVRFMigratableConsumerV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFMigratableConsumerV2Plus.sol";
import {IOwnable} from "@chainlink/contracts/src/v0.8/shared/interfaces/IOwnable.sol";
/// @notice Defines common functionalities used across IGameAdmin, IGameAffiliate & IGamePlayer interfaces.
interface IGameCommon {
/// @notice Reverting error when token has pending bets.
error TokenHasPendingBets();
/// @notice Reverting error when house edge is too high (setHouseEdge & newBet)
error HouseEdgeTooHigh();
}
/// @notice Defines administrative functionalities.
interface IGameAdmin is IVRFMigratableConsumerV2Plus, IOwnable, IGameCommon {
/// @notice Emitted after the house edge is set for a token.
/// @param token Address of the token.
/// @param previousHouseEdge Old house edge rate.
/// @param houseEdge House edge rate.
event SetHouseEdge(
address indexed token,
uint16 previousHouseEdge,
uint16 houseEdge
);
/// @notice Emitted after the Chainlink base callback gas is set for a token.
/// @param token Address of the token.
/// @param previousCallbackGasBase Previous Chainlink VRF base callback gas.
/// @param callbackGasBase New Chainlink VRF base callback gas.
event SetVRFCallbackGasBase(
address indexed token,
uint32 previousCallbackGasBase,
uint32 callbackGasBase
);
/// @notice Emitted after the token's VRF subscription ID is set.
/// @param token Address of the token.
/// @param previousSubId Previous subscription ID.
/// @param subId Subscription ID.
event SetVRFSubId(
address indexed token,
uint256 previousSubId,
uint256 subId
);
/// @notice Emitted after the max call gas is set.
/// @param previousMaxCallGas The previous max call gas value.
/// @param maxCallGas The max call gas value.
event SetMaxCallGas(uint256 previousMaxCallGas, uint256 maxCallGas);
/// @notice Emitted after the refund time is set.
/// @param previousRefundTime The previous refund yime value.
/// @param refundTime The refund time value.
event SetRefundTime(uint64 previousRefundTime, uint64 refundTime);
/// @notice Emitted after the Chainlink config is set.
/// @param requestConfirmations How many confirmations the Chainlink node should wait before responding.
/// @param keyHash Hash of the public key used to verify the VRF proof.
/// @param chainlinkWrapper Chainlink Wrapper used to estimate the VRF cost.
/// @param VRFCallbackGasExtraBet Callback gas to be added for each bet while multi betting.
/// @param nativePayment Whether Betswirl pays VRF fees in gas token or in LINK token.
event SetChainlinkConfig(
uint16 requestConfirmations,
bytes32 keyHash,
IVRFV2PlusWrapperCustom chainlinkWrapper,
uint32 VRFCallbackGasExtraBet,
bool nativePayment
);
/// @notice Emitted after the token's VRF fees amount is transfered to the user.
/// @param token Address of the token.
/// @param amount Token amount refunded.
event DistributeTokenVRFFees(address indexed token, uint256 amount);
/// @notice Chainlink VRF configuration struct.
/// @param requestConfirmations How many confirmations the Chainlink node should wait before responding.
/// @param numRandomWords How many random words is needed to resolve a game's bet.
/// @param keyHash Hash of the public key used to verify the VRF proof.
/// @param chainlinkWrapper Chainlink Wrapper used to estimate the VRF cost
/// @param VRFCallbackGasExtraBet Callback gas to be added for each bet while multi betting.
/// @param nativePayment Whether Betswirl pays VRF fees in gas token or in LINK token.
struct ChainlinkConfig {
uint16 requestConfirmations;
uint16 numRandomWords;
bytes32 keyHash;
IVRFV2PlusWrapperCustom chainlinkWrapper;
uint32 VRFCallbackGasExtraBet;
bool nativePayment;
}
/// @notice Token struct.
/// @param houseEdge House edge rate.
/// @param pendingCount Number of pending bets.
/// @param vrfSubId Chainlink VRF v2.5 subscription ID.
/// @param VRFCallbackGasBase How much gas is needed in the Chainlink VRF callback.
/// @param VRFFees Chainlink's VRF collected fees amount.
struct Token {
uint16 houseEdge;
uint64 pendingCount;
uint256 vrfSubId;
uint32 VRFCallbackGasBase;
uint256 VRFFees;
}
/// @notice Sets the game house edge rate for a specific token.
/// @param token Address of the token.
/// @param houseEdge House edge rate.
function setHouseEdge(address token, uint16 houseEdge) external;
/// @notice Pauses/Unpauses the contract to disable/enable new bets.
function togglePause() external;
/// @notice Sets the Chainlink VRF subscription ID for a specific token.
/// @param token Address of the token.
/// @param subId Subscription ID.
function setVRFSubId(address token, uint256 subId) external;
/// @notice Sets the new max call gas value.
/// @param maxCallGas_ The max call gas value.
function setMaxCallGas(uint256 maxCallGas_) external;
/// @notice Sets the new refund time value.
/// @param refundTime_ The refund time value.
/// @dev Should be bewteen 24h (provided by Chainlink) & 30 days.
function setRefundTime(uint64 refundTime_) external;
/// @notice Sets the Chainlink VRF V2.5 configuration.
/// @param requestConfirmations How many confirmations the Chainlink node should wait before responding.
/// @param keyHash Hash of the public key used to verify the VRF proof.
/// @param chainlinkWrapper Chainlink Wrapper used to estimate the VRF cost.
/// @param VRFCallbackGasExtraBet Callback gas to be added for each bet while multi betting.
/// @param nativePayment Whether Betswirl pays VRF fees in gas token or in LINK token.
function setChainlinkConfig(
uint16 requestConfirmations,
bytes32 keyHash,
IVRFV2PlusWrapperCustom chainlinkWrapper,
uint32 VRFCallbackGasExtraBet,
bool nativePayment
) external;
/// @notice Sets the Chainlink VRF V2.5 configuration.
/// @param callbackGasBase How much gas is needed in the Chainlink VRF callback.
function setVRFCallbackGasBase(
address token,
uint32 callbackGasBase
) external;
/// @notice Distributes the token's collected Chainlink fees.
/// @param token Address of the token.
function withdrawTokenVRFFees(address token) external;
/// @notice Returns the Chainlink VRF config.
/// @param requestConfirmations How many confirmations the Chainlink node should wait before responding.
/// @param keyHash Hash of the public key used to verify the VRF proof.
/// @param chainlinkCoordinator Reference to the VRFCoordinatorV2Plus deployed contract.
/// @param chainlinkWrapper Reference to the VRFV2PlusWrapper deployed contract.
/// @param VRFCallbackGasExtraBet Callback gas to be added for each bet while multi betting.
function getChainlinkConfig()
external
view
returns (
uint16 requestConfirmations,
bytes32 keyHash,
IVRFCoordinatorV2Plus chainlinkCoordinator,
IVRFV2PlusWrapperCustom chainlinkWrapper,
uint32 VRFCallbackGasExtraBet,
bool nativePayment
);
/// @notice Reverting error when max call gas value is not valid.
error InvalidMaxCallGas();
/// @notice Reverting error when calling withdrawTokenVRFFees with a token for which VRF sub ID is not set.
error InvalidVRFSubId();
/// @notice Reverting when calling setChainlinkConfig with wrong requestConfirmations or keyHash value
error InvalidParam();
}
/// @notice Defines affiliate functionalities, essentially setting house edge.
interface IGameAffiliate is IGameCommon {
/// @notice Emitted after the affiliate's house edge is set for a token.
/// @param token Address of the token.
/// @param affiliate Address of the affiliate.
/// @param previousHouseEdge Previous affiliate's house edge rate.
/// @param houseEdge Affiliate's house edge rate.
event SetAffiliateHouseEdge(
address indexed token,
address affiliate,
uint16 previousHouseEdge,
uint16 houseEdge
);
/// @notice Sets the game affiliate's house edge rate for a specific token.
/// @param token Address of the token.
/// @param affiliateHouseEdge Affiliate's house edge rate.
/// @dev The msg.sender of the tx is considered as to be the affiliate.
function setAffiliateHouseEdge(
address token,
uint16 affiliateHouseEdge
) external;
/// @notice Reverting error when sender isn't allowed.
error AccessDenied();
/// @notice Reverting error when house edge is too low
error HouseEdgeTooLow();
}
/// @notice Defines functionalities used by the bank contract.
interface IGameBank {
/// @notice Returns whether the token has pending bets.
/// @return Whether the token has pending bets.
function hasPendingBets(address token) external view returns (bool);
}
/// @notice Defines player functionalities, essentially wagering & refunding a bet.
interface IGamePlayer {
/// @notice Bet configuration struct.
/// @param token Address of the token.
/// @param betAmount The amount per bet.
/// @param betCount How many bets at maximum must be placed.
/// @param stopGain Profit limit indicating that bets must stop after surpassing it (before deduction of house edge).
/// @param stopLoss Loss limit indicating that bets must stop after exceeding it (before deduction of house edge).
/// @param maxHouseEdge Maximum authorized house edge.
struct BetData {
address token;
uint256 betAmount;
uint16 betCount;
uint256 stopGain;
uint256 stopLoss;
uint16 maxHouseEdge;
}
/// @notice Bet information struct.
/// @param resolved Whether the bet has been resolved.
/// @param receiver Address of the receiver.
/// @param token Address of the token.
/// @param id Bet ID generated by Chainlink VRF.
/// @param amount The bet amount.
/// @param houseEdge The house ege.
/// @param timestamp of the bet used to refund in case Chainlink's callback fail.
/// @param payout The payout amount.
/// @param betCount How many bets at maximum must be placed.
/// @param stopGain Profit limit indicating that bets must stop after surpassing it (before deduction of house edge).
/// @param stopLoss Loss limit indicating that bets must stop after surpassing it (before deduction of house edge).
/// @param affiliate Address of the affiliate.
struct Bet {
bool resolved;
address receiver;
address token;
uint256 id;
uint256 amount;
uint16 houseEdge;
uint32 timestamp;
uint256 payout;
uint16 betCount;
uint256 stopGain;
uint256 stopLoss;
address affiliate;
}
/// @notice Emitted after the bet amount is transfered to the user.
/// @param id The bet ID.
/// @param user Address of the player.
/// @param amount Token amount refunded.
event BetRefunded(uint256 id, address user, uint256 amount);
/// @notice Refunds the bet to the receiver if the Chainlink VRF callback failed.
/// @param id The Bet ID.
function refundBet(uint256 id) external;
/// @notice Returns the amount of ETH that should be passed to the wager transaction.
/// to cover Chainlink VRF fee.
/// @param token Address of the token.
/// @param betCount The number of bets to place.
/// @return The bet resolution cost amount.
/// @dev The user always pays VRF fees in gas token, whatever we pay in gas token or in LINK on our side.
function getChainlinkVRFCost(
address token,
uint16 betCount
) external view returns (uint256);
/// @notice Get the affiliate's house edge. If the affiliate has not their own house edge,
/// then it takes the default house edge.
/// @param affiliate Address of the affiliate.
/// @param token Address of the token.
/// @return The affiliate's house edge.
function getAffiliateHouseEdge(
address affiliate,
address token
) external view returns (uint16);
/// @notice Insufficient bet amount.
/// @param minBetAmount Bet amount.
error UnderMinBetAmount(uint256 minBetAmount);
/// @notice Reverting error when provided betCount isn't valid.
error UnderMinBetCount(uint256 minBetCount);
/// @notice Bet count provided is too high.
/// @param maxBetCount Maximum bet count.
error BetCountTooHigh(uint256 maxBetCount);
/// @notice Bet provided doesn't exist or was already resolved.
error NotPendingBet();
/// @notice Bet isn't resolved yet.
error NotFulfilled();
/// @notice Token is not allowed.
error ForbiddenToken();
/// @notice The msg.value is not enough to cover Chainlink's fee.
error WrongGasValueToCoverVRFFee();
/// @notice Reverting error when provided address isn't valid.
error InvalidAddress();
}
/// @notice Aggregates all functionalities from IGameAdmin, IGameBank, IGameAffiliate & IGamePlayer interfaces.
interface IGame is IGameAdmin, IGameBank, IGameAffiliate, IGamePlayer {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {IGame} from "./IGame.sol";
/// @notice Defines common functionalities between all PVH implemention games.
interface IGameImplementation {
function wagerWithData(
bytes calldata bet,
address receiver,
address affiliate,
IGame.BetData memory betData
) external payable returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOwnable {
function owner() external returns (address);
function transferOwnership(address recipient) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {VRFV2PlusClient} from "../libraries/VRFV2PlusClient.sol";
import {IVRFSubscriptionV2Plus} from "./IVRFSubscriptionV2Plus.sol";
// Interface that enables consumers of VRFCoordinatorV2Plus to be future-proof for upgrades
// This interface is supported by subsequent versions of VRFCoordinatorV2Plus
interface IVRFCoordinatorV2Plus is IVRFSubscriptionV2Plus {
/**
* @notice Request a set of random words.
* @param req - a struct containing following fields for randomness request:
* keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* requestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* extraArgs - abi-encoded extra args
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(VRFV2PlusClient.RandomWordsRequest calldata req) external returns (uint256 requestId);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The IVRFMigratableConsumerV2Plus interface defines the
/// @notice method required to be implemented by all V2Plus consumers.
/// @dev This interface is designed to be used in VRFConsumerBaseV2Plus.
interface IVRFMigratableConsumerV2Plus {
event CoordinatorSet(address vrfCoordinator);
/// @notice Sets the VRF Coordinator address
/// @notice This method should only be callable by the coordinator or contract owner
function setCoordinator(address vrfCoordinator) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The IVRFSubscriptionV2Plus interface defines the subscription
/// @notice related methods implemented by the V2Plus coordinator.
interface IVRFSubscriptionV2Plus {
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint256 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint256 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint256 subId, address to) external;
/**
* @notice Accept subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(uint256 subId) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint256 subId, address newOwner) external;
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription with LINK, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
* @dev Note to fund the subscription with Native, use fundSubscriptionWithNative. Be sure
* @dev to send Native with the call, for example:
* @dev COORDINATOR.fundSubscriptionWithNative{value: amount}(subId);
*/
function createSubscription() external returns (uint256 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return nativeBalance - native balance of the subscription in wei.
* @return reqCount - Requests count of subscription.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(
uint256 subId
)
external
view
returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address owner, address[] memory consumers);
/*
* @notice Check to see if there exists a request commitment consumers
* for all consumers and keyhashes for a given sub.
* @param subId - ID of the subscription
* @return true if there exists at least one unfulfilled request for the subscription, false
* otherwise.
*/
function pendingRequestExists(uint256 subId) external view returns (bool);
/**
* @notice Paginate through all active VRF subscriptions.
* @param startIndex index of the subscription to start from
* @param maxCount maximum number of subscriptions to return, 0 to return all
* @dev the order of IDs in the list is **not guaranteed**, therefore, if making successive calls, one
* @dev should consider keeping the blockheight constant to ensure a holistic picture of the contract state
*/
function getActiveSubscriptionIds(uint256 startIndex, uint256 maxCount) external view returns (uint256[] memory);
/**
* @notice Fund a subscription with native.
* @param subId - ID of the subscription
* @notice This method expects msg.value to be greater than or equal to 0.
*/
function fundSubscriptionWithNative(uint256 subId) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IVRFV2PlusWrapper {
/**
* @return the request ID of the most recent VRF V2 request made by this wrapper. This should only
* be relied option within the same transaction that the request was made.
*/
function lastRequestId() external view returns (uint256);
/**
* @notice Calculates the price of a VRF request with the given callbackGasLimit at the current
* @notice block.
*
* @dev This function relies on the transaction gas price which is not automatically set during
* @dev simulation. To estimate the price at a specific gas price, use the estimatePrice function.
*
* @param _callbackGasLimit is the gas limit used to estimate the price.
* @param _numWords is the number of words to request.
*/
function calculateRequestPrice(uint32 _callbackGasLimit, uint32 _numWords) external view returns (uint256);
/**
* @notice Calculates the price of a VRF request in native with the given callbackGasLimit at the current
* @notice block.
*
* @dev This function relies on the transaction gas price which is not automatically set during
* @dev simulation. To estimate the price at a specific gas price, use the estimatePrice function.
*
* @param _callbackGasLimit is the gas limit used to estimate the price.
* @param _numWords is the number of words to request.
*/
function calculateRequestPriceNative(uint32 _callbackGasLimit, uint32 _numWords) external view returns (uint256);
/**
* @notice Estimates the price of a VRF request with a specific gas limit and gas price.
*
* @dev This is a convenience function that can be called in simulation to better understand
* @dev pricing.
*
* @param _callbackGasLimit is the gas limit used to estimate the price.
* @param _numWords is the number of words to request.
* @param _requestGasPriceWei is the gas price in wei used for the estimation.
*/
function estimateRequestPrice(
uint32 _callbackGasLimit,
uint32 _numWords,
uint256 _requestGasPriceWei
) external view returns (uint256);
/**
* @notice Estimates the price of a VRF request in native with a specific gas limit and gas price.
*
* @dev This is a convenience function that can be called in simulation to better understand
* @dev pricing.
*
* @param _callbackGasLimit is the gas limit used to estimate the price.
* @param _numWords is the number of words to request.
* @param _requestGasPriceWei is the gas price in wei used for the estimation.
*/
function estimateRequestPriceNative(
uint32 _callbackGasLimit,
uint32 _numWords,
uint256 _requestGasPriceWei
) external view returns (uint256);
/**
* @notice Requests randomness from the VRF V2 wrapper, paying in native token.
*
* @param _callbackGasLimit is the gas limit for the request.
* @param _requestConfirmations number of request confirmations to wait before serving a request.
* @param _numWords is the number of words to request.
*/
function requestRandomWordsInNative(
uint32 _callbackGasLimit,
uint16 _requestConfirmations,
uint32 _numWords,
bytes calldata extraArgs
) external payable returns (uint256 requestId);
function link() external view returns (address);
function linkNativeFeed() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {IVRFV2PlusWrapper} from "@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFV2PlusWrapper.sol";
interface IVRFV2PlusWrapperCustom is IVRFV2PlusWrapper {
function getConfig()
external
view
returns (
int256 fallbackWeiPerUnitLink,
uint32 stalenessSeconds,
uint32 fulfillmentFlatFeeNativePPM,
uint32 fulfillmentFlatFeeLinkDiscountPPM,
uint32 wrapperGasOverhead,
uint32 coordinatorGasOverheadNative,
uint32 coordinatorGasOverheadLink,
uint16 coordinatorGasOverheadPerWord,
uint8 wrapperNativePremiumPercentage,
uint8 wrapperLinkPremiumPercentage,
bytes32 keyHash,
uint8 maxNumWords
);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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 up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (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; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
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.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 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.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
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 (rounding == Rounding.Up && 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 down.
*
* 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @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.
*
* By default, the owner account will be the one that deploys the contract. 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;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @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 {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @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 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].
*/
abstract contract ReentrancyGuard {
// 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;
uint256 private _status;
constructor() {
_status = _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();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _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 _status == _ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @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 v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @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), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(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) {
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
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 keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// End consumer library.
library VRFV2PlusClient {
// extraArgs will evolve to support new features
bytes4 public constant EXTRA_ARGS_V1_TAG = bytes4(keccak256("VRF ExtraArgsV1"));
struct ExtraArgsV1 {
bool nativePayment;
}
struct RandomWordsRequest {
bytes32 keyHash;
uint256 subId;
uint16 requestConfirmations;
uint32 callbackGasLimit;
uint32 numWords;
bytes extraArgs;
}
function _argsToBytes(ExtraArgsV1 memory extraArgs) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(EXTRA_ARGS_V1_TAG, extraArgs);
}
}
{
"compilationTarget": {
"contracts/b2b/FreeBet.sol": "FreeBet"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 7777777
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"manager_","type":"address"},{"internalType":"address","name":"bank_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"BalanceTooLow","type":"error"},{"inputs":[],"name":"BetAlreadyWagered","type":"error"},{"inputs":[],"name":"BetExpired","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidSignature","type":"error"},{"inputs":[],"name":"InvalidValue","type":"error"},{"inputs":[],"name":"UnauthorizedGame","type":"error"},{"inputs":[],"name":"WagerDenied","type":"error"},{"inputs":[],"name":"WrongChainId","type":"error"},{"inputs":[],"name":"WrongFreebetAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousBank","type":"address"},{"indexed":false,"internalType":"address","name":"bank","type":"address"}],"name":"BankSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"affiliate","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousManager","type":"address"},{"indexed":false,"internalType":"address","name":"manager","type":"address"}],"name":"ManagerSet","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":true,"internalType":"uint256","name":"freeBetId","type":"uint256"},{"indexed":true,"internalType":"address","name":"player","type":"address"},{"indexed":true,"internalType":"address","name":"affiliate","type":"address"},{"indexed":false,"internalType":"uint256","name":"betId","type":"uint256"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"address","name":"game","type":"address"}],"name":"PlaceFreeBet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"affiliate","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"address","name":"to","type":"address"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"WithdrawStuckFunds","type":"event"},{"inputs":[],"name":"GAME_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"affiliateBalances","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bank","outputs":[{"internalType":"contract IBank","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"affiliate","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"freeBets","outputs":[{"internalType":"uint256","name":"freeBetId","type":"uint256"},{"internalType":"address","name":"player","type":"address"},{"internalType":"uint256","name":"betId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"game","type":"address"},{"internalType":"address","name":"affiliate","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"bank_","type":"address"}],"name":"setBank","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"manager_","type":"address"}],"name":"setManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"totalAffiliateBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"game","type":"address"},{"internalType":"bytes","name":"input","type":"bytes"},{"components":[{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"uint256","name":"freeBetId","type":"uint256"},{"internalType":"address","name":"player","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint64","name":"expiresAt","type":"uint64"},{"internalType":"address","name":"affiliate","type":"address"},{"internalType":"address","name":"freebetAddress","type":"address"}],"internalType":"struct IFreeBetPlayer.FreeBetData","name":"freeBetData","type":"tuple"},{"internalType":"bytes","name":"signature","type":"bytes"},{"internalType":"uint16","name":"maxHouseEdge","type":"uint16"}],"name":"wager","outputs":[{"internalType":"uint256","name":"betId","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"withdrawStuckFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]