Transaction Hash:
Block:
23958610 at Dec-07-2025 04:34:11 AM +UTC
Transaction Fee:
0.000032459614793508 ETH
$0.06
Gas Used:
85,413 Gas / 0.380031316 Gwei
Emitted Events:
| 383 |
Token.Transfer( from=[Sender] 0xca793ba1e428a506944f3615da9cf239ae2f4481, to=[Receiver] SuperVerseStaker, value=123522302696952619648 )
|
| 384 |
Token.Approval( owner=[Sender] 0xca793ba1e428a506944f3615da9cf239ae2f4481, spender=[Receiver] SuperVerseStaker, value=0 )
|
| 385 |
SuperVerseStaker.Stake( user=[Sender] 0xca793ba1e428a506944f3615da9cf239ae2f4481, amount=123522302696952619648, power=123522302696952619648, items= )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
|
0x4838B106...B0BAD5f97
Miner
| (Titan Builder) | 9.217208061881124513 Eth | 9.217208062735254513 Eth | 0.00000000085413 | |
| 0x8C96EdC8...d54d0b887 | |||||
| 0xca793ba1...9ae2f4481 |
0.012691761804382885 Eth
Nonce: 921
|
0.012659302189589377 Eth
Nonce: 922
| 0.000032459614793508 | ||
| 0xe53EC727...31AB40A55 |
Execution Trace
SuperVerseStaker.stake( _amount=123522302696952619648, _user=0xca793ba1E428A506944F3615da9CF239ae2f4481, _items= )
-
Token.transferFrom( sender=0xca793ba1E428A506944F3615da9CF239ae2f4481, recipient=0x8C96EdC82d111E3c5686F5ABE738A82d54d0b887, amount=123522302696952619648 ) => ( True )
File 1 of 2: SuperVerseStaker
File 2 of 2: Token
// 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.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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.
*/
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].
*/
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
// 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.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.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// 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 v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
interface IFee1155 {
\tfunction setApprovalForAll ( address, bool ) external;
\tfunction safeTransferFrom (
\t\taddress, address, uint256, uint256, bytes memory) external;
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
/**
\tThis enum tracks each type of asset that may be operated on with this
\tstaker.
\t@param ET1155 A staked Elliotrades NFT.
\t@param SF1155 A staked SuperFarm NFT.
*/
enum ItemOrigin {
\tET1155,
\tSF1155
}
interface ISuperVerseStaker {
\terror ItemAlreadyStaked ();
\terror ItemNotFound ();
\terror AmountExceedsStakedAmount ();
\terror RewardPayoutFailed ();
\t/**
\t\tThrown when attempting to withdraw before withdraw buffer has transpired.
\t*/
\terror WithdrawBufferNotFinished ();
\t
\t/**
\t\tThrown when attempting to stake or unstake no tokens and no items.
\t*/
\terror BadArguments ();
\t/**
\t\tThrown when attempting to rebase before cooldown window is finished.
\t*/
\terror rebaseWindowClosed ();
\t/**
\t\tThrown when attempting to rebase before cooldown window is finished.
\t*/
\terror RebaseWindowClosed ();
\t/**
\t Emitted on new staking position.
\t*/
\tevent Stake (
\t\taddress indexed user,
\t\tuint256 amount,
\t\tuint256 power,
\t\tInputItem[] items
\t);
\t/**
\t Emitted on successful reward claim.
\t*/
\tevent Claim (
\t\taddress indexed user,
\t\tuint256 amount
\t);
\t/**
\t Emitted on successful withdrawal.
\t*/
\tevent Withdraw (
\t\taddress indexed user,
\t\tuint256 amount,
\t\tuint256 power,
\t\tInputItem[] items
\t);
\t/**
\t Emitted on reward funding.
\t*/
\tevent Fund (
\t\taddress indexed user,
\t\tuint256 amount
\t);
\t/**
\t Input helper struct.
\t*/
\tstruct InputItem {
\t\tuint256 itemId;
\t\tItemOrigin origin;
\t}
\t/**
\t\tStake ERC20 tokens and items from specified collections. The amount of
\t\tERC20 tokens can be zero as long as at least one item is staked.
\t\tSimilarly, the amount of items being staked can be zero as long as the
\t\tuser is staking ERC20 tokens. Tokens can be staked on a user's behalf,
\t\tprovided the caller has the necessary approvals for transfers by the user
\t\t@param _amount The amount of ERC20 tokens being staked
\t\t@param _user The address of the user staking tokens
\t\t@param _items The array of items being staked
\t*/
\tfunction stake(
\t\tuint256 _amount,
\t\taddress _user,
\t\tInputItem[] calldata _items
\t) external;
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
import {
\tOwnable
} from "@openzeppelin/contracts/access/Ownable.sol";
import {
\tAddress
} from "@openzeppelin/contracts/utils/Address.sol";
error RightNotSpecified();
error CallerHasNoAccess();
error ManagedRightNotSpecified();
/**
\t@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
\t@title An advanced permission-management contract.
\t@author Tim Clancy <@_Enoch>
\tThis contract allows for a contract owner to delegate specific rights to
\texternal addresses. Additionally, these rights can be gated behind certain
\tsets of circumstances and granted expiration times. This is useful for some
\tmore finely-grained access control in contracts.
\tThe owner of this contract is always a fully-permissioned super-administrator.
\t@custom:date August 23rd, 2021.
*/
abstract contract PermitControl is Ownable {
\tusing Address for address;
\t/// A special reserved constant for representing no rights.
\tbytes32 internal constant _ZERO_RIGHT = hex"00000000000000000000000000000000";
\t/// A special constant specifying the unique, universal-rights circumstance.
\tbytes32 internal constant _UNIVERSAL = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
\t/**
\t\tA special constant specifying the unique manager right. This right allows an
\t\taddress to freely-manipulate the `managedRight` mapping.
\t*/
\tbytes32 internal constant _MANAGER = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
\t/**
\t\tA mapping of per-address permissions to the circumstances, represented as
\t\tan additional layer of generic bytes32 data, under which the addresses have
\t\tvarious permits. A permit in this sense is represented by a per-circumstance
\t\tmapping which couples some right, represented as a generic bytes32, to an
\t\texpiration time wherein the right may no longer be exercised. An expiration
\t\ttime of 0 indicates that there is in fact no permit for the specified
\t\taddress to exercise the specified right under the specified circumstance.
\t\t@dev Universal rights MUST be stored under the 0xFFFFFFFFFFFFFFFFFFFFFFFF...
\t\tmax-integer circumstance. Perpetual rights may be given an expiry time of
\t\tmax-integer.
\t*/
\tmapping ( address => mapping( bytes32 => mapping( bytes32 => uint256 )))
\t\tinternal _permissions;
\t/**
\t\tAn additional mapping of managed rights to manager rights. This mapping
\t\trepresents the administrator relationship that various rights have with one
\t\tanother. An address with a manager right may freely set permits for that
\t\tmanager right's managed rights. Each right may be managed by only one other
\t\tright.
\t*/
\tmapping ( bytes32 => bytes32 ) internal _managerRights;
\t/**
\t\tAn event emitted when an address has a permit updated. This event captures,
\t\tthrough its various parameter combinations, the cases of granting a permit,
\t\tupdating the expiration time of a permit, or revoking a permit.
\t\t@param updater The address which has updated the permit.
\t\t@param updatee The address whose permit was updated.
\t\t@param circumstance The circumstance wherein the permit was updated.
\t\t@param role The role which was updated.
\t\t@param expirationTime The time when the permit expires.
\t*/
\tevent PermitUpdated (
\t\taddress indexed updater,
\t\taddress indexed updatee,
\t\tbytes32 circumstance,
\t\tbytes32 indexed role,
\t\tuint256 expirationTime
\t);
\t/**
\t\tAn event emitted when a management relationship in `managerRight` is
\t\tupdated. This event captures adding and revoking management permissions via
\t\tobserving the update history of the `managerRight` value.
\t\t@param manager The address of the manager performing this update.
\t\t@param managedRight The right which had its manager updated.
\t\t@param managerRight The new manager right which was updated to.
\t*/
\tevent ManagementUpdated (
\t\taddress indexed manager,
\t\tbytes32 indexed managedRight,
\t\tbytes32 indexed managerRight
\t);
\t/**
\t\tA modifier which allows only the super-administrative owner or addresses
\t\twith a specified valid right to perform a call.
\t\t@param _circumstance The circumstance under which to check for the validity
\t\t\tof the specified `right`.
\t\t@param _right The right to validate for the calling address. It must be
\t\t\tnon-expired and exist within the specified `_circumstance`.
\t*/
\tmodifier hasValidPermit (
\t\tbytes32 _circumstance,
\t\tbytes32 _right
\t) {
\t\tif (
\t\t\tmsg.sender != owner() &&
\t\t\t\t!_hasRight(msg.sender, _circumstance, _right)
\t\t) {
\t\t\trevert CallerHasNoAccess();
\t\t}
\t\t_;
\t}
\t/**
\t\tDetermine whether or not an address has some rights under the given
\t\tcircumstance,
\t\t@param _address The address to check for the specified `_right`.
\t\t@param _circumstance The circumstance to check the specified `_right` for.
\t\t@param _right The right to check for validity.
\t\t@return true or false, whether user has rights and time is valid.
\t*/
\tfunction _hasRight (
\t\taddress _address,
\t\tbytes32 _circumstance,
\t\tbytes32 _right
\t) internal view returns (bool) {
\t\treturn _permissions[_address][_circumstance][_right] > block.timestamp;
\t}
\t/**
\t\tSet the `_managerRight` whose `UNIVERSAL` holders may freely manage the
\t\tspecified `_managedRight`.
\t\t@param _managedRight The right which is to have its manager set to
\t\t\t`_managerRight`.
\t\t@param _managerRight The right whose `UNIVERSAL` holders may manage
\t\t\t`_managedRight`.
\t*/
\tfunction setManagerRight (
\t\tbytes32 _managedRight,
\t\tbytes32 _managerRight
\t) external virtual hasValidPermit(_UNIVERSAL, _MANAGER) {
\t\tif (_managedRight == _ZERO_RIGHT) {
\t\t\trevert ManagedRightNotSpecified();
\t\t}
\t\t_managerRights[_managedRight] = _managerRight;
\t\temit ManagementUpdated(msg.sender, _managedRight, _managerRight);
\t}
\t/**
\t\tSet the permit to a specific address under some circumstances. A permit may
\t\tonly be set by the super-administrative contract owner or an address holding
\t\tsome delegated management permit.
\t\t@param _address The address to assign the specified `_right` to.
\t\t@param _circumstance The circumstance in which the `_right` is valid.
\t\t@param _right The specific right to assign.
\t\t@param _expirationTime The time when the `_right` expires for the provided
\t\t\t`_circumstance`.
\t*/
\tfunction setPermit (
\t\taddress _address,
\t\tbytes32 _circumstance,
\t\tbytes32 _right,
\t\tuint256 _expirationTime
\t) public virtual hasValidPermit(_UNIVERSAL, _managerRights[_right]) {
\t\tif(_right == _ZERO_RIGHT) {
\t\t\trevert RightNotSpecified();
\t\t}
\t\t_permissions[_address][_circumstance][_right] = _expirationTime;
\t\temit PermitUpdated(
\t\t\tmsg.sender,
\t\t\t_address,
\t\t\t_circumstance,
\t\t\t_right,
\t\t\t_expirationTime
\t\t);
\t}
\t/**
\t\tDetermine whether or not an address has some rights under the given
\t\tcircumstance, and if they do have the right, until when.
\t\t@param _address The address to check for the specified `_right`.
\t\t@param _circumstance The circumstance to check the specified `_right` for.
\t\t@param _right The right to check for validity.
\t\t@return The timestamp in seconds when the `_right` expires. If the timestamp
\t\t\tis zero, we can assume that the user never had the right.
\t*/
\tfunction hasRightUntil (
\t\taddress _address,
\t\tbytes32 _circumstance,
\t\tbytes32 _right
\t) public view returns (uint256) {
\t\treturn _permissions[_address][_circumstance][_right];
\t}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
import {
\tIERC721
} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {
\tIERC1155
} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {
\tIERC20,
\tSafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
\tPermitControl
} from "./access/PermitControl.sol";
/**
\tThrown in the event that attempting to rescue an asset from the contract
\tfails.
\t@param index The index of the asset whose rescue failed.
*/
error RescueFailed (uint256 index);
/**
\t@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
\t@title Escape Hatch
\t@author Rostislav Khlebnikov <@catpic5buck>
\t@custom:contributor Tim Clancy <@_Enoch>
\t
\tThis contract contains logic for pausing contract operations during updates
\tand a backup mechanism for user assets restoration.
*/
abstract contract EscapeHatch is PermitControl {
\tusing SafeERC20 for IERC20;
\t/// The public identifier for the right to rescue assets.
\tbytes32 internal constant _ASSET_RESCUER = keccak256("ASSET_RESCUER");
\t/**
\t\tAn enum type representing the status of the contract being escaped.
\t\t@param None A default value used to avoid setting storage unnecessarily.
\t\t@param Unpaused The contract is unpaused.
\t\t@param Paused The contract is paused.
\t*/
\tenum Status {
\t\tNone,
\t\tUnpaused,
\t\tPaused
\t}
\t/**
\t\tAn enum type representing the type of asset this contract may be dealing
\t\twith.
\t\t@param Native The type for Ether.
\t\t@param ERC20 The type for an ERC-20 token.
\t\t@param ERC721 The type for an ERC-721 token.
\t\t@param ERC1155 The type for an ERC-1155 token.
\t*/
\tenum AssetType {
\t\tNative,
\t\tERC20,
\t\tERC721,
\t\tERC1155
\t}
\t/**
\t\tA struct containing information about a particular asset transfer.
\t\t@param assetType The type of the asset involved.
\t\t@param asset The address of the asset.
\t\t@param id The ID of the asset.
\t\t@param amount The amount of asset being transferred.
\t\t@param to The destination address where the asset is being sent.
\t*/
\tstruct Asset {
\t\tAssetType assetType;
\t\taddress asset;
\t\tuint256 id;
\t\tuint256 amount;
\t\taddress to;
\t}
\t/// A flag to track whether or not the contract is paused.
\tStatus internal _status = Status.Unpaused;
\t/**
\t\tConstruct a new instance of an escape hatch, which supports pausing and the
\t\trescue of trapped assets.
\t\t@param _rescuer The address of the rescuer caller that can pause, unpause,
\t\t\tand rescue assets.
\t*/
\tconstructor (
\t\taddress _rescuer
\t) {
\t\t// Set the permit for the rescuer.
\t\tsetPermit(_rescuer, _UNIVERSAL, _ASSET_RESCUER, type(uint256).max);
\t}
\t/// An administrative function to pause the contract.
\tfunction pause () external hasValidPermit(_UNIVERSAL, _ASSET_RESCUER) {
\t\t_status = Status.Paused;
\t}
\t/// An administrative function to resume the contract.
\tfunction unpause () external hasValidPermit(_UNIVERSAL, _ASSET_RESCUER) {
\t\t_status = Status.Unpaused;
\t}
\t/// Return the magic value signifying the ability to receive ERC-721 items.
\tfunction onERC721Received (
\t\taddress,
\t\taddress,
\t\tuint256,
\t\tbytes memory
\t) public pure returns (bytes4) {
\t\treturn bytes4(
\t\t\tkeccak256(
\t\t\t\t"onERC721Received(address,address,uint256,bytes)"
\t\t\t)
\t\t);
\t}
\t/// Return the magic value signifying the ability to receive ERC-1155 items.
\tfunction onERC1155Received (
\t\taddress,
\t\taddress,
\t\tuint256,
\t\tuint256,
\t\tbytes memory
\t) public pure returns (bytes4) {
\t\treturn bytes4(
\t\t\tkeccak256(
\t\t\t\t"onERC1155Received(address,address,uint256,uint256,bytes)"
\t\t\t)
\t\t);
\t}
\t/// Return the magic value signifying the ability to batch receive ERC-1155.
\tfunction onERC1155BatchReceived (
\t\taddress,
\t\taddress,
\t\tuint256[] memory,
\t\tuint256[] memory,
\t\tbytes memory
\t) public pure returns (bytes4) {
\t\treturn bytes4(
\t\t\tkeccak256(
\t\t\t\t"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"
\t\t\t)
\t\t);
\t}
\t/**
\t\tAn admin function used in emergency situations to transfer assets from this
\t\tcontract if they get stuck.
\t\t@param _assets An array of `Asset` structs to attempt transfers.
\t\t@custom:throws RescueFailed if an Ether asset could not be rescued.
\t*/
\tfunction rescueAssets (
\t\tAsset[] calldata _assets
\t) external hasValidPermit(_UNIVERSAL, _ASSET_RESCUER) {
\t\tfor (uint256 i; i < _assets.length; ) {
\t\t\t// If the asset is Ether, attempt a rescue; skip on reversion.
\t\t\tif (_assets[i].assetType == AssetType.Native) {
\t\t\t\t(bool result, ) = _assets[i].to.call{ value: _assets[i].amount }("");
\t\t\t\tif (!result) {
\t\t\t\t\trevert RescueFailed(i);
\t\t\t\t}
\t\t\t\tunchecked {
\t\t\t\t\t++i;
\t\t\t\t}
\t\t\t\tcontinue;
\t\t\t}
\t\t\t// Attempt to rescue ERC-20 items.
\t\t\tif (_assets[i].assetType == AssetType.ERC20) {
\t\t\t\tIERC20(_assets[i].asset).safeTransfer(
\t\t\t\t\t_assets[i].to,
\t\t\t\t\t_assets[i].amount
\t\t\t\t);
\t\t\t}
\t\t\t// Attempt to rescue ERC-721 items.
\t\t\tif (_assets[i].assetType == AssetType.ERC721) {
\t\t\t\tIERC721(_assets[i].asset).transferFrom(
\t\t\t\t\taddress(this),
\t\t\t\t\t_assets[i].to,
\t\t\t\t\t_assets[i].id
\t\t\t\t);
\t\t\t}
\t\t\t// Attempt to rescue ERC-1155 items.
\t\t\tif (_assets[i].assetType == AssetType.ERC1155) {
\t\t\t\tIERC1155(_assets[i].asset).safeTransferFrom(
\t\t\t\t\taddress(this),
\t\t\t\t\t_assets[i].to,
\t\t\t\t\t_assets[i].id,
\t\t\t\t\t_assets[i].amount,
\t\t\t\t\t""
\t\t\t\t);
\t\t\t}
\t\t\tunchecked {
\t\t\t\t++i;
\t\t\t}
\t\t}
\t}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
import {
\tEscapeHatch
} from "./EscapeHatch.sol";
import {
\tItemOrigin
} from "../interfaces/ISuperVerseStaker.sol";
/**
\tThrown when attempting to set item values with unequal argument arrays lengths.
*/
error CantConfigureItemValues ();
/**
\t@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
\t@title SuperVerseDAO staking contract.
\t@author throw; <@0xthrpw>
\t@author Tim Clancy <@_Enoch>
\t@author Rostislav Khlebnikov <@catpic5buck>
\tThis contract provides methods for configuring the SuperVerseDAO staking
\tcontract
\t@custom:date May 15th, 2023.
*/
contract StakerConfig is EscapeHatch {
\t/// The identifier for the right to configure emission rates and the DAO tax.
\tbytes32 constant private _CONFIG_ITEM_VALUES =
\t\tkeccak256("CONFIG_ITEM_VALUES");
\t/// The identifier for the right to configure the length of reward emission.
\tbytes32 constant private _CONFIG_WINDOW =
\t\tkeccak256("CONFIG_WINDOW");
\t/// The address of the Elliotrades NFT collection
\taddress immutable public ET_COLLECTION;
\t/// The address of the SuperFarm NFT collection
\taddress immutable public SF_COLLECTION;
\t/// The address of the ERC20 staking token
\taddress immutable public TOKEN;
\t/// The amount of time for which rewards are emitted
\tuint256 public immutable REWARD_PERIOD;
\t/// The timestamp of when rebase can next be called
\tuint256 public nextRebaseTimestamp;
\t/// The minimum amount of seconds between rebase calls
\tuint256 public rebaseCooldown;
\t/// collection type > group id > equivalent token amount
\tmapping( ItemOrigin => mapping ( uint256 => uint128 ) ) public itemValues;
\t/// user address > timestamp of last stake operation
\tmapping ( address => uint256 ) public stakeTimestamps;
\t/**
\t Construct a new instance of a SuperVerse staking configuration with the
\t following parameters.
\t @param _etCollection The address of the Elliotrades NFT collection
\t @param _sfCollection The address of the SuperFarm NFT collection
\t @param _token The address of the staking erc20 token
\t @param _rewardPeriod The length of time rewards are emitted
\t*/
\tconstructor(
\t\taddress _etCollection,
\t\taddress _sfCollection,
\t\taddress _token,
\t\tuint256 _rewardPeriod
\t) EscapeHatch (
\t\tmsg.sender
\t) {
\t\tET_COLLECTION = _etCollection;
\t\tSF_COLLECTION = _sfCollection;
\t\tTOKEN = _token;
\t\tREWARD_PERIOD = _rewardPeriod;
\t\trebaseCooldown = 1 weeks;
\t}
\t/**
\t\tThis function allows a permitted user to configure the equivalent token
\t\tvalues available for each item rarity/type.
\t\t@param _assetType The type of asset whose timelock options are being
\t\t\tconfigured.
\t\t@param _groupIds An array with IDs for specific rewards
\t\t\tavailable under `_assetType`.
\t\t@param _values An array keyed to `_groupIds` containing the token
\t\t\tvalue for the group id
\t*/
\tfunction configureItemValues (
\t\tItemOrigin _assetType,
\t\tuint256[] memory _groupIds,
\t\tuint128[] memory _values
\t) external hasValidPermit(_UNIVERSAL, _CONFIG_ITEM_VALUES) {
\t\tif (_groupIds.length != _values.length) {
\t\t\trevert CantConfigureItemValues();
\t\t}
\t\tfor (uint256 i; i < _groupIds.length; ) {
\t\t\titemValues[_assetType][_groupIds[i]] = _values[i];
\t\t\tunchecked { ++i; }
\t\t}
\t}
\t/**
\t
\t*/
\tfunction setRebaseCooldown (
\t\tuint256 _rebaseCooldown
\t) external hasValidPermit(_UNIVERSAL, _CONFIG_WINDOW) {
\t\trebaseCooldown = _rebaseCooldown;
\t}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
using ItemsHelper for ItemsById global;
library ItemsHelper {
\tfunction add(
\t\tItemsById storage _items,
\t\tuint256 _tokenId
\t) internal {
\t\t_items.array.push(_tokenId);
\t\t_items.idx[_tokenId] = _items.array.length;
\t}
\tfunction remove(
\t\tItemsById storage _items,
\t\tuint256 _tokenId
\t) internal {
\t\tuint256 arrayIdx = _items.idx[_tokenId] - 1;
\t\tuint256 lastIdx = _items.array.length - 1;
\t\tif (arrayIdx != lastIdx) {
\t\t\tuint256 lastElement = _items.array[lastIdx];
\t\t\t_items.array[arrayIdx] = lastElement;
\t\t\t_items.idx[lastElement] = arrayIdx + 1;
\t\t}
\t\t_items.array.pop();
\t\tdelete _items.idx[_tokenId];
\t}
\tfunction exists(
\t\tItemsById storage _items,
\t\tuint256 _tokenId
\t) internal view returns (bool) {
\t\treturn _items.idx[_tokenId] != 0;
\t}
}
/*
\tStaked item storage alignment.
*/
struct ItemsById {
\tuint256[] array;
\tmapping ( uint256 => uint256 ) idx;
}
uint256 constant SINGLE_ITEM = 1;
uint256 constant PRECISION = 1e12;
uint256 constant WITHDRAW_BUFFER = 1 minutes;// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
import {
\tReentrancyGuard
} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {
\tIERC20,
\tSafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
\tIFee1155
} from "./interfaces/IFee1155.sol";
import {
\tItemOrigin,
\tISuperVerseStaker
} from "./interfaces/ISuperVerseStaker.sol";
import {
\tStakerConfig
} from "./lib/StakerConfig.sol";
import {
\tItemsById,
\tPRECISION,
\tSINGLE_ITEM,
\tWITHDRAW_BUFFER
} from "./lib/TypesAndConstants.sol";
/**
\t@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
\t@title SuperVerseDAO staking contract.
\t@author throw; <@0xthrpw>
\t@author Tim Clancy <tim-clancy.eth>
\t@author Rostislav Khlebnikov <@catpic5buck>
\tThis contract allows callers to stake SUPER tokens and items from the
\tEllioTrades and Superfarm NFT Collections and earn rewards in ETH. It uses
\ta point based system and has a mechanism for 'rebasing' the reward emission
\trate to distribute the contract's reward balance over a specified reward
\tperiod.
\t@custom:date May 15th, 2023.
*/
contract SuperVerseStaker is
\tISuperVerseStaker, StakerConfig, ReentrancyGuard
{
\tusing SafeERC20 for IERC20;
\t/**
\t\tThis struct defines a user's staked position
\t*/
\tstruct Staker {
\t\tuint256 stakerPower;
\t\tuint256 missedReward;
\t\tuint256 claimedReward;
\t\tuint256 stakedTokens;
\t\tItemsById ETs;
\t\tItemsById SFs;
\t}
\t/// user address > position
\tmapping ( address => Staker ) internal _stakers;
\t/// rewards distributed over reward period.
\tuint256 public reward;
/// rewards for previous reward windows.
\tuint256 public allProduced;
\t
/// total produced reward.
\tuint256 public producedReward;
\t
/// reward round beginning timestamp.
\tuint256 public producedTimestamp;
\t
/// rewards per power point.
\tuint256 public rpp;
\t
/// total power points.
\tuint256 public totalPower;
\t/**
\t\tConstruct a new instance of a SuperVerse staking contract with the
\t\tfollowing parameters.
\t\t@param _etCollection The address of the Elliotrades NFT collection
\t\t@param _sfCollection The address of the SuperFarm NFT collection
\t\t@param _token The address of the staking erc20 token
\t\t@param _rewardPeriod The length of time rewards are emitted
\t*/
\tconstructor(
\t\taddress _etCollection,
\t\taddress _sfCollection,
\t\taddress _token,
\t\tuint256 _rewardPeriod
\t) StakerConfig (
\t\t_etCollection,
\t\t_sfCollection,
\t\t_token,
\t\t_rewardPeriod
\t) { }
\t/**
\t\tHandle ETH reward deposits.
\t*/
\treceive () external payable{
\t\temit Fund(
\t\t\tmsg.sender,
\t\t\tmsg.value
\t\t);
\t}
\t/**
\t\tHelper function for calculating the total amount of reward emissions.
\t*/
\tfunction _produced () private view returns (uint256) {
\t\treturn allProduced +
\t\t\treward * (block.timestamp - producedTimestamp) / REWARD_PERIOD;
\t}
\t/**
\t\tHelper function that handles updating rewards per point and total
\t\tproducedReward.
\t*/
\tfunction _update () private {
\t\tuint256 current = _produced();
\t\tif (current > producedReward) {
\t\t\tuint256 difference = current - producedReward;
\t\t\tif (totalPower > 0) {
\t\t\t\trpp += difference * PRECISION / totalPower;
\t\t\t}
\t\t\tproducedReward += difference;
\t\t}
\t}
\t/**
\t\tCalculate pending reward for a given address
\t\t@param _recipient the user querying their rewards
\t\t@param _rpp current rewards per point
\t\t@return reward the amount of rewards the user is due
\t*/
\tfunction _calcReward (
\t\taddress _recipient,
\t\tuint256 _rpp
\t) private view returns(uint256) {
\t\tStaker storage staker = _stakers[_recipient];
\t\treturn staker.stakerPower * _rpp/ PRECISION -
\t\t\tstaker.claimedReward - staker.missedReward;
\t}
\t/**
\t\tA helper function for locking ERC20 and ERC1155 assets and
\t\tcalculating staker's gained power.
\t\t@param _erc20Amount Amount of ERC20 staking tokens.
\t\t@param _items An array of ERC1155 items being staked.
\t\t@param _staker A storage pointer to staker.
\t\t@return power A sum of all assets power.
\t*/
\tfunction _addAssets (
\t\tuint256 _erc20Amount,
\t\tInputItem[] calldata _items,
\t\tStaker storage _staker
\t) private returns (uint256 power) {
\t\t/// Handle ERC20 tokens
\t\tIERC20(TOKEN).safeTransferFrom(
\t\t\tmsg.sender,
\t\t\taddress(this),
\t\t\t_erc20Amount
\t\t);
\t\tpower = _erc20Amount;
\t\t
\t\tfor (uint256 i; i < _items.length; ){
\t\t\t
\t\t\tif (_items[i].origin == ItemOrigin.SF1155) {
\t\t\t\tif (_staker.SFs.exists(_items[i].itemId)) {
\t\t\t\t\trevert ItemAlreadyStaked();
\t\t\t\t}
\t\t\t\tIFee1155(SF_COLLECTION).safeTransferFrom(
\t\t\t\t\tmsg.sender,
\t\t\t\t\taddress(this),
\t\t\t\t\t_items[i].itemId,
\t\t\t\t\tSINGLE_ITEM,
\t\t\t\t\t""
\t\t\t\t);
\t\t\t\t_staker.SFs.add(_items[i].itemId);
\t\t\t}
\t\t\tif (_items[i].origin == ItemOrigin.ET1155) {
\t\t\t\t
\t\t\t\tif (_staker.ETs.exists(_items[i].itemId)) {
\t\t\t\t\trevert ItemAlreadyStaked();
\t\t\t\t}
\t\t\t\tIFee1155(ET_COLLECTION).safeTransferFrom(
\t\t\t\t\tmsg.sender,
\t\t\t\t\taddress(this),
\t\t\t\t\t_items[i].itemId,
\t\t\t\t\tSINGLE_ITEM,
\t\t\t\t\t""
\t\t\t\t);
\t\t\t\t_staker.ETs.add(_items[i].itemId);
\t\t\t}
\t\t\t//get item id and parse group id
\t\t\tuint256 grpId = _items[i].itemId >> 128;
\t\t\tunchecked {
\t\t\t\t//add value from group id in item reward mapping
\t\t\t\tpower += itemValues[_items[i].origin][grpId];
\t\t\t\t++i;
\t\t\t}
\t\t}
\t}
\t/**
\t A helper function for retrieving ERC20 and ERC1155 assets and
\t\tcalculating staker's lost power.
\t\t@param _erc20Amount Amount of ERC20 staking tokens.
\t\t@param _items An array of ERC1155 items being staked.
\t\t@param _staker A storage pointer to staker.
\t\t@return power A sum of all assets power.
\t*/
\tfunction _removeAssets (
\t\tuint256 _erc20Amount,
\t\tInputItem[] calldata _items,
\t\tStaker storage _staker
\t) private returns (uint256 power) {
\t\tif (_erc20Amount > _staker.stakedTokens) {
\t\t\trevert AmountExceedsStakedAmount();
\t\t}
\t\t/// Handle ERC20 tokens
\t\tIERC20(TOKEN).safeTransfer(
\t\t\tmsg.sender,
\t\t\t_erc20Amount
\t\t);
\t\tpower = _erc20Amount;
\t\t
\t\tfor (uint256 i; i < _items.length; ){
\t\t\t
\t\t\tif (_items[i].origin == ItemOrigin.SF1155) {
\t\t\t\tif (!_staker.SFs.exists(_items[i].itemId)) {
\t\t\t\t\trevert ItemNotFound();
\t\t\t\t}
\t\t\t\tIFee1155(SF_COLLECTION).safeTransferFrom(
\t\t\t\t\taddress(this),
\t\t\t\t\tmsg.sender,
\t\t\t\t\t_items[i].itemId,
\t\t\t\t\tSINGLE_ITEM,
\t\t\t\t\t""
\t\t\t\t);
\t\t\t\t_staker.SFs.remove(_items[i].itemId);
\t\t\t}
\t\t\tif (_items[i].origin == ItemOrigin.ET1155) {
\t\t\t\t
\t\t\t\tif (!_staker.ETs.exists(_items[i].itemId)) {
\t\t\t\t\trevert ItemNotFound();
\t\t\t\t}
\t\t\t\tIFee1155(ET_COLLECTION).safeTransferFrom(
\t\t\t\t\taddress(this),
\t\t\t\t\tmsg.sender,
\t\t\t\t\t_items[i].itemId,
\t\t\t\t\tSINGLE_ITEM,
\t\t\t\t\t""
\t\t\t\t);
\t\t\t\t_staker.ETs.remove(_items[i].itemId);
\t\t\t}
\t\t\t//get item id and parse group id
\t\t\tuint256 grpId = _items[i].itemId >> 128;
\t\t\tunchecked {
\t\t\t\t//add value from group id in item reward mapping
\t\t\t\tpower += itemValues[_items[i].origin][grpId];
\t\t\t\t++i;
\t\t\t}
\t\t}
\t}
\t/**
\t\tHelper function that handles updating reward ratio and distributes
\t\trewards to the user
\t*/
\tfunction _claim () private {
\t\t_update();
\t\tuint256 rewardAmount = _calcReward(msg.sender, rpp);
\t\tif (rewardAmount == 0) {
\t\t\treturn;
\t\t}
\t\t(bool success,) = msg.sender.call{value: rewardAmount}("");
\t\tif (!success) {
\t\t\trevert RewardPayoutFailed();
\t\t}
\t\tunchecked {
\t\t\t_stakers[msg.sender].claimedReward += rewardAmount;
\t\t}
\t\t
\t\temit Claim(msg.sender, rewardAmount);
\t}
\t/**
\t\tStake ERC20 tokens and items from specified collections. The amount of
\t\tERC20 tokens can be zero as long as at least one item is staked.
\t\tSimilarly, the amount of items being staked can be zero as long as the
\t\tuser is staking ERC20 tokens. Tokens can be staked on a user's behalf,
\t\tprovided the caller has the necessary approvals for transfers by the user
\t\t@param _amount The amount of ERC20 tokens being staked
\t\t@param _user The address of the user staking tokens
\t\t@param _items The array of items being staked
\t*/
\tfunction stake (
\t\tuint256 _amount,
\t\taddress _user,
\t\tInputItem[] calldata _items
\t) external nonReentrant {
\t\tif(_amount == 0 && _items.length == 0){
\t\t\trevert BadArguments();
\t\t}
\t\tStaker storage staker = _stakers[_user];
\t\tstakeTimestamps[_user] = block.timestamp;
\t\tuint256 power = _addAssets(_amount, _items, staker);
\t\t_update();
\t\t/// Update balance and positions
\t\tunchecked {
\t\t\tstaker.stakedTokens += _amount;
\t\t\tstaker.stakerPower += power;
\t\t\tstaker.missedReward += power * rpp / PRECISION;
\t\t\ttotalPower += power;
\t\t}
\t\temit Stake(
\t\t\t_user,
\t\t\t_amount,
\t\t\tpower,
\t\t\t_items
\t\t);
\t}
\t/**
\t\tWithdraw ERC20 tokens and items from specified collections and
\t\tdistribute rewards to the caller.
\t\t@param _amount The amount of ERC20 tokens to withdraw
\t\t@param _items The array of items to withdraw
\t*/
\tfunction withdraw (
\t\tuint256 _amount,
\t\tInputItem[] calldata _items
\t) external nonReentrant {
\t\tif(_amount == 0 && _items.length == 0){
\t\t\trevert BadArguments();
\t\t}
\t\tif( block.timestamp - WITHDRAW_BUFFER < stakeTimestamps[msg.sender]){
\t\t\trevert WithdrawBufferNotFinished();
\t\t}
\t\tStaker storage staker = _stakers[msg.sender];
\t\tuint256 lostPower = _removeAssets(_amount, _items, staker);
\t\t_claim();
\t\tuint256 difference = staker.stakerPower - lostPower;
\t\tunchecked {
\t\t\tstaker.stakedTokens -= _amount;
\t\t\tstaker.stakerPower = difference;
\t\t\tstaker.missedReward = difference * rpp / PRECISION;
\t\t\ttotalPower -= lostPower;
\t\t}
\t\tdelete staker.claimedReward;
\t\temit Withdraw(
\t\t\tmsg.sender,
\t\t\t_amount,
\t\t\tlostPower,
\t\t\t_items
\t\t);
\t}
\t/**
\t\tHelper function that handles updating reward ratio and distributes
\t\trewards to the user
\t*/
\tfunction claim () external nonReentrant {
\t\t_claim();
\t}
\t/**
\t\tUpdate produced reward amounts and adjust the reward rate to emit
\t\trewards for the entirety of the REWARD_PERIOD. This function has a cool
\t\tdown period and can only be called at a minimum frequency of
\t\trebaseCooldown seconds.
\t*/
\tfunction rebase () external {
\t\tif( block.timestamp < nextRebaseTimestamp ){
\t\t\trevert RebaseWindowClosed();
\t\t}
\t\tallProduced = _produced();
\t\treward = address(this).balance;
\t\tproducedTimestamp = block.timestamp;
\t\tnextRebaseTimestamp = block.timestamp + rebaseCooldown;
\t}
\tfunction availableReward (address _staker) public view returns (uint256) {
\t\tuint256 rpp_virtual = rpp;
\t\tuint256 current = _produced();
\t\tuint256 difference = current - producedReward;
\t\tif (totalPower > 0) {
\t\t\trpp_virtual += difference * PRECISION / totalPower;
\t\t}
\t\treturn _calcReward(_staker, rpp_virtual);
\t}
\t/**
\t\tView function for retrieving a user's staking position data
\t\t@param _staker the address of the user
\t\t@return stakerPower the total power of all staking postions
\t\t@return stakedTokens the amount of ERC20 tokens the user has staked
\t\t@return claimedReward the amount of ERC20 tokens the user had claimed
\t\t@return missedReward the amount of ERC20 tokens the user missed
\t\t@return availableToClaim the amount of the rewards the user can claim
\t\t@return idsET the user's staked items from the ET Collection
\t\t@return idsSFs the user's staked items from the SF Collection
\t*/
\tfunction stakerInfo (
\t\taddress _staker
\t) external view returns (
\t\tuint256 stakerPower,
\t\tuint256 stakedTokens,
\t\tuint256 claimedReward,
\t\tuint256 missedReward,
\t\tuint256 availableToClaim,
\t\tuint256[] memory idsET,
\t\tuint256[] memory idsSFs
\t) {
\t\tStaker storage staker = _stakers[_staker];
\t\tavailableToClaim = availableReward(_staker);
\t\tstakerPower = staker.stakerPower;
\t\tstakedTokens = staker.stakedTokens;
\t\tclaimedReward = staker.claimedReward;
\t\tmissedReward = staker.missedReward;
\t\tidsET = staker.ETs.array;
\t\tidsSFs = staker.SFs.array;
\t}
}
File 2 of 2: Token
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
@title A basic ERC-20 token with voting functionality.
@author Tim Clancy
This contract is used when deploying SuperFarm ERC-20 tokens.
This token is created with a fixed, immutable cap and includes voting rights.
Voting functionality is copied and modified from Sushi, and in turn from YAM:
https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
Which is in turn copied and modified from COMPOUND:
https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
*/
contract Token is ERC20Capped, Ownable {
/// A version number for this Token contract's interface.
uint256 public version = 1;
/**
Construct a new Token by providing it a name, ticker, and supply cap.
@param _name The name of the new Token.
@param _ticker The ticker symbol of the new Token.
@param _cap The supply cap of the new Token.
*/
constructor (string memory _name, string memory _ticker, uint256 _cap) public ERC20(_name, _ticker) ERC20Capped(_cap) { }
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
Allows Token creator to mint `_amount` of this Token to the address `_to`.
New tokens of this Token cannot be minted if it would exceed the supply cap.
Users are delegated votes when they are minted Token.
@param _to the address to mint Tokens to.
@param _amount the amount of new Token to mint.
*/
function mint(address _to, uint256 _amount) external onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/**
Allows users to transfer tokens to a recipient, moving delegated votes with
the transfer.
@param recipient The address to transfer tokens to.
@param amount The amount of tokens to send to `recipient`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
_moveDelegates(_delegates[msg.sender], _delegates[recipient], amount);
return true;
}
/// @dev A mapping to record delegates for each address.
mapping (address => address) internal _delegates;
/// A checkpoint structure to mark some number of votes from a given block.
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// A mapping to record indexed Checkpoint votes for each address.
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// A mapping to record the number of Checkpoints for each address.
mapping (address => uint32) public numCheckpoints;
/// The EIP-712 typehash for the contract's domain.
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// The EIP-712 typehash for the delegation struct used by the contract.
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// A mapping to record per-address states for signing / validating signatures.
mapping (address => uint) public nonces;
/// An event emitted when an address changes its delegate.
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// An event emitted when the vote balance of a delegated address changes.
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
Return the address delegated to by `delegator`.
@return The address delegated to by `delegator`.
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
Delegate votes from `msg.sender` to `delegatee`.
@param delegatee The address to delegate votes to.
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
Delegate votes from signatory to `delegatee`.
@param delegatee The address to delegate votes to.
@param nonce The contract state required for signature matching.
@param expiry The time at which to expire the signature.
@param v The recovery byte of the signature.
@param r Half of the ECDSA signature pair.
@param s Half of the ECDSA signature pair.
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)));
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry));
bytes32 digest = keccak256(
abi.encodePacked(
"\\x19\\x01",
domainSeparator,
structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Invalid signature.");
require(nonce == nonces[signatory]++, "Invalid nonce.");
require(now <= expiry, "Signature expired.");
return _delegate(signatory, delegatee);
}
/**
Get the current votes balance for the address `account`.
@param account The address to get the votes balance of.
@return The number of current votes for `account`.
*/
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
Determine the prior number of votes for an address as of a block number.
@dev The block number must be a finalized block or else this function will revert to prevent misinformation.
@param account The address to check.
@param blockNumber The block number to get the vote balance at.
@return The number of votes the account had as of the given block.
*/
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "The specified block is not yet finalized.");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check the most recent balance.
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Then check the implicit zero balance.
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/**
An internal function to actually perform the delegation of votes.
@param delegator The address delegating to `delegatee`.
@param delegatee The address receiving delegated votes.
*/
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
/* console.log('a-', currentDelegate, delegator, delegatee); */
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
/**
An internal function to move delegated vote amounts between addresses.
@param srcRep the previous representative who received delegated votes.
@param dstRep the new representative to receive these delegated votes.
@param amount the amount of delegated votes to move between representatives.
*/
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
// Decrease the number of votes delegated to the previous representative.
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
// Increase the number of votes delegated to the new representative.
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
/**
An internal function to write a checkpoint of modified vote amounts.
This function is guaranteed to add at most one checkpoint per block.
@param delegatee The address whose vote count is changed.
@param nCheckpoints The number of checkpoints by address `delegatee`.
@param oldVotes The prior vote count of address `delegatee`.
@param newVotes The new vote count of address `delegatee`.
*/
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Block number exceeds 32 bits.");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
/**
A function to safely limit a number to less than 2^32.
@param n the number to limit.
@param errorMessage the error message to revert with should `n` be too large.
@return The number `n` limited to 32 bits.
*/
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
/**
A function to return the ID of the contract's particular network or chain.
@return The ID of the contract's network or chain.
*/
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20Capped is ERC20 {
using SafeMath for uint256;
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap_) internal {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = 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");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 GSN 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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool);
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}