¡El código fuente de este contrato está verificado!
Metadatos del Contrato
Compilador
0.8.11+commit.d7f03943
Idioma
Solidity
Código Fuente del Contrato
Archivo 1 de 26: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^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.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Código Fuente del Contrato
Archivo 2 de 26: Counters.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)pragmasolidity ^0.8.0;/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/libraryCounters{
structCounter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add// this feature: see https://github.com/ethereum/solidity/issues/4637uint256 _value; // default: 0
}
functioncurrent(Counter storage counter) internalviewreturns (uint256) {
return counter._value;
}
functionincrement(Counter storage counter) internal{
unchecked {
counter._value +=1;
}
}
functiondecrement(Counter storage counter) internal{
uint256 value = counter._value;
require(value >0, "Counter: decrement overflow");
unchecked {
counter._value = value -1;
}
}
functionreset(Counter storage counter) internal{
counter._value =0;
}
}
Código Fuente del Contrato
Archivo 3 de 26: ECDSA.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)pragmasolidity ^0.8.0;import"../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/libraryECDSA{
enumRecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function_throwError(RecoverError error) privatepure{
if (error == RecoverError.NoError) {
return; // no error: do nothing
} elseif (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} elseif (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} elseif (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} elseif (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash, bytesmemory signature) internalpurereturns (address, RecoverError) {
// Check the signature length// - case 65: r,s,v signature (standard)// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._if (signature.length==65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly.assembly {
r :=mload(add(signature, 0x20))
s :=mload(add(signature, 0x40))
v :=byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} elseif (signature.length==64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly.assembly {
r :=mload(add(signature, 0x20))
vs :=mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/functionrecover(bytes32 hash, bytesmemory signature) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address, RecoverError) {
bytes32 s = vs &bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v =uint8((uint256(vs) >>255) +27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/functionrecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internalpurereturns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most// signatures from current libraries generate a unique signature with an s-value in the lower half order.//// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept// these malleable signatures as well.if (uint256(s) >0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v !=27&& v !=28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer addressaddress signer =ecrecover(hash, v, r, s);
if (signer ==address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/functionrecover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytes32 hash) internalpurereturns (bytes32) {
// 32 is the length in bytes of hash,// enforced by the type signature abovereturnkeccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytesmemory s) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/functiontoTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
Código Fuente del Contrato
Archivo 4 de 26: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Código Fuente del Contrato
Archivo 5 de 26: ERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)pragmasolidity ^0.8.0;import"./IERC20.sol";
import"./extensions/IERC20Metadata.sol";
import"../../utils/Context.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 Contracts guidelines: functions revert
* instead 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}.
*/contractERC20isContext, IERC20, IERC20Metadata{
mapping(address=>uint256) private _balances;
mapping(address=>mapping(address=>uint256)) private _allowances;
uint256private _totalSupply;
stringprivate _name;
stringprivate _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
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 this function is
* overridden;
*
* 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}.
*/functiondecimals() publicviewvirtualoverridereturns (uint8) {
return18;
}
/**
* @dev See {IERC20-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/functionbalanceOf(address account) publicviewvirtualoverridereturns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/functiontransfer(address to, uint256 amount) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
returntrue;
}
/**
* @dev See {IERC20-allowance}.
*/functionallowance(address owner, address spender) publicviewvirtualoverridereturns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionapprove(address spender, uint256 amount) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
returntrue;
}
/**
* @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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/functiontransferFrom(addressfrom,
address to,
uint256 amount
) publicvirtualoverridereturns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
returntrue;
}
/**
* @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.
*/functionincreaseAllowance(address spender, uint256 addedValue) publicvirtualreturns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
returntrue;
}
/**
* @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`.
*/functiondecreaseAllowance(address spender, uint256 subtractedValue) publicvirtualreturns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
returntrue;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/function_transfer(addressfrom,
address to,
uint256 amount
) internalvirtual{
require(from!=address(0), "ERC20: transfer from the zero address");
require(to !=address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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:
*
* - `account` cannot be the zero address.
*/function_mint(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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) internalvirtual{
require(account !=address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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
) internalvirtual{
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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/function_spendAllowance(address owner,
address spender,
uint256 amount
) internalvirtual{
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance !=type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @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 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(addressfrom,
address to,
uint256 amount
) internalvirtual{}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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_afterTokenTransfer(addressfrom,
address to,
uint256 amount
) internalvirtual{}
}
Código Fuente del Contrato
Archivo 6 de 26: ERC20Votes.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Votes.sol)pragmasolidity ^0.8.0;import"./draft-ERC20Permit.sol";
import"../../../utils/math/Math.sol";
import"../../../governance/utils/IVotes.sol";
import"../../../utils/math/SafeCast.sol";
import"../../../utils/cryptography/ECDSA.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
*
* _Available since v4.2._
*/abstractcontractERC20VotesisIVotes, ERC20Permit{
structCheckpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32privateconstant _DELEGATION_TYPEHASH =keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address=>address) private _delegates;
mapping(address=> Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/functioncheckpoints(address account, uint32 pos) publicviewvirtualreturns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/functionnumCheckpoints(address account) publicviewvirtualreturns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/functiondelegates(address account) publicviewvirtualoverridereturns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/functiongetVotes(address account) publicviewvirtualoverridereturns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos ==0 ? 0 : _checkpoints[account][pos -1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/functiongetPastVotes(address account, uint256 blockNumber) publicviewvirtualoverridereturns (uint256) {
require(blockNumber <block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/functiongetPastTotalSupply(uint256 blockNumber) publicviewvirtualoverridereturns (uint256) {
require(blockNumber <block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/function_checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) privateviewreturns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.//// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not// out of bounds (in which case we're looking too far in the past and the result is 0).// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out// the same.uint256 high = ckpts.length;
uint256 low =0;
while (low < high) {
uint256 mid = Math.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid +1;
}
}
return high ==0 ? 0 : ckpts[high -1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/functiondelegate(address delegatee) publicvirtualoverride{
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/functiondelegateBySig(address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtualoverride{
require(block.timestamp<= expiry, "ERC20Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/function_maxSupply() internalviewvirtualreturns (uint224) {
returntype(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/function_mint(address account, uint256 amount) internalvirtualoverride{
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/function_burn(address account, uint256 amount) internalvirtualoverride{
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/function_afterTokenTransfer(addressfrom,
address to,
uint256 amount
) internalvirtualoverride{
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/function_delegate(address delegator, address delegatee) internalvirtual{
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function_moveVotingPower(address src,
address dst,
uint256 amount
) private{
if (src != dst && amount >0) {
if (src !=address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst !=address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function_writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) viewreturns (uint256) op,
uint256 delta
) privatereturns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos ==0 ? 0 : ckpts[pos -1].votes;
newWeight = op(oldWeight, delta);
if (pos >0&& ckpts[pos -1].fromBlock ==block.number) {
ckpts[pos -1].votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
}
}
function_add(uint256 a, uint256 b) privatepurereturns (uint256) {
return a + b;
}
function_subtract(uint256 a, uint256 b) privatepurereturns (uint256) {
return a - b;
}
}
Código Fuente del Contrato
Archivo 7 de 26: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^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}.
*/interfaceIERC165{
/**
* @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.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Código Fuente del Contrato
Archivo 8 de 26: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (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.
*/functiontransfer(address to, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (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.
*/functionapprove(address spender, uint256 amount) externalreturns (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.
*/functiontransferFrom(addressfrom,
address to,
uint256 amount
) externalreturns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
}
Código Fuente del Contrato
Archivo 9 de 26: IERC20Metadata.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Código Fuente del Contrato
Archivo 10 de 26: IERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (address owner);
/**
* @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 be 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.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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.
*/functiontransferFrom(addressfrom,
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.
*/functionapprove(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @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.
*/functionsetApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
/**
* @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.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytescalldata data
) external;
}
Código Fuente del Contrato
Archivo 11 de 26: IERC721Receiver.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.0;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
Código Fuente del Contrato
Archivo 12 de 26: INFTWEscrow.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.2;import"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import"@openzeppelin/contracts/utils/introspection/IERC165.sol";
import"@openzeppelin/contracts/token/ERC20/IERC20.sol";
interfaceINFTWEscrowisIERC165, IERC20, IERC721Receiver{
eventWeightUpdated(addressindexed user, bool increase, uint weight, uint timestamp);
eventWorldStaked(uint256indexed tokenId, addressindexed user);
eventWorldUnstaked(uint256indexed tokenId, addressindexed user);
eventRewardsSet(uint32 start, uint32 end, uint256 rate);
eventRewardsUpdated(uint32 start, uint32 end, uint256 rate);
eventRewardsPerWeightUpdated(uint256 accumulated);
eventUserRewardsUpdated(address user, uint256 userRewards, uint256 paidRewardPerWeight);
eventRewardClaimed(address receiver, uint256 claimed);
structWorldInfo {
uint16 weight; // weight based on rarityaddress owner; // staked to, otherwise owner == 0uint16 deposit; // unit is ether, paid in WRLD. The deposit is deducted from the last payment(s) since the deposit is non-custodialuint16 rentalPerDay; // unit is ether, paid in WRLD. Total is deposit + rentalPerDay * daysuint16 minRentDays; // must rent for at least min rent days, otherwise deposit is forfeited up to this amountuint32 rentableUntil; // timestamp in unix epoch
}
structRewardsPeriod {
uint32 start; // reward start time, in unix epochuint32 end; // reward end time, in unix epoch
}
structRewardsPerWeight {
uint32 totalWeight;
uint96 accumulated;
uint32 lastUpdated;
uint96 rate;
}
structUserRewards {
uint32 stakedWeight;
uint96 accumulated;
uint96 checkpoint;
}
// view functionsfunctiongetWorldInfo(uint tokenId) externalviewreturns(WorldInfo memory);
functioncheckUserRewards(address user) externalviewreturns(uint);
functiononERC721Received(address, address, uint256, bytescalldata) externalviewoverridereturns(bytes4);
// public functionsfunctioninitialStake(uint[] calldata tokenIds, uint[] calldata weights, address stakeTo,
uint16 _deposit, uint16 _rentalPerDay, uint16 _minRentDays, uint32 _rentableUntil, uint32 _maxTimestamp, bytescalldata _signature)
external;
functionstake(uint[] calldata tokenIds, address stakeTo,
uint16 _deposit, uint16 _rentalPerDay, uint16 _minRentDays, uint32 _rentableUntil)
external;
functionupdateRent(uint[] calldata tokenIds,
uint16 _deposit, uint16 _rentalPerDay, uint16 _minRentDays, uint32 _rentableUntil)
external;
functionextendRentalPeriod(uint tokenId, uint32 _rentableUntil) external;
functionunstake(uint[] calldata tokenIds, address unstakeTo) external;
functionclaim(address to) external;
}
Código Fuente del Contrato
Archivo 13 de 26: INFTWRental.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.2;import"@openzeppelin/contracts/utils/introspection/IERC165.sol";
interfaceINFTWRentalisIERC165{
eventWorldRented(uint256indexed tokenId, addressindexed tenant, uint256 payment);
eventRentalPaid(uint256indexed tokenId, addressindexed tenant, uint256 payment);
eventRentalTerminated(uint256indexed tokenId, addressindexed tenant);
structWorldRentInfo {
address tenant; // rented to, otherwise tenant == 0uint32 rentStartTime; // timestamp in unix epochuint32 rentalPaid; // total rental paid since the beginning including the deposituint32 paymentAlert; // alert time before next rent payment in seconds (used by frontend only)
}
functionisRentActive(uint tokenId) externalviewreturns(bool);
functiongetTenant(uint tokenId) externalviewreturns(address);
functionrentedByIndex(address tenant, uint index) externalviewreturns(uint);
functionisRentable(uint tokenId) externalviewreturns(bool state);
functionrentalPaidUntil(uint tokenId) externalviewreturns(uint paidUntil);
functionrentWorld(uint tokenId, uint32 _paymentAlert, uint32 initialPayment) external;
functionpayRent(uint tokenId, uint32 payment) external;
functionterminateRental(uint tokenId) external;
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)pragmasolidity ^0.8.0;/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/interfaceIVotes{
/**
* @dev Emitted when an account changes their delegate.
*/eventDelegateChanged(addressindexed delegator, addressindexed fromDelegate, addressindexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/eventDelegateVotesChanged(addressindexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/functiongetVotes(address account) externalviewreturns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/functiongetPastVotes(address account, uint256 blockNumber) externalviewreturns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/functiongetPastTotalSupply(uint256 blockNumber) externalviewreturns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/functiondelegates(address account) externalviewreturns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/functiondelegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/functiondelegateBySig(address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
Código Fuente del Contrato
Archivo 17 de 26: Math.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)pragmasolidity ^0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
/**
* @dev Returns the largest of two numbers.
*/functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/functionaverage(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b) / 2 can overflow.return (a & b) + (a ^ b) /2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/functionceilDiv(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.return a / b + (a % b ==0 ? 0 : 1);
}
}
Código Fuente del Contrato
Archivo 18 de 26: NFTWEscrow.sol
// SPDX-License-Identifier: MITpragmasolidity 0.8.11;import"@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import"@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import"@openzeppelin/contracts/utils/introspection/ERC165.sol";
import"@openzeppelin/contracts/utils/Context.sol";
import"@openzeppelin/contracts/access/Ownable.sol";
import"@openzeppelin/contracts/security/ReentrancyGuard.sol";
import"@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import"@openzeppelin/contracts/utils/math/SafeCast.sol";
import"./TransferHelper.sol";
import"./INFTWEscrow.sol";
import"./INFTWRental.sol";
import"./INFTWRouter.sol";
import"./INFTW_ERC721.sol";
contractNFTWEscrowisContext, ERC165, INFTWEscrow, ERC20Permit, ERC20Votes, Ownable, ReentrancyGuard{
usingSafeCastforuint;
usingECDSAforbytes32;
addressimmutable WRLD_ERC20_ADDR;
INFTW_ERC721 immutable NFTW_ERC721;
INFTWRental private NFTWRental;
INFTWRouter private NFTWRouter;
WorldInfo[10001] private worldInfo; // NFTW tokenId is in N [1,10000]
RewardsPeriod public rewardsPeriod;
RewardsPerWeight public rewardsPerWeight;
mapping (address=> UserRewards) public rewards;
mapping (address=>bool) private isPredicate; // Polygon bridge predicatemapping (address=>uint) public userBridged;
uintprivate bridged;
addressprivate signer;
// ======== Admin functions ========constructor(address wrld, address nftw) ERC20("Vote-escrowed NFTWorld", "veNFTW") ERC20Permit("Vote-escrowed NFTWorld") {
require(wrld !=address(0), "E0"); // E0: addr errrequire(nftw !=address(0), "E0");
WRLD_ERC20_ADDR = wrld;
NFTW_ERC721 = INFTW_ERC721(nftw);
}
// Set a rewards schedule// rate is in wei per second for all users// This must be called AFTER some worlds are staked (or ensure at least 1 world is staked before the start timestamp)functionsetRewards(uint32 start, uint32 end, uint96 rate) externalvirtualonlyOwner{
require(start <= end, "E1"); // E1: Incorrect input// some safeguard, value TBD. (2b over 5 years is 12.68 per sec) require(rate >0.03ether&& rate <30ether, "E2"); // E2: Rate incorrectrequire(WRLD_ERC20_ADDR !=address(0), "E3"); // E3: Rewards token not setrequire(block.timestamp.toUint32() < rewardsPeriod.start ||block.timestamp.toUint32() > rewardsPeriod.end, "E4"); // E4: Rewards already set
rewardsPeriod.start = start;
rewardsPeriod.end = end;
rewardsPerWeight.lastUpdated = start;
rewardsPerWeight.rate = rate;
emit RewardsSet(start, end, rate);
}
functionsetWeight(uint[] calldata tokenIds, uint[] calldata weights) externalonlyOwner{
require(tokenIds.length== weights.length, "E6");
for (uint i =0; i < tokenIds.length; i++) {
uint tokenId = tokenIds[i];
require(worldInfo[tokenId].weight ==0, "E8");
worldInfo[tokenId].weight = weights[i].toUint16();
}
}
// signing key does not require high security and can be put on an API server and rotated periodically, as signatures are issued dynamicallyfunctionsetSigner(address _signer) externalonlyOwner{
signer = _signer;
}
functionsetRentalContract(INFTWRental _contract) externalonlyOwner{
require(_contract.supportsInterface(type(INFTWRental).interfaceId),"E0");
NFTWRental = _contract;
}
functionsetRouterContract(INFTWRouter _contract) externalonlyOwner{
NFTWRouter = _contract;
}
functionsetPredicate(address _contract, bool _allow) externalonlyOwner{
require(_contract !=address(0), "E0"); // E0: addr err
isPredicate[_contract] = _allow;
}
// ======== Public functions ========// Stake worlds for a first time. You may optionally stake to a different wallet. Ownership will be transferred to the stakeTo address.// Initial weights passed as input parameters, which are secured by a dev signature. weight = 40003 - 3 * rank// When you stake you can set rental conditions for all of them.// Initialized and uninitialized stake can be mixed into one tx using this method.// If you set rentalPerDay to 0 and rentableUntil to some time in the future, then anyone can rent for free // until the rentableUntil timestamp with no way of backing outfunctioninitialStake(uint[] calldata tokenIds, uint[] calldata weights, address stakeTo,
uint16 _deposit, uint16 _rentalPerDay, uint16 _minRentDays, uint32 _rentableUntil, uint32 _maxTimestamp, bytescalldata _signature)
externalvirtualoverridenonReentrant{
require(uint(_deposit) <=uint(_rentalPerDay) * (uint(_minRentDays) +1), "ER"); // ER: Rental rate incorrect// security measure against input length attackrequire(tokenIds.length== weights.length, "E6"); // E6: Input length mismatchrequire(block.timestamp<= _maxTimestamp, "EX"); // EX: Signature expired// verifying signature here is much cheaper than verifying merkle rootrequire(_verifySignerSignature(keccak256(
abi.encode(tokenIds, weights, _msgSender(), _maxTimestamp, address(this))), _signature), "E7"); // E7: Invalid signature// ensure stakeTo is EOA or ERC721Receiver to avoid token lockup
_ensureEOAorERC721Receiver(stakeTo);
require(stakeTo !=address(this), "ES"); // ES: Stake to escrowuint totalWeights =0;
for (uint i =0; i < tokenIds.length; i++) {
{ // scope to avoid stack too deep errorsuint tokenId = tokenIds[i];
uint _weight = worldInfo[tokenId].weight;
require(_weight ==0|| _weight == weights[i], "E8"); // E8: Initialized weight cannot be changedrequire(NFTW_ERC721.ownerOf(tokenId) == _msgSender(), "E9"); // E9: Not your world
NFTW_ERC721.safeTransferFrom(_msgSender(), address(this), tokenId);
emit WorldStaked(tokenId, stakeTo);
}
worldInfo[tokenIds[i]] = WorldInfo(weights[i].toUint16(), stakeTo, _deposit, _rentalPerDay, _minRentDays, _rentableUntil);
totalWeights += weights[i];
}
// update rewards
_updateRewardsPerWeight(totalWeights.toUint32(), true);
_updateUserRewards(stakeTo, totalWeights.toUint32(), true);
// mint veNFTW
_mint(stakeTo, tokenIds.length*1e18);
}
// subsequent staking does not require dev signaturefunctionstake(uint[] calldata tokenIds, address stakeTo,
uint16 _deposit, uint16 _rentalPerDay, uint16 _minRentDays, uint32 _rentableUntil)
externalvirtualoverridenonReentrant{
require(uint(_deposit) <=uint(_rentalPerDay) * (uint(_minRentDays) +1), "ER"); // ER: Rental rate incorrect// ensure stakeTo is EOA or ERC721Receiver to avoid token lockup
_ensureEOAorERC721Receiver(stakeTo);
require(stakeTo !=address(this), "ES"); // ES: Stake to escrowuint totalWeights =0;
for (uint i =0; i < tokenIds.length; i++) {
uint tokenId = tokenIds[i];
uint16 _weight = worldInfo[tokenId].weight;
require(_weight !=0, "EA"); // EA: Weight not initializedrequire(NFTW_ERC721.ownerOf(tokenId) == _msgSender(), "E9"); // E9: Not your world
NFTW_ERC721.safeTransferFrom(_msgSender(), address(this), tokenId);
totalWeights += _weight;
worldInfo[tokenId] = WorldInfo(_weight, stakeTo, _deposit, _rentalPerDay, _minRentDays, _rentableUntil);
emit WorldStaked(tokenId, stakeTo);
}
// update rewards
_updateRewardsPerWeight(totalWeights.toUint32(), true);
_updateUserRewards(stakeTo, totalWeights.toUint32(), true);
// mint veNFTW
_mint(stakeTo, tokenIds.length*1e18);
}
// Update rental conditions as long as therer's no ongoing rent.// setting rentableUntil to 0 makes the world unrentable.functionupdateRent(uint[] calldata tokenIds,
uint16 _deposit, uint16 _rentalPerDay, uint16 _minRentDays, uint32 _rentableUntil)
externalvirtualoverride{
require(uint(_deposit) <=uint(_rentalPerDay) * (uint(_minRentDays) +1), "ER"); // ER: Rental rate incorrectfor (uint i =0; i < tokenIds.length; i++) {
uint tokenId = tokenIds[i];
WorldInfo storage worldInfo_ = worldInfo[tokenId];
require(worldInfo_.weight !=0, "EA"); // EA: Weight not initializedrequire(NFTW_ERC721.ownerOf(tokenId) ==address(this) && worldInfo_.owner == _msgSender(), "E9"); // E9: Not your worldrequire(!NFTWRental.isRentActive(tokenId), "EB"); // EB: Ongoing rent
worldInfo_.deposit = _deposit;
worldInfo_.rentalPerDay = _rentalPerDay;
worldInfo_.minRentDays = _minRentDays;
worldInfo_.rentableUntil = _rentableUntil;
}
}
// Extend rental period of ongoing rentfunctionextendRentalPeriod(uint tokenId, uint32 _rentableUntil) externalvirtualoverride{
WorldInfo storage worldInfo_ = worldInfo[tokenId];
require(worldInfo_.weight !=0, "EA"); // EA: Weight not initializedrequire(NFTW_ERC721.ownerOf(tokenId) ==address(this) && worldInfo_.owner == _msgSender(), "E9"); // E9: Not your world
worldInfo_.rentableUntil = _rentableUntil;
}
functionunstake(uint[] calldata tokenIds, address unstakeTo) externalvirtualoverridenonReentrant{
// ensure unstakeTo is EOA or ERC721Receiver to avoid token lockup
_ensureEOAorERC721Receiver(unstakeTo);
require(unstakeTo !=address(this), "ES"); // ES: Unstake to escrowrequire(balanceOf(_msgSender()) - userBridged[_msgSender()] >= tokenIds.length*1e18, "EP"); // EP: veNFTW bridged to polygonuint totalWeights =0;
for (uint i =0; i < tokenIds.length; i++) {
uint tokenId = tokenIds[i];
require(worldInfo[tokenId].owner == _msgSender(), "E9"); // E9: Not your worldrequire(!NFTWRental.isRentActive(tokenId), "EB"); // EB: Ongoing rent
NFTW_ERC721.safeTransferFrom(address(this), unstakeTo, tokenId);
uint16 _weight = worldInfo[tokenId].weight;
totalWeights += _weight;
worldInfo[tokenId] = WorldInfo(_weight,address(0),0,0,0,0);
emit WorldUnstaked(tokenId, _msgSender()); // World `id` unstaked from `address`
}
// update rewards
_updateRewardsPerWeight(totalWeights.toUint32(), false);
_updateUserRewards(_msgSender(), totalWeights.toUint32(), false);
// burn veNFTW
_burn(_msgSender(), tokenIds.length*1e18);
}
functionsetRoutingDataIPFSHash(uint tokenId, stringcalldata _ipfsHash) external{
require((worldInfo[tokenId].owner == _msgSender() &&!NFTWRental.isRentActive(tokenId))
|| (worldInfo[tokenId].owner !=address(0) && NFTWRental.getTenant(tokenId) == _msgSender()),
"EH"); // EH: Not your world or not rented
NFTWRouter.setRoutingDataIPFSHash(tokenId, _ipfsHash);
}
functionremoveRoutingDataIPFSHash(uint tokenId) external{
require((worldInfo[tokenId].owner == _msgSender() &&!NFTWRental.isRentActive(tokenId))
|| (worldInfo[tokenId].owner !=address(0) && NFTWRental.getTenant(tokenId) == _msgSender()),
"EH"); // EH: Not your world or not rented
NFTWRouter.removeRoutingDataIPFSHash(tokenId);
}
functionupdateMetadata(uint tokenId, stringcalldata _tokenMetadataIPFSHash) externalvirtual{
require((worldInfo[tokenId].owner == _msgSender() &&!NFTWRental.isRentActive(tokenId))
|| (worldInfo[tokenId].owner !=address(0) && NFTWRental.getTenant(tokenId) == _msgSender()),
"EH"); // EH: Not your world or not rented
NFTW_ERC721.updateMetadataIPFSHash(tokenId, _tokenMetadataIPFSHash);
}
// Claim all rewards from caller into a given addressfunctionclaim(address to) externalvirtualoverridenonReentrant{
_updateRewardsPerWeight(0, false);
uint rewardAmount = _updateUserRewards(_msgSender(), 0, false);
rewards[_msgSender()].accumulated =0;
TransferHelper.safeTransfer(WRLD_ERC20_ADDR, to, rewardAmount);
emit RewardClaimed(to, rewardAmount);
}
// ======== View only functions ========functiongetWorldInfo(uint tokenId) externalviewoverridereturns(WorldInfo memory) {
return worldInfo[tokenId];
}
functioncheckUserRewards(address user) externalvirtualviewoverridereturns(uint) {
RewardsPerWeight memory rewardsPerWeight_ = rewardsPerWeight;
UserRewards memory userRewards_ = rewards[user];
// Find out the unaccounted timeuint32 end = min(block.timestamp.toUint32(), rewardsPeriod.end);
uint256 unaccountedTime = end - rewardsPerWeight_.lastUpdated; // Cast to uint256 to avoid overflows later onif (unaccountedTime !=0) {
// Calculate and update the new value of the accumulator. unaccountedTime casts it into uint256, which is desired.// If the first mint happens mid-program, we don't update the accumulator, no one gets the rewards for that period.if (rewardsPerWeight_.totalWeight !=0) {
rewardsPerWeight_.accumulated = (rewardsPerWeight_.accumulated + unaccountedTime * rewardsPerWeight_.rate / rewardsPerWeight_.totalWeight).toUint96();
}
}
// Calculate and update the new value user reserves. userRewards_.stakedWeight casts it into uint256, which is desired.return userRewards_.accumulated + userRewards_.stakedWeight * (rewardsPerWeight_.accumulated - userRewards_.checkpoint);
}
functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return interfaceId ==type(INFTWEscrow).interfaceId||super.supportsInterface(interfaceId);
}
// ======== internal functions ========function_verifySignerSignature(bytes32 hash, bytescalldata signature) internalviewreturns(bool) {
return hash.toEthSignedMessageHash().recover(signature) == signer;
}
functionmin(uint32 x, uint32 y) internalpurereturns (uint32 z) {
z = (x < y) ? x : y;
}
// Updates the rewards per weight accumulator.// Needs to be called on each staking/unstaking event.function_updateRewardsPerWeight(uint32 weight, bool increase) internalvirtual{
RewardsPerWeight memory rewardsPerWeight_ = rewardsPerWeight;
RewardsPeriod memory rewardsPeriod_ = rewardsPeriod;
// We skip the update if the program hasn't startedif (block.timestamp.toUint32() >= rewardsPeriod_.start) {
// Find out the unaccounted timeuint32 end = min(block.timestamp.toUint32(), rewardsPeriod_.end);
uint256 unaccountedTime = end - rewardsPerWeight_.lastUpdated; // Cast to uint256 to avoid overflows later onif (unaccountedTime !=0) {
// Calculate and update the new value of the accumulator.// If the first mint happens mid-program, we don't update the accumulator, no one gets the rewards for that period.if (rewardsPerWeight_.totalWeight !=0) {
rewardsPerWeight_.accumulated = (rewardsPerWeight_.accumulated + unaccountedTime * rewardsPerWeight_.rate / rewardsPerWeight_.totalWeight).toUint96();
}
rewardsPerWeight_.lastUpdated = end;
}
}
if (increase) {
rewardsPerWeight_.totalWeight += weight;
}
else {
rewardsPerWeight_.totalWeight -= weight;
}
rewardsPerWeight = rewardsPerWeight_;
emit RewardsPerWeightUpdated(rewardsPerWeight_.accumulated);
}
// Accumulate rewards for an user.// Needs to be called on each staking/unstaking event.function_updateUserRewards(address user, uint32 weight, bool increase) internalvirtualreturns (uint96) {
UserRewards memory userRewards_ = rewards[user];
RewardsPerWeight memory rewardsPerWeight_ = rewardsPerWeight;
// Calculate and update the new value user reserves.
userRewards_.accumulated = userRewards_.accumulated + userRewards_.stakedWeight * (rewardsPerWeight_.accumulated - userRewards_.checkpoint);
userRewards_.checkpoint = rewardsPerWeight_.accumulated;
if (weight !=0) {
if (increase) {
userRewards_.stakedWeight += weight;
}
else {
userRewards_.stakedWeight -= weight;
}
emit WeightUpdated(user, increase, weight, block.timestamp);
}
rewards[user] = userRewards_;
emit UserRewardsUpdated(user, userRewards_.accumulated, userRewards_.checkpoint);
return userRewards_.accumulated;
}
function_ensureEOAorERC721Receiver(address to) internalvirtual{
uint32 size;
assembly {
size :=extcodesize(to)
}
if (size >0) {
try IERC721Receiver(to).onERC721Received(address(this), address(this), 0, "") returns (bytes4 retval) {
require(retval == IERC721Receiver.onERC721Received.selector, "ET"); // ET: neither EOA nor ERC721Receiver
} catch (bytesmemory) {
revert("ET"); // ET: neither EOA nor ERC721Receiver
}
}
}
// ======== function overrides ========function_beforeTokenTransfer(addressfrom, address to, uint256 amount) internaloverride{
require(from==address(0) || to ==address(0) || isPredicate[from] || isPredicate[to], "ERC20: Non-transferrable");
// bridge back from polygonif (isPredicate[from]) {
bridged -= amount;
userBridged[to] -= amount;
super._burn(to, amount);
}
// bridge to polygonif (isPredicate[to]) {
bridged += amount;
userBridged[from] += amount;
super._mint(from, amount);
}
super._beforeTokenTransfer(from, to, amount);
}
functiontotalSupply() publicviewoverride(ERC20, IERC20) returns (uint256 supply) {
supply =super.totalSupply() - bridged;
}
// Prevent sending ERC721 tokens directly to this contractfunctiononERC721Received(address operator, addressfrom, uint256 tokenId, bytescalldata data) externalviewoverridereturns (bytes4) {
from; tokenId; data; // supress solidity warningsif (operator ==address(this)) {
returnthis.onERC721Received.selector;
}
else {
return0x00000000;
}
}
// The following functions are overrides required by Solidity.function_afterTokenTransfer(addressfrom, address to, uint256 amount)
internaloverride(ERC20, ERC20Votes)
{
super._afterTokenTransfer(from, to, amount);
}
function_mint(address to, uint256 amount)
internaloverride(ERC20, ERC20Votes)
{
super._mint(to, amount);
}
function_burn(address account, uint256 amount)
internaloverride(ERC20, ERC20Votes)
{
super._burn(account, amount);
}
}
Código Fuente del Contrato
Archivo 19 de 26: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)pragmasolidity ^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.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
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.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
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) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Código Fuente del Contrato
Archivo 20 de 26: ReentrancyGuard.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)pragmasolidity ^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].
*/abstractcontractReentrancyGuard{
// 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.uint256privateconstant _NOT_ENTERED =1;
uint256privateconstant _ENTERED =2;
uint256private _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.
*/modifiernonReentrant() {
// On the first call to nonReentrant, _notEntered will be truerequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
Código Fuente del Contrato
Archivo 21 de 26: SafeCast.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)pragmasolidity ^0.8.0;/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/librarySafeCast{
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/functiontoUint224(uint256 value) internalpurereturns (uint224) {
require(value <=type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
returnuint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/functiontoUint128(uint256 value) internalpurereturns (uint128) {
require(value <=type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
returnuint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/functiontoUint96(uint256 value) internalpurereturns (uint96) {
require(value <=type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
returnuint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/functiontoUint64(uint256 value) internalpurereturns (uint64) {
require(value <=type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
returnuint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/functiontoUint32(uint256 value) internalpurereturns (uint32) {
require(value <=type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
returnuint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/functiontoUint16(uint256 value) internalpurereturns (uint16) {
require(value <=type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
returnuint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/functiontoUint8(uint256 value) internalpurereturns (uint8) {
require(value <=type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
returnuint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/functiontoUint256(int256 value) internalpurereturns (uint256) {
require(value >=0, "SafeCast: value must be positive");
returnuint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/functiontoInt128(int256 value) internalpurereturns (int128) {
require(value >=type(int128).min&& value <=type(int128).max, "SafeCast: value doesn't fit in 128 bits");
returnint128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/functiontoInt64(int256 value) internalpurereturns (int64) {
require(value >=type(int64).min&& value <=type(int64).max, "SafeCast: value doesn't fit in 64 bits");
returnint64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/functiontoInt32(int256 value) internalpurereturns (int32) {
require(value >=type(int32).min&& value <=type(int32).max, "SafeCast: value doesn't fit in 32 bits");
returnint32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/functiontoInt16(int256 value) internalpurereturns (int16) {
require(value >=type(int16).min&& value <=type(int16).max, "SafeCast: value doesn't fit in 16 bits");
returnint16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/functiontoInt8(int256 value) internalpurereturns (int8) {
require(value >=type(int8).min&& value <=type(int8).max, "SafeCast: value doesn't fit in 8 bits");
returnint8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/functiontoInt256(uint256 value) internalpurereturns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positiverequire(value <=uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
returnint256(value);
}
}
Código Fuente del Contrato
Archivo 22 de 26: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)pragmasolidity ^0.8.0;/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _HEX_SYMBOLS ="0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
// Inspired by OraclizeAPI's implementation - MIT licence// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.solif (value ==0) {
return"0";
}
uint256 temp = value;
uint256 digits;
while (temp !=0) {
digits++;
temp /=10;
}
bytesmemory buffer =newbytes(digits);
while (value !=0) {
digits -=1;
buffer[digits] =bytes1(uint8(48+uint256(value %10)));
value /=10;
}
returnstring(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
if (value ==0) {
return"0x00";
}
uint256 temp = value;
uint256 length =0;
while (temp !=0) {
length++;
temp >>=8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _HEX_SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
}
Código Fuente del Contrato
Archivo 23 de 26: TransferHelper.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.2;/**
helper methods for interacting with ERC20 tokens that do not consistently return true/false
with the addition of a transfer function to send eth or an erc20 token
*/libraryTransferHelper{
functionsafeApprove(address token, address to, uint value) internal{
(bool success, bytesmemory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length==0||abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED");
}
functionsafeTransfer(address token, address to, uint value) internal{
(bool success, bytesmemory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length==0||abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED");
}
functionsafeTransferFrom(address token, addressfrom, address to, uint value) internal{
(bool success, bytesmemory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length==0||abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED");
}
// sends ETH or an erc20 tokenfunctionsafeTransferBaseToken(address token, addresspayable to, uint value, bool isERC20) internal{
if (!isERC20) {
to.transfer(value);
} else {
(bool success, bytesmemory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length==0||abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED");
}
}
}
Código Fuente del Contrato
Archivo 24 de 26: draft-EIP712.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)pragmasolidity ^0.8.0;import"./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/abstractcontractEIP712{
/* solhint-disable var-name-mixedcase */// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to// invalidate the cached domain separator if the chain id changes.bytes32privateimmutable _CACHED_DOMAIN_SEPARATOR;
uint256privateimmutable _CACHED_CHAIN_ID;
addressprivateimmutable _CACHED_THIS;
bytes32privateimmutable _HASHED_NAME;
bytes32privateimmutable _HASHED_VERSION;
bytes32privateimmutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase *//**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/constructor(stringmemory name, stringmemory version) {
bytes32 hashedName =keccak256(bytes(name));
bytes32 hashedVersion =keccak256(bytes(version));
bytes32 typeHash =keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID =block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS =address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/function_domainSeparatorV4() internalviewreturns (bytes32) {
if (address(this) == _CACHED_THIS &&block.chainid== _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function_buildDomainSeparator(bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) privateviewreturns (bytes32) {
returnkeccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/function_hashTypedDataV4(bytes32 structHash) internalviewvirtualreturns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
Código Fuente del Contrato
Archivo 25 de 26: draft-ERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)pragmasolidity ^0.8.0;import"./draft-IERC20Permit.sol";
import"../ERC20.sol";
import"../../../utils/cryptography/draft-EIP712.sol";
import"../../../utils/cryptography/ECDSA.sol";
import"../../../utils/Counters.sol";
/**
* @dev Implementation 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.
*
* _Available since v3.4._
*/abstractcontractERC20PermitisERC20, IERC20Permit, EIP712{
usingCountersforCounters.Counter;
mapping(address=> Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcasebytes32privateimmutable _PERMIT_TYPEHASH =keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/constructor(stringmemory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtualoverride{
require(block.timestamp<= deadline, "ERC20Permit: expired deadline");
bytes32 structHash =keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/functionnonces(address owner) publicviewvirtualoverridereturns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewoverridereturns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/function_useNonce(address owner) internalvirtualreturns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
Código Fuente del Contrato
Archivo 26 de 26: draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)pragmasolidity ^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.
*/interfaceIERC20Permit{
/**
* @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].
*/functionpermit(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.
*/functionnonces(address owner) externalviewreturns (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-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}