Contract Overview
Balance:
0 FTM
FTM Value:
$0.00
My Name Tag:
Not Available, login to update
Txn Hash | Method |
Block
|
From
|
To
|
Value | [Txn Fee] | ||
---|---|---|---|---|---|---|---|---|
0x4fc4a4ce22c659cb137b60f54fc495682bc2d74591d6c421f71e9f9ed5f1eef1 | 0x60806040 | 47957845 | 131 days 6 hrs ago | FantOHM DAO: Deployer | IN | Create: BalanceVaultShare | 0 FTM | 0.00508498074 |
[ Download CSV Export ]
Latest 1 internal transaction
Parent Txn Hash | Block | From | To | Value | |||
---|---|---|---|---|---|---|---|
0x4fc4a4ce22c659cb137b60f54fc495682bc2d74591d6c421f71e9f9ed5f1eef1 | 47957845 | 131 days 6 hrs ago | FantOHM DAO: Deployer | Contract Creation | 0 FTM |
[ Download CSV Export ]
Contract Name:
BalanceVaultShare
Compiler Version
v0.8.16+commit.07a7930e
Optimization Enabled:
Yes with 200 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/Base64Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "erc721a-upgradeable/contracts/extensions/ERC721AQueryableUpgradeable.sol"; import "./BalanceVault.sol"; import "../utils/BokkyPooBahsDateTimeLibrary.sol"; struct AmountInfo { uint256[] amounts; address[] tokens; } /// @notice Share of Balance Vault /// @author Balance Capital https://www.balance.capital/, [email protected] contract BalanceVaultShare is ERC721AQueryableUpgradeable, OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; BalanceVault public vault; /// token amounts representation of user share in given vault mapping(uint256 => AmountInfo) internal amountInfos; /// @notice one time initialize /// @param _vault vault instance function initialize(address _vault) public initializerERC721A initializer { __ERC721A_init("BalanceVaultShare", "BALANCE-VAULT-SHARE"); __Ownable_init(); require(_vault != address(0), "MISSING_VAULT"); vault = BalanceVault(_vault); } /// @notice can burn user tokens in favor of creating new recipe token later from vault /// @param _tokenId tokenId to burn function burn(uint256 _tokenId) external { require(msg.sender == address(vault), "CALLER_NOT_VAULT"); delete amountInfos[_tokenId]; _burn(_tokenId, false); } /// @notice mints recipe share to the user /// @param _user depositor /// @param _amounts amounts of tokens provided into vault /// @param _tokens tokens provided into vault /// @return tokenId of currently minted token function mint( address _user, uint256[] calldata _amounts, address[] calldata _tokens ) external returns (uint256) { require(msg.sender == address(vault), "CALLER_NOT_VAULT"); require(_user != address(0), "MISSING_USER"); require(_tokens.length > 0, "MISSING_TOKENS"); require(_tokens.length == _amounts.length, "AMOUNT_LENGTH"); uint256 tokenId = _nextTokenId(); amountInfos[tokenId] = AmountInfo({amounts: _amounts, tokens: _tokens}); _mint(_user, 1); return tokenId; } function getAmountInfos(uint256 _tokenId) external view returns (uint256[] memory, address[] memory) { return (amountInfos[_tokenId].amounts, amountInfos[_tokenId].tokens); } function getOwnerName() internal view returns (string memory) { return vault.ownerName(); } function getOwnerDescription() internal view returns (string memory) { return vault.ownerDescription(); } function getRepayment() internal view returns (string memory) { uint256 timestamp = vault.repaymentTimestamp(); if (timestamp == 0) return "No repayment"; string memory yearStr = StringsUpgradeable.toString( BokkyPooBahsDateTimeLibrary.getYear(timestamp) ); uint256 month = BokkyPooBahsDateTimeLibrary.getMonth(timestamp); string memory monthStr = StringsUpgradeable.toString(month); if (month < 10) { monthStr = string(abi.encodePacked("0", monthStr)); } uint256 day = BokkyPooBahsDateTimeLibrary.getDay(timestamp); string memory dayStr = StringsUpgradeable.toString(day); if (day < 10) { dayStr = string(abi.encodePacked("0", dayStr)); } uint256 hour = BokkyPooBahsDateTimeLibrary.getHour(timestamp); string memory hourStr = StringsUpgradeable.toString(hour); if (hour < 10) { hourStr = string(abi.encodePacked("0", hourStr)); } uint256 minute = BokkyPooBahsDateTimeLibrary.getMinute(timestamp); string memory minuteStr = StringsUpgradeable.toString(minute); if (minute < 10) { minuteStr = string(abi.encodePacked("0", minuteStr)); } return string( abi.encodePacked( "Repayment: ", yearStr, "/", monthStr, "/", dayStr, " ", hourStr, ":", minuteStr ) ); } function getApr() internal view returns (string memory) { uint256 apr = vault.apr(); if (apr == 0) return "No APR"; return string( abi.encodePacked( "APR: ", StringsUpgradeable.toString(apr / 100), "%" ) ); } function getRoi() internal view returns (string memory) { uint256 roi = (vault.roi(1e9) * 10000) / 1e9; if (roi == 0) return "No ROI"; return string( abi.encodePacked( "ROI: ", StringsUpgradeable.toString(roi / 100), "%" ) ); } function getTokenAmount(uint256 _tokenId, uint256 _index) public view returns (string memory) { uint256[] memory amounts = amountInfos[_tokenId].amounts; address[] memory tokens = amountInfos[_tokenId].tokens; if (tokens.length == 0 || _index >= tokens.length) return "No deposits"; ERC20Upgradeable token = ERC20Upgradeable(tokens[_index]); // FIXME weth decimals maybe show also last 2 digits uint256 amount = amounts[_index] / (10**token.decimals()); return string( abi.encodePacked( "Deposited: ", StringsUpgradeable.toString(amount), " ", token.symbol() ) ); } /// @notice returns image in plain text /// @param _tokenId token id /// @return image for base64 encoding into manifest function getImagePlainText(uint256 _tokenId) public view returns (string memory) { uint256 tokenLength = amountInfos[_tokenId].tokens.length; uint256 length = 2 * tokenLength + 12; /* rect+text for each token amount */ /* 4 + 4 + 4 */ uint256 index = 0; string[] memory parts = new string[](length); parts[index++] = '<?xml version="1.0" encoding="UTF-8"?>'; parts[ index++ ] = '<svg xmlns="http://www.w3.org/2000/svg" width="1080" height="1359" viewBox="0 0 1080 1359">' '<style>.b,.h{fill:#fff;font-family:"Arial"}.h{font-size:83px}.b{font-size:34px;background-color:#000;padding:20px}</style>'; parts[index++] = "<defs>" '<clipPath id="clip-path">' '<rect id="Rectangle_994" width="1080" height="1359" rx="34" stroke="#707070" stroke-width="1"/>' "</clipPath>" '<radialGradient id="radial-gradient" cx="0.5" cy="0.5" r="0.5" gradientUnits="objectBoundingBox">' '<stop offset="0" stop-color="#358077"/>' '<stop offset="1" stop-opacity="0"/>' "</radialGradient>" '<radialGradient id="radial-gradient-2" cx="0.5" cy="0.5" r="0.5" gradientUnits="objectBoundingBox">' '<stop offset="0" stop-color="#393493"/>' '<stop offset="1" stop-color="#1d1a4a" stop-opacity="0"/>' "</radialGradient>" '<linearGradient id="linear-gradient" y1="0.5" x2="1" y2="0.5" gradientUnits="objectBoundingBox">' '<stop offset="0" stop-color="#fff"/>' '<stop offset="1" stop-color="gray"/>' "</linearGradient>" "</defs>"; parts[ index++ ] = '<g id="Rectangle_993" stroke="#707070" stroke-width="1">' '<rect width="1080" height="1359" rx="34" stroke="none"/>' '<rect x="0.5" y="0.5" width="1079" height="1358" rx="33.5" fill="none"/>' "</g>" '<g id="Mask_Group_1" clip-path="url(#clip-path)">' '<g id="Group_12660" transform="translate(-1025 -1533.908)">' '<ellipse id="Ellipse_975" cx="1042" cy="1311.5" rx="1042" ry="1311.5" transform="translate(0 1963.908)" fill="url(#radial-gradient)"/>' '<ellipse id="Ellipse_976" cx="986" cy="1241" rx="986" ry="1241" transform="translate(1025 -0.092)" fill="url(#radial-gradient-2)"/>' "</g>" "</g>" '<g id="Rectangle_992" transform="translate(53 53)" fill="none" stroke="rgba(255,255,255,0.17)" stroke-width="1">' '<rect width="975" height="1254" rx="23" stroke="none"/>' '<rect x="0.5" y="0.5" width="974" height="1253" rx="22.5" fill="none"/>' "</g>" '<g id="Group_12556" transform="translate(-347.391 -267.524)">' '<g id="Group_12539" transform="translate(447.391 395.883)">' '<g id="Group_12544" transform="translate(0 0)">' '<path id="Path_3381" d="M484.882-1143.461a51.172,51.172,0,0,1-39.349-39.349,8.723,8.723,0,0,1,8.509-10.564h0a8.655,8.655,0,0,1,8.5,6.835,33.7,33.7,0,0,0,26.067,26.068,8.655,8.655,0,0,1,6.835,8.5h0A8.724,8.724,0,0,1,484.882-1143.461Z" transform="translate(-412.268 1193.987)" fill="url(#linear-gradient)"/>' '<path id="Path_3382" d="M379.928-1118.648a51.172,51.172,0,0,1,39.349,39.349,8.723,8.723,0,0,1-8.509,10.564h0a8.655,8.655,0,0,1-8.5-6.835,33.7,33.7,0,0,0-26.067-26.067,8.655,8.655,0,0,1-6.835-8.5h0A8.723,8.723,0,0,1,379.928-1118.648Z" transform="translate(-369.364 1151.897)" fill="url(#linear-gradient)"/>' '<path id="Path_3383" d="M379.928-1144.869a51.171,51.171,0,0,0,39.349-39.349,8.723,8.723,0,0,0-8.509-10.563h0a8.655,8.655,0,0,0-8.5,6.835,33.7,33.7,0,0,1-26.067,26.067,8.654,8.654,0,0,0-6.835,8.5h0A8.723,8.723,0,0,0,379.928-1144.869Z" transform="translate(-369.364 1194.781)" fill="#fff"/>' '<path id="Path_3384" d="M484.882-1118.648a51.172,51.172,0,0,0-39.349,39.349,8.723,8.723,0,0,0,8.509,10.564h0a8.655,8.655,0,0,0,8.5-6.835,33.7,33.7,0,0,1,26.067-26.067,8.656,8.656,0,0,0,6.835-8.5h0A8.723,8.723,0,0,0,484.882-1118.648Z" transform="translate(-412.268 1151.897)" fill="#fff"/>' "</g>" "</g>" '<text id="balance" transform="translate(645.958 450.121)" fill="#fff" stroke="rgba(0,0,0,0)" stroke-width="1" font-size="41" style="font-family:\'Arial\';" letter-spacing="0.05em"><tspan x="-87.801" y="0">balance</tspan></text>' "</g>"; uint256 yStart = 763; for (uint256 i = 0; i < tokenLength; i++) { parts[index++] = string( abi.encodePacked( '<rect width="585" height="104" rx="23" transform="translate(100 ', StringsUpgradeable.toString(yStart - i * 132), ')" fill="rgba(255,255,255,0.11)"/>' ) ); } parts[ index++ ] = '<rect width="585" height="104" rx="23" transform="translate(100 895)" fill="rgba(255,255,255,0.11)"/>'; parts[ index++ ] = '<rect width="211" height="104" rx="23" transform="translate(100 1025)" fill="rgba(255,255,255,0.11)"/>'; parts[ index++ ] = '<rect width="240" height="104" rx="23" transform="translate(100 1155)" fill="rgba(255,255,255,0.11)"/>'; parts[index++] = string( abi.encodePacked( '<text transform="translate(100 366)" class="h" style="font-family:\'Arial\';">', getOwnerName(), "</text>" ) ); yStart = 827; for (uint256 i = 0; i < tokenLength; i++) { parts[index++] = string( abi.encodePacked( '<text transform="translate(134 ', StringsUpgradeable.toString(yStart - i * 129), ')" class="b" style="font-family:\'Arial\';">', getTokenAmount(_tokenId, i), "</text>" ) ); } parts[index++] = string( abi.encodePacked( '<text transform="translate(134 956)" class="b" style="font-family:\'Arial\';">', getRepayment(), "</text>" ) ); parts[index++] = string( abi.encodePacked( '<text transform="translate(134 1085)" class="b" style="font-family:\'Arial\';">', getApr(), "</text>" ) ); parts[index++] = string( abi.encodePacked( '<text transform="translate(134 1219)" class="b" style="font-family:\'Arial\';">', getRoi(), "</text>" ) ); parts[index] = "</svg>"; // <xml> to <image> string memory output = string( abi.encodePacked(parts[0], parts[1], parts[2], parts[3]) ); // <rect> for tokens for (uint256 i = 0; i < tokenLength; i++) { output = string(abi.encodePacked(output, parts[4 + i])); } // <rect> for others + <text> for heading output = string( abi.encodePacked( output, parts[4 + tokenLength], parts[5 + tokenLength], parts[6 + tokenLength], parts[7 + tokenLength] ) ); // <text> for tokens for (uint256 i = 0; i < tokenLength; i++) { output = string( abi.encodePacked(output, parts[8 + tokenLength + i]) ); } // <text> for others + </svg> output = string( abi.encodePacked( output, parts[8 + 2 * tokenLength], parts[9 + 2 * tokenLength], parts[10 + 2 * tokenLength], parts[11 + 2 * tokenLength] ) ); return output; } /// @notice constructs manifest metadata in plaintext for base64 encoding /// @param _tokenId token id /// @return _manifest manifest for base64 encoding function getManifestPlainText(uint256 _tokenId) public view returns (string memory _manifest) { string memory image = getImagePlainText(_tokenId); _manifest = string( abi.encodePacked( '{"name": ', '"', getOwnerName(), " (Balance Vault) - ", StringsUpgradeable.toString(_tokenId), '", "description": "', getOwnerDescription(), '", "image": "data:image/svg+xml;base64,', Base64Upgradeable.encode(bytes(image)), '"}' ) ); } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 _tokenId) public view virtual override(IERC721AUpgradeable, ERC721AUpgradeable) returns (string memory) { string memory output = getManifestPlainText(_tokenId); string memory json = Base64Upgradeable.encode(bytes(output)); return string(abi.encodePacked("data:application/json;base64,", json)); } function recoverTokens(IERC20Upgradeable token) external onlyOwner { token.safeTransfer(owner(), token.balanceOf(address(this))); } function recoverEth() external onlyOwner { payable(owner()).transfer(address(this).balance); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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.7.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.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}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _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. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 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}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * 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. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * 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`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); 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) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + 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) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * 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( address from, address to, uint256 amount ) internal virtual { 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) internal virtual { 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) internal virtual { 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 ) 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 Updates `owner` s allowance for `spender` based on spent `amount`. * * 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 ) internal virtual { 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( address from, address to, uint256 amount ) internal virtual {} /** * @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( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../extensions/draft-IERC20PermitUpgradeable.sol"; import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable 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( IERC20Upgradeable 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)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20PermitUpgradeable 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(IERC20Upgradeable 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"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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 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 { _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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol) pragma solidity ^0.8.0; /** * @dev Provides a set of functions to operate with Base64 strings. * * _Available since v4.5._ */ library Base64Upgradeable { /** * @dev Base64 Encoding/Decoding Table */ string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * @dev Converts a `bytes` to its Bytes64 `string` representation. */ function encode(bytes memory data) internal pure returns (string memory) { /** * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol */ if (data.length == 0) return ""; // Loads the table into memory string memory table = _TABLE; // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter // and split into 4 numbers of 6 bits. // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up // - `data.length + 2` -> Round up // - `/ 3` -> Number of 3-bytes chunks // - `4 *` -> 4 characters for each chunk string memory result = new string(4 * ((data.length + 2) / 3)); /// @solidity memory-safe-assembly assembly { // Prepare the lookup table (skip the first "length" byte) let tablePtr := add(table, 1) // Prepare result pointer, jump over length let resultPtr := add(result, 32) // Run over the input, 3 bytes at a time for { let dataPtr := data let endPtr := add(data, mload(data)) } lt(dataPtr, endPtr) { } { // Advance 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // To write each character, shift the 3 bytes (18 bits) chunk // 4 times in blocks of 6 bits for each character (18, 12, 6, 0) // and apply logical AND with 0x3F which is the number of // the previous character in the ASCII table prior to the Base64 Table // The result is then added to the table to get the character to write, // and finally write it in the result pointer but with a left shift // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) // Advance } // When data `bytes` is not exactly 3 bytes long // it is padded with `=` characters at the end switch mod(mload(data), 3) case 1 { mstore8(sub(resultPtr, 1), 0x3d) mstore8(sub(resultPtr, 2), 0x3d) } case 2 { mstore8(sub(resultPtr, 1), 0x3d) } } return result; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { 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. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } }
// SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.2 // Creator: Chiru Labs pragma solidity ^0.8.4; import './IERC721AQueryableUpgradeable.sol'; import '../ERC721AUpgradeable.sol'; import '../ERC721A__Initializable.sol'; /** * @title ERC721AQueryable. * * @dev ERC721A subclass with convenience query functions. */ abstract contract ERC721AQueryableUpgradeable is ERC721A__Initializable, ERC721AUpgradeable, IERC721AQueryableUpgradeable { function __ERC721AQueryable_init() internal onlyInitializingERC721A { __ERC721AQueryable_init_unchained(); } function __ERC721AQueryable_init_unchained() internal onlyInitializingERC721A {} /** * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting. * * If the `tokenId` is out of bounds: * * - `addr = address(0)` * - `startTimestamp = 0` * - `burned = false` * - `extraData = 0` * * If the `tokenId` is burned: * * - `addr = <Address of owner before token was burned>` * - `startTimestamp = <Timestamp when token was burned>` * - `burned = true` * - `extraData = <Extra data when token was burned>` * * Otherwise: * * - `addr = <Address of owner>` * - `startTimestamp = <Timestamp of start of ownership>` * - `burned = false` * - `extraData = <Extra data at start of ownership>` */ function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory) { TokenOwnership memory ownership; if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) { return ownership; } ownership = _ownershipAt(tokenId); if (ownership.burned) { return ownership; } return _ownershipOf(tokenId); } /** * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order. * See {ERC721AQueryable-explicitOwnershipOf} */ function explicitOwnershipsOf(uint256[] calldata tokenIds) external view virtual override returns (TokenOwnership[] memory) { unchecked { uint256 tokenIdsLength = tokenIds.length; TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength); for (uint256 i; i != tokenIdsLength; ++i) { ownerships[i] = explicitOwnershipOf(tokenIds[i]); } return ownerships; } } /** * @dev Returns an array of token IDs owned by `owner`, * in the range [`start`, `stop`) * (i.e. `start <= tokenId < stop`). * * This function allows for tokens to be queried if the collection * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. * * Requirements: * * - `start < stop` */ function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) external view virtual override returns (uint256[] memory) { unchecked { if (start >= stop) revert InvalidQueryRange(); uint256 tokenIdsIdx; uint256 stopLimit = _nextTokenId(); // Set `start = max(start, _startTokenId())`. if (start < _startTokenId()) { start = _startTokenId(); } // Set `stop = min(stop, stopLimit)`. if (stop > stopLimit) { stop = stopLimit; } uint256 tokenIdsMaxLength = balanceOf(owner); // Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`, // to cater for cases where `balanceOf(owner)` is too big. if (start < stop) { uint256 rangeLength = stop - start; if (rangeLength < tokenIdsMaxLength) { tokenIdsMaxLength = rangeLength; } } else { tokenIdsMaxLength = 0; } uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength); if (tokenIdsMaxLength == 0) { return tokenIds; } // We need to call `explicitOwnershipOf(start)`, // because the slot at `start` may not be initialized. TokenOwnership memory ownership = explicitOwnershipOf(start); address currOwnershipAddr; // If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`. // `ownership.address` will not be zero, as `start` is clamped to the valid token ID range. if (!ownership.burned) { currOwnershipAddr = ownership.addr; } for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) { ownership = _ownershipAt(i); if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx++] = i; } } // Downsize the array to fit. assembly { mstore(tokenIds, tokenIdsIdx) } return tokenIds; } } /** * @dev Returns an array of token IDs owned by `owner`. * * This function scans the ownership mapping and is O(`totalSupply`) in complexity. * It is meant to be called off-chain. * * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into * multiple smaller scans if the collection is large enough to cause * an out-of-gas error (10K collections should be fine). */ function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) { ownership = _ownershipAt(i); if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx++] = i; } } return tokenIds; } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "./BalanceVaultManager.sol"; import "./BalanceVaultShare.sol"; import "../utils/ArrayUtils.sol"; struct VaultParams { string[] ownerInfos; string[] ownerContacts; address ownerWallet; address nftAddress; uint256 fundingAmount; address[] allowedTokens; uint256 freezeTimestamp; uint256 repaymentTimestamp; uint256 apr; uint256 feeBorrower; uint256 feeLenderUsdb; uint256 feeLenderOther; } /// @notice balance vault /// @author Balance Capital https://www.balance.capital/, [email protected] contract BalanceVault is OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeERC20Upgradeable for ERC20Upgradeable; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /// name of the vault owner string public ownerName; /// description of the vault owner string public ownerDescription; /// contact info of the vault owner string[] public ownerContacts; /// unmodifiable balance vault manager BalanceVaultManager public manager; /// unmodifiable balance share nft BalanceVaultShare public nft; /// unmodifiable wallet of the vault owner where all funds are going address public ownerWallet; /// unmodifiable funding amount with 18 decimals uint256 public fundingAmount; /// (can be moved to the future but not above repaymentTimestamp) timestamp to freeze this fundraising uint256 public freezeTimestamp; /// unmodifiable timestamp to the payout of given APR uint256 public repaymentTimestamp; /// unmodifiable apr in 2 decimals uint256 public apr; uint256 public feeBorrower; uint256 public feeLenderUsdb; uint256 public feeLenderOther; /// unmodifiable allowed tokens which are 1:1 used for funding EnumerableSetUpgradeable.AddressSet internal allowedTokens; bool public frozen; bool public redeemPrepared; /// to repay amount in repay token (allowedTokens[0]) decimals uint256 public toRepayAmount; /// /// events /// /// @notice info about user deposit /// @param _user caller /// @param _amount amount in token /// @param _token token CA /// @param _tokenId NFT token id minted event Deposited( address indexed _user, uint256 _amount, address _token, uint256 _tokenId ); /// @notice info about premature withdraw of all user funds /// @param _user caller /// @param _amounts all amounts of all tokens /// @param _tokens CAs from all previous amounts /// @param _tokenIds NFT token ids burnt from given user event Withdrawn( address indexed _user, uint256[] _amounts, address[] _tokens, uint256[] _tokenIds ); /// @notice vault frozen which means anyone cannot deposit or withdraw, users will wait until repayment /// @param _timestamp timestamp of frozen /// @param _amounts all amounts of fundraised funds /// @param _tokens all tokens of fundraised funds /// @param _toRepayAmount amount to repay /// @param _token in which token it should be paid event Frozen( uint256 _timestamp, uint256[] _amounts, address[] _tokens, uint256 _toRepayAmount, address _token ); /// @notice redeemed original deposit + yield /// @param _user calling user /// @param _tokenIds existing tokenIds /// @param _amount amount redeemed /// @param _fee fee sent to DAO /// @param _token in which token event Redeemed( address indexed _user, uint256[] _tokenIds, uint256 _amount, uint256 _fee, address _token ); /// /// /// /// @notice initialize newly created vault /// @param _params vault params function initialize(VaultParams memory _params) public initializer { __Ownable_init(); __ReentrancyGuard_init(); require(_params.ownerInfos.length == 2, "INFOS_MISSING"); ownerName = _params.ownerInfos[0]; ownerDescription = _params.ownerInfos[1]; ownerContacts = _params.ownerContacts; ownerWallet = _params.ownerWallet; manager = BalanceVaultManager(msg.sender); nft = BalanceVaultShare(_params.nftAddress); fundingAmount = _params.fundingAmount; for (uint256 i = 0; i < _params.allowedTokens.length; i++) { allowedTokens.add(_params.allowedTokens[i]); } freezeTimestamp = _params.freezeTimestamp; repaymentTimestamp = _params.repaymentTimestamp; apr = _params.apr; feeBorrower = _params.feeBorrower; feeLenderUsdb = _params.feeLenderUsdb; feeLenderOther = _params.feeLenderOther; } /// /// business logic /// /// @notice ROI /// @param _amount amount with which its counted /// @return return of investment based on freeze timestamp and repayment timestamp function roi(uint256 _amount) public view returns (uint256) { uint256 yieldSeconds = repaymentTimestamp - freezeTimestamp; return (_amount * yieldSeconds * apr) / 10000 / 31536000; } /// @notice get current fundraised amount /// @return total amount fundraised summarized according to token decimals in 18 decimals function fundraised() public view returns (uint256) { uint256 totalFundraised = 0; address[] memory tokens = allowedTokens.values(); for (uint256 i = 0; i < tokens.length; i++) { ERC20Upgradeable token = ERC20Upgradeable(tokens[i]); totalFundraised += token.balanceOf(address(this)) * 10**(18 - token.decimals()); } return totalFundraised; } /// @notice get address of repay token /// @return repay token address function repayToken() public view returns (address) { return allowedTokens.values()[0]; } /// @notice get all allowed tokens /// @return all all allowed tokens function getAllowedTokens() external view returns (address[] memory) { return allowedTokens.values(); } function getOwnerContacts() external view returns (string[] memory) { return ownerContacts; } /// @notice return all NFTs of given user /// @param _owner user /// @return all token ids of given user function tokensOfOwner(address _owner) public view returns (uint256[] memory) { return nft.tokensOfOwner(_owner); } /// @notice get balances from all user NFTs /// @param _owner user /// @return _amounts all user balance in tokens decimals and, _tokens all user tokens function balanceOf(address _owner) public view returns (uint256[] memory _amounts, address[] memory _tokens) { uint256[] memory tokenIds = tokensOfOwner(_owner); (_amounts, _tokens) = balanceOf(tokenIds); } /// @notice get balances from all user NFTs /// @param _tokenIds token ids which we want to count balance /// @return _amounts all user balance in token decimals and _tokens all user tokens function balanceOf(uint256[] memory _tokenIds) public view returns (uint256[] memory _amounts, address[] memory _tokens) { if (_tokenIds.length == 0) { _amounts = new uint256[](0); _tokens = new address[](0); return (_amounts, _tokens); } uint256[] memory tmpAmounts; address[] memory tmpTokens; for (uint256 i = 0; i < _tokenIds.length; i++) { (uint256[] memory amounts, address[] memory tokens) = nft .getAmountInfos(_tokenIds[i]); for (uint256 j = 0; j < tokens.length; j++) { // FIXME performance tmpAmounts = withAmount( tmpAmounts, tmpTokens, amounts[j], tokens[j] ); tmpTokens = withToken(tmpTokens, tokens[j]); } } (_amounts, _tokens) = unique(tmpAmounts, tmpTokens); } /// @return true if timestamp > freezeTimestamp or hard cap was reached function shouldBeFrozen() public view returns (bool) { return block.timestamp > freezeTimestamp || fundraised() == fundingAmount; } /// @notice deposit amount of given token into the vault /// @param _amount amount of token /// @param _token token ca /// @return _tokenId tokenId of currently minted nft function deposit(uint256 _amount, address _token) external nonReentrant returns (uint256 _tokenId) { require(allowedTokens.contains(_token), "TOKEN_NOT_WHITELISTED"); require(!shouldBeFrozen(), "SHOULD_BE_FROZEN"); uint256 remaining = fundingAmount - fundraised(); uint256 remainingSameUnits = remaining / 10**(18 - ERC20Upgradeable(_token).decimals()); require(_amount <= remainingSameUnits, "AMOUNT_TOO_BIG"); IERC20Upgradeable(_token).safeTransferFrom( msg.sender, address(this), _amount ); // collect previous deposits uint256[] memory tokenIds = tokensOfOwner(msg.sender); (uint256[] memory amounts, address[] memory tokens) = balanceOf( tokenIds ); // burn previous state for (uint256 i = 0; i < tokenIds.length; i++) { nft.burn(tokenIds[i]); } // mint new state amounts = withAmount(amounts, tokens, _amount, _token); tokens = withToken(tokens, _token); _tokenId = nft.mint(msg.sender, amounts, tokens); emit Deposited(msg.sender, _amount, _token, _tokenId); } /// @notice premature withdraw all your funds from vault, burn all your nfts without get any APR function withdraw() external nonReentrant { // in case the vault owner doesn't freeze the vault, if repaymentTimestamp < block.timestamp, allow withdrawing funds // so that the funds aren't stucked forever require( !shouldBeFrozen() || (!frozen && repaymentTimestamp < block.timestamp), "SHOULD_BE_FROZEN" ); // collect previous deposits uint256[] memory tokenIds = tokensOfOwner(msg.sender); require(tokenIds.length > 0, "NFTS_NOT_FOUND"); (uint256[] memory amounts, address[] memory tokens) = balanceOf( tokenIds ); // burn previous state for (uint256 i = 0; i < tokenIds.length; i++) { nft.burn(tokenIds[i]); } // remember in history emit Withdrawn(msg.sender, amounts, tokens, tokenIds); // withdraw for (uint256 i = 0; i < tokens.length; i++) { IERC20Upgradeable(tokens[i]).safeTransfer(msg.sender, amounts[i]); } } /// @notice redeem all your NFTs for given APR in usdb, can technically be redeemed before repaymentTimestamp passed\ /// @return _toRepayInRepayToken amount to be repaid in repay token decimals, _feeInRepayToken amount paid in fees in repay token decimals function redeem() external nonReentrant returns (uint256 _toRepayInRepayToken, uint256 _feeInRepayToken) { require(redeemPrepared, "REDEEM_FUNDS_NOT_PREPARED"); // get user holdings uint256[] memory tokenIds = tokensOfOwner(msg.sender); require(tokenIds.length > 0, "NFTS_NOT_FOUND"); // count deposit, yield and fees in repay token (uint256[] memory amounts, address[] memory tokens) = balanceOf( tokenIds ); uint256 toRepaySameUnits = 0; uint256 feeSameUnits = 0; for (uint256 i = 0; i < tokens.length; i++) { uint256 amountSameUnits = amounts[i] * 10**(18 - ERC20Upgradeable(tokens[i]).decimals()); uint256 roiSameUnits = roi(amountSameUnits); toRepaySameUnits += amountSameUnits + roiSameUnits; uint256 originalFee = (roiSameUnits * feeLenderOther) / 10000; if (tokens[i] == manager.USDB()) { originalFee = (roiSameUnits * feeLenderUsdb) / 10000; } // this should always return something, at least amount [0, originalFee] (uint256 amount, uint256 fee) = manager.getDiscountFromFee( msg.sender, originalFee ); // cannot rug existing vaults by adding more fee than there was before // can only add some amount to customers from originalFee if (fee > originalFee) { fee = originalFee; } toRepaySameUnits += amount; feeSameUnits += fee; } // burn user tokens for (uint256 i = 0; i < tokenIds.length; i++) { nft.burn(tokenIds[i]); } // remember in history ERC20Upgradeable token = ERC20Upgradeable(repayToken()); _toRepayInRepayToken = toRepaySameUnits / 10**(18 - token.decimals()); _feeInRepayToken = feeSameUnits / 10**(18 - token.decimals()); emit Redeemed( msg.sender, tokenIds, _toRepayInRepayToken, _feeInRepayToken, address(token) ); // and sent tokens require(_toRepayInRepayToken <= toRepayAmount, "REPAY_OUT_OF_BOUNDS"); token.safeTransfer(msg.sender, _toRepayInRepayToken); token.safeTransfer(manager.DAO(), _feeInRepayToken); } /// @notice construct new array of tokens as a set /// @param _tokens tokens /// @param _token token to add to set /// @return new array of tokens as a set function withToken(address[] memory _tokens, address _token) internal pure returns (address[] memory) { uint256 index = ArrayUtils.arrayIndex(_tokens, _token, _tokens.length); // token not in the list if (index == type(uint256).max) { address[] memory newTokens = new address[](_tokens.length + 1); newTokens[_tokens.length] = _token; return newTokens; } // token already in the list return _tokens; } /// @notice construct new array of amounts from set of tokens /// @param _amounts amounts which are in pair with tokens /// @param _tokens tokens /// @param _amount amount of token to add to amounts from set of tokens /// @param _token token to add to tokens set /// @return new array of amounts from set of tokens function withAmount( uint256[] memory _amounts, address[] memory _tokens, uint256 _amount, address _token ) internal pure returns (uint256[] memory) { require(_amounts.length == _tokens.length, "ARRAY_LEN_NOT_MATCH"); uint256 index = ArrayUtils.arrayIndex(_tokens, _token, _tokens.length); // token not in the list if (index == type(uint256).max) { uint256[] memory newAmounts = new uint256[](_tokens.length + 1); newAmounts[_tokens.length] = _amount; return newAmounts; } // token already in the list _amounts[index] += _amount; return _amounts; } /// @notice creates new arrays of amounts and tokens from given amounts and tokens /// @param _amounts all amounts /// @param _tokens all tokens /// @return _newAmounts new amounts which are paired with _newTokens set, _newTokens set function unique(uint256[] memory _amounts, address[] memory _tokens) internal pure returns (uint256[] memory _newAmounts, address[] memory _newTokens) { require(_amounts.length == _tokens.length, "ARRAY_LEN_NOT_MATCH"); if (_tokens.length == 1) return (_amounts, _tokens); uint256 realTokenCount = 0; uint256[] memory tmpAmounts = new uint256[](_tokens.length); address[] memory tmpTokens = new address[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { uint256 index = ArrayUtils.arrayIndex( tmpTokens, _tokens[i], realTokenCount ); // token is not processed yet if (index == type(uint256).max) { tmpAmounts[realTokenCount] = _amounts[i]; tmpTokens[realTokenCount] = _tokens[i]; realTokenCount++; } // token is already processed else { tmpAmounts[index] += _amounts[i]; } } _newAmounts = new uint256[](realTokenCount); _newTokens = new address[](realTokenCount); for (uint256 i = 0; i < realTokenCount; i++) { _newAmounts[i] = tmpAmounts[i]; _newTokens[i] = tmpTokens[i]; } return (_newAmounts, _newTokens); } /// /// management /// /// @notice change description of existing vault, should not harm existing users /// @param _ownerName name of the vault owner /// @param _ownerDescription description of vault purpose /// @param _ownerContacts contact info of vault owner function changeDescription( string calldata _ownerName, string calldata _ownerDescription, string[] memory _ownerContacts ) external onlyOwner { require(!shouldBeFrozen(), "SHOULDNT_BE_FROZEN"); require(!frozen, "ALREADY_FROZEN"); ownerName = _ownerName; ownerDescription = _ownerDescription; ownerContacts = _ownerContacts; } /// @notice change freezeTimestamp to the future /// @param _freezeTimestamp changed timestamp function setFreezeTimestamp(uint256 _freezeTimestamp) external onlyOwner { require(_freezeTimestamp >= freezeTimestamp, "NEW_VALUE_IS_BEFORE_OLD"); require( _freezeTimestamp < repaymentTimestamp, "SHOULD_BE_BEFORE_REPAYMENT" ); require(!shouldBeFrozen(), "SHOULDNT_BE_FROZEN"); freezeTimestamp = _freezeTimestamp; } /// @notice freeze vault, send fundraised funds into owners wallet, subtracted from vault fee function freeze() external nonReentrant onlyOwner { require(!frozen, "ALREADY_FROZEN"); require(shouldBeFrozen(), "SHOULD_BE_FROZEN"); frozen = true; uint256[] memory amounts = new uint256[](allowedTokens.length()); address[] memory tokens = allowedTokens.values(); // total amount in 18 decimals uint256 totalAmount = 0; for (uint256 i = 0; i < tokens.length; i++) { ERC20Upgradeable token = ERC20Upgradeable(tokens[i]); uint256 balance = token.balanceOf(address(this)); amounts[i] = balance; uint256 balanceSameUnits = balance * 10**(18 - token.decimals()); // add 100% of investment to return totalAmount += balanceSameUnits; // add ROI to lender and fee to DAO from lenders return uint256 yield = roi(balanceSameUnits); if (address(token) == manager.USDB()) { totalAmount += yield + (yield * feeLenderUsdb) / 10000; } else { totalAmount += yield + (yield * feeLenderOther) / 10000; } if (balance > 0) { uint256 toDao = (balance * feeBorrower) / 10000; uint256 toVaultOwner = balance - toDao; token.safeTransfer(ownerWallet, toVaultOwner); token.safeTransfer(manager.DAO(), toDao); } } // set repayment amount in repay token decimals ERC20Upgradeable _repayToken = ERC20Upgradeable(repayToken()); toRepayAmount = totalAmount / 10**(18 - _repayToken.decimals()); emit Frozen( block.timestamp, amounts, tokens, toRepayAmount, address(_repayToken) ); } /// @notice send all funds for redeem /// can be called before redeem timestamp function depositForRedeem() external nonReentrant onlyOwner { require(frozen, "NOT_FROZEN"); require(!redeemPrepared, "REDEEM_ALREADY_PREPARED"); redeemPrepared = true; IERC20Upgradeable(repayToken()).safeTransferFrom( msg.sender, address(this), toRepayAmount ); } /// @notice can recover tokens sent by mistake to this CA, but cannot recover allowed tokens, those will be sent to vault owner on freeze /// @param token CA function recoverTokens(IERC20Upgradeable token) external onlyOwner { address[] memory allowed = allowedTokens.values(); for (uint256 i = 0; i < allowed.length; i++) { require( address(token) != allowed[i], "CANNOT_RECOVER_ALLOWED_TOKEN" ); } token.safeTransfer(owner(), token.balanceOf(address(this))); } function recoverEth() external onlyOwner { payable(owner()).transfer(address(this).balance); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // https://aa.usno.navy.mil/faq/JD_formula.html // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 _days) { require(year >= 1970); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4 + (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101; _days = uint256(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } function timestampFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { (uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { (uint256 year, uint256 month, ) = _daysToDate( timestamp / SECONDS_PER_DAY ); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = ((_days + 3) % 7) + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate( timestamp / SECONDS_PER_DAY ); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate( timestamp / SECONDS_PER_DAY ); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate( timestamp / SECONDS_PER_DAY ); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate( timestamp / SECONDS_PER_DAY ); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, uint256 fromMonth, ) = _daysToDate( fromTimestamp / SECONDS_PER_DAY ); (uint256 toYear, uint256 toMonth, ) = _daysToDate( toTimestamp / SECONDS_PER_DAY ); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @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 * ==== * * [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(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) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason 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 { // 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 (token/ERC20/extensions/draft-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 IERC20PermitUpgradeable { /** * @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 // ERC721A Contracts v4.2.2 // Creator: Chiru Labs pragma solidity ^0.8.4; import '../IERC721AUpgradeable.sol'; /** * @dev Interface of ERC721AQueryable. */ interface IERC721AQueryableUpgradeable is IERC721AUpgradeable { /** * Invalid query range (`start` >= `stop`). */ error InvalidQueryRange(); /** * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting. * * If the `tokenId` is out of bounds: * * - `addr = address(0)` * - `startTimestamp = 0` * - `burned = false` * - `extraData = 0` * * If the `tokenId` is burned: * * - `addr = <Address of owner before token was burned>` * - `startTimestamp = <Timestamp when token was burned>` * - `burned = true` * - `extraData = <Extra data when token was burned>` * * Otherwise: * * - `addr = <Address of owner>` * - `startTimestamp = <Timestamp of start of ownership>` * - `burned = false` * - `extraData = <Extra data at start of ownership>` */ function explicitOwnershipOf(uint256 tokenId) external view returns (TokenOwnership memory); /** * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order. * See {ERC721AQueryable-explicitOwnershipOf} */ function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory); /** * @dev Returns an array of token IDs owned by `owner`, * in the range [`start`, `stop`) * (i.e. `start <= tokenId < stop`). * * This function allows for tokens to be queried if the collection * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. * * Requirements: * * - `start < stop` */ function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) external view returns (uint256[] memory); /** * @dev Returns an array of token IDs owned by `owner`. * * This function scans the ownership mapping and is O(`totalSupply`) in complexity. * It is meant to be called off-chain. * * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into * multiple smaller scans if the collection is large enough to cause * an out-of-gas error (10K collections should be fine). */ function tokensOfOwner(address owner) external view returns (uint256[] memory); }
// SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.2 // Creator: Chiru Labs pragma solidity ^0.8.4; import './IERC721AUpgradeable.sol'; import {ERC721AStorage} from './ERC721AStorage.sol'; import './ERC721A__Initializable.sol'; /** * @dev Interface of ERC721 token receiver. */ interface ERC721A__IERC721ReceiverUpgradeable { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC721A * * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721) * Non-Fungible Token Standard, including the Metadata extension. * Optimized for lower gas during batch mints. * * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...) * starting from `_startTokenId()`. * * Assumptions: * * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721AUpgradeable is ERC721A__Initializable, IERC721AUpgradeable { using ERC721AStorage for ERC721AStorage.Layout; // ============================================================= // CONSTANTS // ============================================================= // Mask of an entry in packed address data. uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; // The bit position of `numberMinted` in packed address data. uint256 private constant _BITPOS_NUMBER_MINTED = 64; // The bit position of `numberBurned` in packed address data. uint256 private constant _BITPOS_NUMBER_BURNED = 128; // The bit position of `aux` in packed address data. uint256 private constant _BITPOS_AUX = 192; // Mask of all 256 bits in packed address data except the 64 bits for `aux`. uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; // The bit position of `startTimestamp` in packed ownership. uint256 private constant _BITPOS_START_TIMESTAMP = 160; // The bit mask of the `burned` bit in packed ownership. uint256 private constant _BITMASK_BURNED = 1 << 224; // The bit position of the `nextInitialized` bit in packed ownership. uint256 private constant _BITPOS_NEXT_INITIALIZED = 225; // The bit mask of the `nextInitialized` bit in packed ownership. uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225; // The bit position of `extraData` in packed ownership. uint256 private constant _BITPOS_EXTRA_DATA = 232; // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`. uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1; // The mask of the lower 160 bits for addresses. uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1; // The maximum `quantity` that can be minted with {_mintERC2309}. // This limit is to prevent overflows on the address data entries. // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309} // is required to cause an overflow, which is unrealistic. uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000; // The `Transfer` event signature is given by: // `keccak256(bytes("Transfer(address,address,uint256)"))`. bytes32 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; // ============================================================= // CONSTRUCTOR // ============================================================= function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializingERC721A { __ERC721A_init_unchained(name_, symbol_); } function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializingERC721A { ERC721AStorage.layout()._name = name_; ERC721AStorage.layout()._symbol = symbol_; ERC721AStorage.layout()._currentIndex = _startTokenId(); } // ============================================================= // TOKEN COUNTING OPERATIONS // ============================================================= /** * @dev Returns the starting token ID. * To change the starting token ID, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Returns the next token ID to be minted. */ function _nextTokenId() internal view virtual returns (uint256) { return ERC721AStorage.layout()._currentIndex; } /** * @dev Returns the total number of tokens in existence. * Burned tokens will reduce the count. * To get the total number of tokens minted, please see {_totalMinted}. */ function totalSupply() public view virtual override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than `_currentIndex - _startTokenId()` times. unchecked { return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId(); } } /** * @dev Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view virtual returns (uint256) { // Counter underflow is impossible as `_currentIndex` does not decrement, // and it is initialized to `_startTokenId()`. unchecked { return ERC721AStorage.layout()._currentIndex - _startTokenId(); } } /** * @dev Returns the total number of tokens burned. */ function _totalBurned() internal view virtual returns (uint256) { return ERC721AStorage.layout()._burnCounter; } // ============================================================= // ADDRESS DATA OPERATIONS // ============================================================= /** * @dev Returns the number of tokens in `owner`'s account. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return ERC721AStorage.layout()._packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return uint64(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_AUX); } /** * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal virtual { uint256 packed = ERC721AStorage.layout()._packedAddressData[owner]; uint256 auxCasted; // Cast `aux` with assembly to avoid redundant masking. assembly { auxCasted := aux } packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX); ERC721AStorage.layout()._packedAddressData[owner] = packed; } // ============================================================= // IERC165 // ============================================================= /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // The interface IDs are constants representing the first 4 bytes // of the XOR of all function selectors in the interface. // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165) // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`) return interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165. interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721. interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata. } // ============================================================= // IERC721Metadata // ============================================================= /** * @dev Returns the token collection name. */ function name() public view virtual override returns (string memory) { return ERC721AStorage.layout()._name; } /** * @dev Returns the token collection symbol. */ function symbol() public view virtual override returns (string memory) { return ERC721AStorage.layout()._symbol; } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, it can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } // ============================================================= // OWNERSHIPS OPERATIONS // ============================================================= /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return address(uint160(_packedOwnershipOf(tokenId))); } /** * @dev Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around over time. */ function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnershipOf(tokenId)); } /** * @dev Returns the unpacked `TokenOwnership` struct at `index`. */ function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(ERC721AStorage.layout()._packedOwnerships[index]); } /** * @dev Initializes the ownership slot minted at `index` for efficiency purposes. */ function _initializeOwnershipAt(uint256 index) internal virtual { if (ERC721AStorage.layout()._packedOwnerships[index] == 0) { ERC721AStorage.layout()._packedOwnerships[index] = _packedOwnershipOf(index); } } /** * Returns the packed ownership data of `tokenId`. */ function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < ERC721AStorage.layout()._currentIndex) { uint256 packed = ERC721AStorage.layout()._packedOwnerships[curr]; // If not burned. if (packed & _BITMASK_BURNED == 0) { // Invariant: // There will always be an initialized ownership slot // (i.e. `ownership.addr != address(0) && ownership.burned == false`) // before an unintialized ownership slot // (i.e. `ownership.addr == address(0) && ownership.burned == false`) // Hence, `curr` will not underflow. // // We can directly compare the packed value. // If the address is zero, packed will be zero. while (packed == 0) { packed = ERC721AStorage.layout()._packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } /** * @dev Returns the unpacked `TokenOwnership` struct from `packed`. */ function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) { ownership.addr = address(uint160(packed)); ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP); ownership.burned = packed & _BITMASK_BURNED != 0; ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA); } /** * @dev Packs ownership data into a single uint256. */ function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) { assembly { // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean. owner := and(owner, _BITMASK_ADDRESS) // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`. result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags)) } } /** * @dev Returns the `nextInitialized` flag set if `quantity` equals 1. */ function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) { // For branchless setting of the `nextInitialized` flag. assembly { // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`. result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1)) } } // ============================================================= // APPROVAL OPERATIONS // ============================================================= /** * @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) public virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } ERC721AStorage.layout()._tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); } /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return ERC721AStorage.layout()._tokenApprovals[tokenId].value; } /** * @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) public virtual override { if (operator == _msgSenderERC721A()) revert ApproveToCaller(); ERC721AStorage.layout()._operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); } /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return ERC721AStorage.layout()._operatorApprovals[owner][operator]; } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted. See {_mint}. */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _startTokenId() <= tokenId && tokenId < ERC721AStorage.layout()._currentIndex && // If within bounds, ERC721AStorage.layout()._packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned. } /** * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`. */ function _isSenderApprovedOrOwner( address approvedAddress, address owner, address msgSender ) private pure returns (bool result) { assembly { // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean. owner := and(owner, _BITMASK_ADDRESS) // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean. msgSender := and(msgSender, _BITMASK_ADDRESS) // `msgSender == owner || msgSender == approvedAddress`. result := or(eq(msgSender, owner), eq(msgSender, approvedAddress)) } } /** * @dev Returns the storage slot and value for the approved address of `tokenId`. */ function _getApprovedSlotAndAddress(uint256 tokenId) private view returns (uint256 approvedAddressSlot, address approvedAddress) { ERC721AStorage.TokenApprovalRef storage tokenApproval = ERC721AStorage.layout()._tokenApprovals[tokenId]; // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`. assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) } } // ============================================================= // TRANSFER OPERATIONS // ============================================================= /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) public virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId); // The nested ifs save around 20+ gas over a compound boolean condition. if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner. assembly { if approvedAddress { // This is equivalent to `delete _tokenApprovals[tokenId]`. sstore(approvedAddressSlot, 0) } } // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256. unchecked { // We can directly increment and decrement the balances. --ERC721AStorage.layout()._packedAddressData[from]; // Updates: `balance -= 1`. ++ERC721AStorage.layout()._packedAddressData[to]; // Updates: `balance += 1`. // Updates: // - `address` to the next owner. // - `startTimestamp` to the timestamp of transfering. // - `burned` to `false`. // - `nextInitialized` to `true`. ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); // If the next slot may not have been initialized (i.e. `nextInitialized == false`) . if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; // If the next slot's address is zero and not burned (i.e. packed value is zero). if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) { // If the next slot is within bounds. if (nextTokenId != ERC721AStorage.layout()._currentIndex) { // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @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 memory _data ) public virtual override { transferFrom(from, to, tokenId); if (to.code.length != 0) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Hook that is called before a set of serially-ordered token IDs * are about to be transferred. This includes minting. * And also called before burning one token. * * `startTokenId` - the first token ID to be transferred. * `quantity` - the amount to be transferred. * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token IDs * have been transferred. This includes minting. * And also called after one token has been burned. * * `startTokenId` - the first token ID to be transferred. * `quantity` - the amount to be transferred. * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * `from` - Previous owner of the given token ID. * `to` - Target address that will receive the token. * `tokenId` - Token ID to be transferred. * `_data` - Optional data to send along with the call. * * Returns whether the call correctly returned the expected magic value. */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (bytes4 retval) { return retval == ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } // ============================================================= // MINT OPERATIONS // ============================================================= /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event for each mint. */ function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = ERC721AStorage.layout()._currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // `balance` and `numberMinted` have a maximum limit of 2**64. // `tokenId` has a maximum limit of 2**256. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 toMasked; uint256 end = startTokenId + quantity; // Use assembly to loop and emit the `Transfer` event for gas savings. // The duplicated `log4` removes an extra check and reduces stack juggling. // The assembly, together with the surrounding Solidity code, have been // delicately arranged to nudge the compiler into producing optimized opcodes. assembly { // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. toMasked := and(to, _BITMASK_ADDRESS) // Emit the `Transfer` event. log4( 0, // Start of data (0, since no data). 0, // End of data (0, since no data). _TRANSFER_EVENT_SIGNATURE, // Signature. 0, // `address(0)`. toMasked, // `to`. startTokenId // `tokenId`. ) for { let tokenId := add(startTokenId, 1) } iszero(eq(tokenId, end)) { tokenId := add(tokenId, 1) } { // Emit the `Transfer` event. Similar to above. log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); ERC721AStorage.layout()._currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * This function is intended for efficient minting only during contract creation. * * It emits only one {ConsecutiveTransfer} as defined in * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309), * instead of a sequence of {Transfer} event(s). * * Calling this function outside of contract creation WILL make your contract * non-compliant with the ERC721 standard. * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309 * {ConsecutiveTransfer} event is only permissible during contract creation. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {ConsecutiveTransfer} event. */ function _mintERC2309(address to, uint256 quantity) internal virtual { uint256 startTokenId = ERC721AStorage.layout()._currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are unrealistic due to the above check for `quantity` to be below the limit. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to); ERC721AStorage.layout()._currentIndex = startTokenId + quantity; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * See {_mint}. * * Emits a {Transfer} event for each mint. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = ERC721AStorage.layout()._currentIndex; uint256 index = end - quantity; do { if (!_checkContractOnERC721Received(address(0), to, index++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); // Reentrancy protection. if (ERC721AStorage.layout()._currentIndex != end) revert(); } } } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ''); } // ============================================================= // BURN OPERATIONS // ============================================================= /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { // The nested ifs save around 20+ gas over a compound boolean condition. if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner. assembly { if approvedAddress { // This is equivalent to `delete _tokenApprovals[tokenId]`. sstore(approvedAddressSlot, 0) } } // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256. unchecked { // Updates: // - `balance -= 1`. // - `numberBurned += 1`. // // We can directly decrement the balance, and increment the number burned. // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`. ERC721AStorage.layout()._packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; // Updates: // - `address` to the last owner. // - `startTimestamp` to the timestamp of burning. // - `burned` to `true`. // - `nextInitialized` to `true`. ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); // If the next slot may not have been initialized (i.e. `nextInitialized == false`) . if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; // If the next slot's address is zero and not burned (i.e. packed value is zero). if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) { // If the next slot is within bounds. if (nextTokenId != ERC721AStorage.layout()._currentIndex) { // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { ERC721AStorage.layout()._burnCounter++; } } // ============================================================= // EXTRA DATA OPERATIONS // ============================================================= /** * @dev Directly sets the extra data for the ownership data `index`. */ function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual { uint256 packed = ERC721AStorage.layout()._packedOwnerships[index]; if (packed == 0) revert OwnershipNotInitializedForExtraData(); uint256 extraDataCasted; // Cast `extraData` with assembly to avoid redundant masking. assembly { extraDataCasted := extraData } packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA); ERC721AStorage.layout()._packedOwnerships[index] = packed; } /** * @dev Called during each token transfer to set the 24bit `extraData` field. * Intended to be overridden by the cosumer contract. * * `previousExtraData` - the value of `extraData` before transfer. * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _extraData( address from, address to, uint24 previousExtraData ) internal view virtual returns (uint24) {} /** * @dev Returns the next extra data for the packed ownership data. * The returned result is shifted into position. */ function _nextExtraData( address from, address to, uint256 prevOwnershipPacked ) private view returns (uint256) { uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA); return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA; } // ============================================================= // OTHER OPERATIONS // ============================================================= /** * @dev Returns the message sender (defaults to `msg.sender`). * * If you are writing GSN compatible contracts, you need to override this function. */ function _msgSenderERC721A() internal view virtual returns (address) { return msg.sender; } /** * @dev Converts a uint256 to its ASCII string decimal representation. */ function _toString(uint256 value) internal pure virtual returns (string memory str) { assembly { // The maximum value of a uint256 contains 78 digits (1 byte per digit), // but we allocate 0x80 bytes to keep the free memory pointer 32-byte word aligned. // We will need 1 32-byte word to store the length, // and 3 32-byte words to store a maximum of 78 digits. Total: 0x20 + 3 * 0x20 = 0x80. str := add(mload(0x40), 0x80) // Update the free memory pointer to allocate. mstore(0x40, str) // Cache the end of the memory to calculate the length later. let end := str // We write the string from rightmost digit to leftmost digit. // The following is essentially a do-while loop that also handles the zero case. // prettier-ignore for { let temp := value } 1 {} { str := sub(str, 1) // Write the character to the pointer. // The ASCII index of the '0' character is 48. mstore8(str, add(48, mod(temp, 10))) // Keep dividing `temp` until zero. temp := div(temp, 10) // prettier-ignore if iszero(temp) { break } } let length := sub(end, str) // Move the pointer 32 bytes leftwards to make room for the length. str := sub(str, 0x20) // Store the length. mstore(str, length) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable diamond facet contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ import {ERC721A__InitializableStorage} from './ERC721A__InitializableStorage.sol'; abstract contract ERC721A__Initializable { using ERC721A__InitializableStorage for ERC721A__InitializableStorage.Layout; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializerERC721A() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require( ERC721A__InitializableStorage.layout()._initializing ? _isConstructor() : !ERC721A__InitializableStorage.layout()._initialized, 'ERC721A__Initializable: contract is already initialized' ); bool isTopLevelCall = !ERC721A__InitializableStorage.layout()._initializing; if (isTopLevelCall) { ERC721A__InitializableStorage.layout()._initializing = true; ERC721A__InitializableStorage.layout()._initialized = true; } _; if (isTopLevelCall) { ERC721A__InitializableStorage.layout()._initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializingERC721A() { require( ERC721A__InitializableStorage.layout()._initializing, 'ERC721A__Initializable: contract is not initializing' ); _; } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } }
// SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.2 // Creator: Chiru Labs pragma solidity ^0.8.4; /** * @dev Interface of ERC721A. */ interface IERC721AUpgradeable { /** * The caller must own the token or be an approved operator. */ error ApprovalCallerNotOwnerNorApproved(); /** * The token does not exist. */ error ApprovalQueryForNonexistentToken(); /** * The caller cannot approve to their own address. */ error ApproveToCaller(); /** * Cannot query the balance for the zero address. */ error BalanceQueryForZeroAddress(); /** * Cannot mint to the zero address. */ error MintToZeroAddress(); /** * The quantity of tokens minted must be more than zero. */ error MintZeroQuantity(); /** * The token does not exist. */ error OwnerQueryForNonexistentToken(); /** * The caller must own the token or be an approved operator. */ error TransferCallerNotOwnerNorApproved(); /** * The token must be owned by `from`. */ error TransferFromIncorrectOwner(); /** * Cannot safely transfer to a contract that does not implement the * ERC721Receiver interface. */ error TransferToNonERC721ReceiverImplementer(); /** * Cannot transfer to the zero address. */ error TransferToZeroAddress(); /** * The token does not exist. */ error URIQueryForNonexistentToken(); /** * The `quantity` minted with ERC2309 exceeds the safety limit. */ error MintERC2309QuantityExceedsLimit(); /** * The `extraData` cannot be set on an unintialized ownership slot. */ error OwnershipNotInitializedForExtraData(); // ============================================================= // STRUCTS // ============================================================= struct TokenOwnership { // The address of the owner. address addr; // Stores the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}. uint24 extraData; } // ============================================================= // TOKEN COUNTERS // ============================================================= /** * @dev Returns the total number of tokens in existence. * Burned tokens will reduce the count. * To get the total number of tokens minted, please see {_totalMinted}. */ function totalSupply() external view returns (uint256); // ============================================================= // IERC165 // ============================================================= /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); // ============================================================= // IERC721 // ============================================================= /** * @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`, * 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. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; /** * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` 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. */ 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); // ============================================================= // IERC721Metadata // ============================================================= /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); // ============================================================= // IERC2309 // ============================================================= /** * @dev Emitted when tokens in `fromTokenId` to `toTokenId` * (inclusive) is transferred from `from` to `to`, as defined in the * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard. * * See {_mintERC2309} for more details. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC721AStorage { // Reference type for token approval. struct TokenApprovalRef { address value; } struct Layout { // ============================================================= // STORAGE // ============================================================= // The next token ID to be minted. uint256 _currentIndex; // The number of tokens burned. uint256 _burnCounter; // Token name string _name; // Token symbol string _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. // See {_packedOwnershipOf} implementation for details. // // Bits Layout: // - [0..159] `addr` // - [160..223] `startTimestamp` // - [224] `burned` // - [225] `nextInitialized` // - [232..255] `extraData` mapping(uint256 => uint256) _packedOwnerships; // Mapping owner address to address data. // // Bits Layout: // - [0..63] `balance` // - [64..127] `numberMinted` // - [128..191] `numberBurned` // - [192..255] `aux` mapping(address => uint256) _packedAddressData; // Mapping from token ID to approved address. mapping(uint256 => ERC721AStorage.TokenApprovalRef) _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) _operatorApprovals; } bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.ERC721A'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base storage for the initialization function for upgradeable diamond facet contracts **/ library ERC721A__InitializableStorage { struct Layout { /* * Indicates that the contract has been initialized. */ bool _initialized; /* * Indicates that the contract is in the process of being initialized. */ bool _initializing; } bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.initializable.facet'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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() { // On the first call to nonReentrant, _notEntered will be true require(_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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet. * ==== */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./BalanceVault.sol"; import "./BalanceVaultShare.sol"; import "../utils/ArrayUtils.sol"; interface IBalancePassManager { function getDiscountFromFee(address _user, uint256 _fee) external view returns (uint256, uint256); } /// @notice Creates new balance vaults /// @author Balance Capital https://www.balance.capital/, [email protected] contract BalanceVaultManager is Ownable, AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); address public immutable DAO; address public immutable USDB; address public vaultTemplate; address public nftTemplate; /// fee on borrowers total amount raised, 2 decimals percent, 100% is 10000 uint256 public feeBorrower; /// fee on lenders return in case usdb is used, 2 decimals percent, 100% is 10000 uint256 public feeLenderUsdb; /// fee on lenders return in case other token is used, 2 decimals percent, 100% is 10000 uint256 public feeLenderOther; /// vetted tokens address[] public allowedTokens; mapping(address => bool) public allowedTokensMapping; /// extension to support configurable discounts address public balancePassManager; /// repository for all generated vaults address[] generatedVaults; mapping(address => bool) generatedVaultsWhitelist; struct BalanceVaultDto { address vaultAddress; uint256 index; address nftAddress; string[] ownerInfos; string[] ownerContacts; address ownerWallet; uint256 fundingAmount; uint256 fundraised; address[] allowedTokens; uint256 freezeTimestamp; uint256 repaymentTimestamp; uint256 apr; bool shouldBeFrozen; } struct BalanceVaultPositionDto { address vaultAddress; uint256 index; address nftAddress; address user; uint256[] amounts; address[] tokens; } /// @param _DAO gnosis multisig address /// @param _USDB usdb address /// @param _feeBorrower fee on borrowers total amount raised, 2 decimals percent, 100% is 10000 /// @param _feeLenderUsdb fee on lenders return in case usdb is used, 2 decimals percent, 100% is 10000 /// @param _feeLenderOther fee on lenders return in case other token is used, 2 decimals percent, 100% is 10000 constructor( address _DAO, address _USDB, uint256 _feeBorrower, uint256 _feeLenderUsdb, uint256 _feeLenderOther ) { require(_DAO != address(0)); DAO = _DAO; require(_USDB != address(0)); USDB = _USDB; feeBorrower = _feeBorrower; feeLenderUsdb = _feeLenderUsdb; feeLenderOther = _feeLenderOther; setAllowedToken(_USDB); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MANAGER_ROLE, _msgSender()); } /// /// events /// /// @notice informs about creating new vault /// @param _creator caller of the function /// @param _vault CA of the vault /// @param _vaultTemplate vault template CA from which it was created /// @param _nftTemplate nft template CA which is used for share event VaultCreated( address _creator, address _vault, address _vaultTemplate, address _nftTemplate ); event LogBytes(bytes data); /// /// business logic /// /// @notice creates new vault /// @param _ownerInfos name, description /// @param _ownerContacts contact info like twitter links, website, etc /// @param _ownerWallet wallet of the owner where funds will be managed /// @param _fundingAmount funding of the vault, with 18 decimals /// @param _allowedTokens allowed tokens which are 1:1 used for funding /// @param _freezeTimestamp timestamp to freeze this fundrising /// @param _repaymentTimestamp timestamp to the payout of given APR /// @param _apr apr in 2 decimals, 10000 is 100% /// @return _vaultAddress actual address of preconfigured vault function createVault( string[] calldata _ownerInfos, string[] calldata _ownerContacts, address _ownerWallet, uint256 _fundingAmount, address[] calldata _allowedTokens, uint256 _freezeTimestamp, uint256 _repaymentTimestamp, uint256 _apr ) external nonReentrant returns (address _vaultAddress) { require(vaultTemplate != address(0), "MISSING_VAULT_TEMPLATE"); require(nftTemplate != address(0), "MISSING_NFT_TEMPLATE"); require( _freezeTimestamp < _repaymentTimestamp, "VAULT_FREEZE_SHOULD_BE_BEFORE_PAYOUT" ); require( _freezeTimestamp > block.timestamp, "VAULT_FREEZE_SHOULD_BE_IN_FUTURE" ); require(_ownerInfos.length == 2, "INFOS_MISSING"); for (uint256 i = 0; i < _allowedTokens.length; i++) { require( allowedTokensMapping[_allowedTokens[i]], "TOKEN_NOT_ALLOWED" ); } // EIP1167 clone factory _vaultAddress = Clones.clone(vaultTemplate); address nftAddress = Clones.clone(nftTemplate); VaultParams memory param = VaultParams({ ownerInfos: _ownerInfos, ownerContacts: _ownerContacts, ownerWallet: _ownerWallet, nftAddress: nftAddress, fundingAmount: _fundingAmount, allowedTokens: _allowedTokens, freezeTimestamp: _freezeTimestamp, repaymentTimestamp: _repaymentTimestamp, apr: _apr, feeBorrower: feeBorrower, feeLenderUsdb: feeLenderUsdb, feeLenderOther: feeLenderOther }); BalanceVault vault = BalanceVault(_vaultAddress); vault.initialize(param); vault.transferOwnership(msg.sender); BalanceVaultShare share = BalanceVaultShare(nftAddress); share.initialize(_vaultAddress); // owner of NFT is only for transferring tokens sent to NFT CA by mistake share.transferOwnership(msg.sender); // persist in paging repository generatedVaults.push(_vaultAddress); // remember in history emit VaultCreated( msg.sender, _vaultAddress, vaultTemplate, nftTemplate ); } /// @notice get amount and fee part from fee /// @param _user given user /// @param _fee fee to split /// @return amount and fee part from given fee function getDiscountFromFee(address _user, uint256 _fee) external returns (uint256, uint256) { if (balancePassManager == address(0)) return (0, _fee); try IBalancePassManager(balancePassManager).getDiscountFromFee( _user, _fee ) returns (uint256 _amount, uint256 _finalFee) { return (_amount, _finalFee); } catch (bytes memory reason) { emit LogBytes(reason); } return (0, _fee); } /// /// paging /// /// @notice get generated vaults length for paging /// @return generated vaults length for paging function getGeneratedVaultsLength() external view returns (uint256) { return generatedVaults.length; } /// @notice skip/limit paging on-chain impl /// @param _skip how many items from beginning to skip /// @param _limit how many items to return in result which are not blacklisted /// @return page of BalanceVaultDto function getGeneratedVaultsPage(uint256 _skip, uint256 _limit) external view returns (BalanceVaultDto[] memory) { if (_skip >= generatedVaults.length) return new BalanceVaultDto[](0); uint256 limit = Math.min(_skip + _limit, generatedVaults.length); BalanceVaultDto[] memory page = new BalanceVaultDto[](limit); uint256 index = 0; for (uint256 i = _skip; i < limit; i++) { BalanceVault vault = BalanceVault(generatedVaults[i]); // do not send not vetted vaults to the frontend if (!generatedVaultsWhitelist[address(vault)]) continue; string[] memory ownerInfos = new string[](2); ownerInfos[0] = vault.ownerName(); ownerInfos[1] = vault.ownerDescription(); page[index++] = BalanceVaultDto({ vaultAddress: address(vault), index: i, nftAddress: address(vault.nft()), ownerInfos: ownerInfos, ownerContacts: vault.getOwnerContacts(), ownerWallet: vault.ownerWallet(), fundingAmount: vault.fundingAmount(), fundraised: vault.fundraised(), allowedTokens: vault.getAllowedTokens(), freezeTimestamp: vault.freezeTimestamp(), repaymentTimestamp: vault.repaymentTimestamp(), apr: vault.apr(), shouldBeFrozen: vault.shouldBeFrozen() }); } return page; } /// @notice skip/limit paging on-chain impl /// @param _user user address /// @param _skip how many items from beginning to skip /// @param _limit how many items to return in result /// @return page of BalanceVaultPositionDto function getPositionsPage( address _user, uint256 _skip, uint256 _limit ) external view returns (BalanceVaultPositionDto[] memory) { if (_skip >= generatedVaults.length) return new BalanceVaultPositionDto[](0); uint256 limit = Math.min(_skip + _limit, generatedVaults.length); BalanceVaultPositionDto[] memory page = new BalanceVaultPositionDto[]( limit ); uint256 index = 0; for (uint256 i = _skip; i < limit; i++) { BalanceVault vault = BalanceVault(generatedVaults[i]); // do not send not vetted vaults to the frontend if (!generatedVaultsWhitelist[address(vault)]) continue; (uint256[] memory _amounts, address[] memory _tokens) = vault .balanceOf(_user); // do not send empty positions to the frontend if (_amounts.length == 0) continue; page[index++] = BalanceVaultPositionDto({ vaultAddress: address(vault), index: i, nftAddress: address(vault.nft()), user: _user, amounts: _amounts, tokens: _tokens }); } return page; } /// @notice when created vault is vetted, operator will add it into the currated list /// @param _contractAddress vault CA /// @param _add true if addition function modifyGeneratedVaultWhitelist(address _contractAddress, bool _add) external { require(hasRole(MANAGER_ROLE, _msgSender()), "MANAGER_ROLE_MISSING"); if (_add) { require( !generatedVaultsWhitelist[_contractAddress], "ALREADY_IN_WHITELIST" ); generatedVaultsWhitelist[_contractAddress] = true; } else { require( generatedVaultsWhitelist[_contractAddress], "NOT_IN_WHITELIST" ); delete generatedVaultsWhitelist[_contractAddress]; } } /// /// management /// /// @notice change vault template, e.g. can deploy new version with same signature /// @param _vaultTemplate CA for new vault function setVaultTemplate(address _vaultTemplate) external onlyOwner { require(_vaultTemplate != address(0), "EMPTY_ADDRESS"); vaultTemplate = _vaultTemplate; } /// @notice change nft template, e.g. can deploy new version with same signature /// @param _nftTemplate CA for new vault nft function setNftTemplate(address _nftTemplate) external onlyOwner { require(_nftTemplate != address(0), "EMPTY_ADDRESS"); nftTemplate = _nftTemplate; } /// @notice sets fee for total amount raise /// @param _feeBorrower fee on borrowers total amount raised, 2 decimals percent, 100% is 10000 function setFeeBorrower(uint256 _feeBorrower) external onlyOwner { require(_feeBorrower < 2000, "FEE_TOO_HIGH"); feeBorrower = _feeBorrower; } /// @notice sets fee for usdb token /// @param _feeLenderUsdb fee on lenders return in case usdb is used, 2 decimals percent, 100% is 10000 function setFeeLenderUsdb(uint256 _feeLenderUsdb) external onlyOwner { require(_feeLenderUsdb < 3000, "FEE_TOO_HIGH"); feeLenderUsdb = _feeLenderUsdb; } /// @notice sets fee for other tokens /// @param _feeLenderOther fee on lenders return in case other token is used, 2 decimals percent, 100% is 10000 function setFeeLenderOther(uint256 _feeLenderOther) external onlyOwner { require(_feeLenderOther < 3000, "FEE_TOO_HIGH"); feeLenderOther = _feeLenderOther; } /// @notice add allowed token /// @param _token token CA function setAllowedToken(address _token) public onlyOwner { address[] memory tokens = new address[](allowedTokens.length + 1); for (uint256 i = 0; i < allowedTokens.length; i++) { tokens[i] = allowedTokens[i]; require(allowedTokens[i] != _token, "TOKEN_ALREADY_USED"); } tokens[allowedTokens.length] = _token; allowedTokens = tokens; allowedTokensMapping[_token] = true; } /// @notice remove allowed token /// @param _token token to remove with its mapping function removeAllowedToken(address _token) external onlyOwner { uint256 index = ArrayUtils.arrayIndex( allowedTokens, _token, allowedTokens.length ); require(index != type(uint256).max, "TOKEN_NOT_FOUND"); address[] memory tokens = new address[](allowedTokens.length - 1); for (uint256 i = 0; i < allowedTokens.length; i++) { if (i < index) tokens[i] = allowedTokens[i]; else if (i == index) continue; else { tokens[i - 1] = allowedTokens[i]; } } allowedTokens = tokens; allowedTokensMapping[_token] = false; } /// @notice set manager for balance passes /// @param _balancePassManager mgr function setBalancePassManager(address _balancePassManager) external onlyOwner { balancePassManager = _balancePassManager; } function recoverTokens(IERC20 token) external onlyOwner { token.safeTransfer(owner(), token.balanceOf(address(this))); } function recoverEth() external onlyOwner { payable(owner()).transfer(address(this).balance); } /// @notice grants manager role to given _account /// @param _account manager contract function grantRoleManager(address _account) external { grantRole(MANAGER_ROLE, _account); } /// @notice revoke manager role to given _account /// @param _account manager contract function revokeRoleManager(address _account) external { revokeRole(MANAGER_ROLE, _account); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.16; library ArrayUtils { /// @notice return item index in array if exists, or uint max if not /// @param _array array can be empty /// @param _item item to search in array /// @param _arrayLength array length in case not filled array /// @return item index in array or uint max if not found function arrayIndex( address[] memory _array, address _item, uint256 _arrayLength ) internal pure returns (uint256) { require(_array.length >= _arrayLength, "ARR_LEN_TOO_BIG"); for (uint256 i = 0; i < _arrayLength; i++) { if (_array[i] == _item) return i; } return type(uint256).max; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.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 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 { _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.7.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * May emit a {RoleGranted} event. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.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.7.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv( uint256 x, uint256 y, uint256 denominator, Rounding rounding ) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`. // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`. // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a // good first aproximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1; uint256 x = a; if (x >> 128 > 0) { x >>= 128; result <<= 64; } if (x >> 64 > 0) { x >>= 64; result <<= 32; } if (x >> 32 > 0) { x >>= 32; result <<= 16; } if (x >> 16 > 0) { x >>= 16; result <<= 8; } if (x >> 8 > 0) { x >>= 8; result <<= 4; } if (x >> 4 > 0) { x >>= 4; result <<= 2; } if (x >> 2 > 0) { result <<= 1; } // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { uint256 result = sqrt(a); if (rounding == Rounding.Up && result * result < a) { result += 1; } return result; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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() { // On the first call to nonReentrant, _notEntered will be true require(_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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/draft-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; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } 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)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } 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"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } 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"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// 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 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { 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. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^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. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// 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: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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.7.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 * ==== * * [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(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) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(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) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason 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 { // 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); } } } }
{ "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[],"name":"ApprovalCallerNotOwnerNorApproved","type":"error"},{"inputs":[],"name":"ApprovalQueryForNonexistentToken","type":"error"},{"inputs":[],"name":"ApproveToCaller","type":"error"},{"inputs":[],"name":"BalanceQueryForZeroAddress","type":"error"},{"inputs":[],"name":"InvalidQueryRange","type":"error"},{"inputs":[],"name":"MintERC2309QuantityExceedsLimit","type":"error"},{"inputs":[],"name":"MintToZeroAddress","type":"error"},{"inputs":[],"name":"MintZeroQuantity","type":"error"},{"inputs":[],"name":"OwnerQueryForNonexistentToken","type":"error"},{"inputs":[],"name":"OwnershipNotInitializedForExtraData","type":"error"},{"inputs":[],"name":"TransferCallerNotOwnerNorApproved","type":"error"},{"inputs":[],"name":"TransferFromIncorrectOwner","type":"error"},{"inputs":[],"name":"TransferToNonERC721ReceiverImplementer","type":"error"},{"inputs":[],"name":"TransferToZeroAddress","type":"error"},{"inputs":[],"name":"URIQueryForNonexistentToken","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"fromTokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"toTokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"ConsecutiveTransfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"explicitOwnershipOf","outputs":[{"components":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"uint64","name":"startTimestamp","type":"uint64"},{"internalType":"bool","name":"burned","type":"bool"},{"internalType":"uint24","name":"extraData","type":"uint24"}],"internalType":"struct IERC721AUpgradeable.TokenOwnership","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"explicitOwnershipsOf","outputs":[{"components":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"uint64","name":"startTimestamp","type":"uint64"},{"internalType":"bool","name":"burned","type":"bool"},{"internalType":"uint24","name":"extraData","type":"uint24"}],"internalType":"struct IERC721AUpgradeable.TokenOwnership[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getAmountInfos","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getImagePlainText","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getManifestPlainText","outputs":[{"internalType":"string","name":"_manifest","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"uint256","name":"_index","type":"uint256"}],"name":"getTokenAmount","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_vault","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256[]","name":"_amounts","type":"uint256[]"},{"internalType":"address[]","name":"_tokens","type":"address[]"}],"name":"mint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"recoverEth","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"}],"name":"recoverTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"tokensOfOwner","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"stop","type":"uint256"}],"name":"tokensOfOwnerIn","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"contract BalanceVault","name":"","type":"address"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
608060405234801561001057600080fd5b50615544806100206000396000f3fe608060405234801561001057600080fd5b50600436106101e55760003560e01c8063715018a61161010f578063c1ee7c98116100a2578063d7ae223811610071578063d7ae223814610431578063e985e9c514610444578063f2fde38b14610457578063fbfa77cf1461046a57600080fd5b8063c1ee7c98146103d8578063c23dc68f146103eb578063c4d66de81461040b578063c87b56dd1461041e57600080fd5b806399a2557a116100de57806399a2557a14610397578063a22cb465146103aa578063b88d4fde146103bd578063bcdb446b146103d057600080fd5b8063715018a6146103565780638462151c1461035e5780638da5cb5b1461037e57806395d89b411461038f57600080fd5b806323b872dd1161018757806342966c681161015657806342966c68146102fd5780635bbb2177146103105780636352211e1461033057806370a082311461034357600080fd5b806323b872dd146102a35780632c4e872f146102b65780632ec8bd1d146102c957806342842e0e146102ea57600080fd5b8063095ea7b3116101c3578063095ea7b3146102525780630bc1236e1461026757806316114acd1461027a57806318160ddd1461028d57600080fd5b806301ffc9a7146101ea57806306fdde0314610212578063081812fc14610227575b600080fd5b6101fd6101f83660046133d5565b61047d565b60405190151581526020015b60405180910390f35b61021a6104cf565b6040516102099190613442565b61023a610235366004613455565b61056a565b6040516001600160a01b039091168152602001610209565b610265610260366004613483565b6105b7565b005b61021a6102753660046134af565b610665565b6102656102883660046134d1565b6108c5565b61029561095e565b604051908152602001610209565b6102656102b13660046134ee565b61097d565b6102956102c436600461357a565b610b62565b6102dc6102d7366004613455565b610d53565b604051610209929190613637565b6102656102f83660046134ee565b610e1d565b61026561030b366004613455565b610e3d565b61032361031e366004613697565b610ebe565b6040516102099190613714565b61023a61033e366004613455565b610f89565b6102956103513660046134d1565b610f94565b610265610ffc565b61037161036c3660046134d1565b611010565b6040516102099190613756565b6033546001600160a01b031661023a565b61021a611118565b6103716103a5366004613769565b611130565b6102656103b83660046137ac565b6112a8565b6102656103cb366004613852565b61134e565b610265611398565b61021a6103e6366004613455565b6113d9565b6103fe6103f9366004613455565b611bc5565b6040516102099190613900565b6102656104193660046134d1565b611c41565b61021a61042c366004613455565b611f19565b61021a61043f366004613455565b611f5e565b6101fd61045236600461390e565b611fb9565b6102656104653660046134d1565b611ff6565b60655461023a906001600160a01b031681565b60006301ffc9a760e01b6001600160e01b0319831614806104ae57506380ac58cd60e01b6001600160e01b03198316145b806104c95750635b5e139f60e01b6001600160e01b03198316145b92915050565b60606104d961206c565b60020180546104e79061393c565b80601f01602080910402602001604051908101604052809291908181526020018280546105139061393c565b80156105605780601f1061053557610100808354040283529160200191610560565b820191906000526020600020905b81548152906001019060200180831161054357829003601f168201915b5050505050905090565b600061057582612090565b610592576040516333d1c03960e21b815260040160405180910390fd5b61059a61206c565b60009283526006016020525060409020546001600160a01b031690565b60006105c282610f89565b9050336001600160a01b038216146105fb576105de8133611fb9565b6105fb576040516367d9dca160e11b815260040160405180910390fd5b8261060461206c565b6000848152600691909101602052604080822080546001600160a01b0319166001600160a01b0394851617905551849286811692908516917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259190a4505050565b60008281526066602090815260408083208054825181850281018501909352808352606094938301828280156106ba57602002820191906000526020600020905b8154815260200190600101908083116106a6575b5050505050905060006066600086815260200190815260200160002060010180548060200260200160405190810160405280929190818152602001828054801561072d57602002820191906000526020600020905b81546001600160a01b0316815260019091019060200180831161070f575b50505050509050805160001480610745575080518410155b15610777576040518060400160405280600b81526020016a4e6f206465706f7369747360a81b815250925050506104c9565b600081858151811061078b5761078b613976565b602002602001015190506000816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107d5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107f9919061398c565b61080490600a613aa9565b84878151811061081657610816613976565b60200260200101516108289190613ace565b9050610833816120cc565b826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa158015610871573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526108999190810190613ae2565b6040516020016108aa929190613b58565b60405160208183030381529060405294505050505092915050565b6108cd6121d4565b61095b6108e26033546001600160a01b031690565b6040516370a0823160e01b81523060048201526001600160a01b038416906370a0823190602401602060405180830381865afa158015610926573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061094a9190613bab565b6001600160a01b038416919061222e565b50565b60008061096961206c565b6001015461097561206c565b540303919050565b600061098882612280565b9050836001600160a01b0316816001600160a01b0316146109bb5760405162a1148160e81b815260040160405180910390fd5b6000806109c78461230c565b915091506109ec81876109d73390565b6001600160a01b039081169116811491141790565b610a17576109fa8633611fb9565b610a1757604051632ce44b5f60e11b815260040160405180910390fd5b6001600160a01b038516610a3e57604051633a954ecd60e21b815260040160405180910390fd5b8015610a4957600082555b610a5161206c565b6001600160a01b0387166000908152600591909101602052604090208054600019019055610a7d61206c565b6001600160a01b03861660008181526005929092016020526040909120805460010190554260a01b17600160e11b17610ab461206c565b60008681526004919091016020526040812091909155600160e11b84169003610b2a5760018401610ae361206c565b600082815260049190910160205260408120549003610b2857610b0461206c565b548114610b285783610b1461206c565b600083815260049190910160205260409020555b505b83856001600160a01b0316876001600160a01b0316600080516020614a9983398151915260405160405180910390a45b505050505050565b6065546000906001600160a01b03163314610bb75760405162461bcd60e51b815260206004820152601060248201526f10d05313115497d393d517d59055531560821b60448201526064015b60405180910390fd5b6001600160a01b038616610bfc5760405162461bcd60e51b815260206004820152600c60248201526b26a4a9a9a4a723afaaa9a2a960a11b6044820152606401610bae565b81610c3a5760405162461bcd60e51b815260206004820152600e60248201526d4d495353494e475f544f4b454e5360901b6044820152606401610bae565b818414610c795760405162461bcd60e51b815260206004820152600d60248201526c0829a9eaa9ca8be988a9c8ea89609b1b6044820152606401610bae565b6000610c83612334565b905060405180604001604052808787808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152505050908252506040805160208781028281018201909352878252928301929091889188918291850190849080828437600092018290525093909452505083815260666020908152604090912083518051919350610d219284929101906132f0565b506020828101518051610d3a926001850192019061333b565b50905050610d49876001612344565b9695505050505050565b6000818152606660209081526040918290208054835181840281018401909452808452606093849360018401928491830182828015610db157602002820191906000526020600020905b815481526020019060010190808311610d9d575b5050505050915080805480602002602001604051908101604052809291908181526020018280548015610e0d57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610def575b5050505050905091509150915091565b610e388383836040518060200160405280600081525061134e565b505050565b6065546001600160a01b03163314610e8a5760405162461bcd60e51b815260206004820152601060248201526f10d05313115497d393d517d59055531560821b6044820152606401610bae565b600081815260666020526040812090610ea38282613390565b610eb1600183016000613390565b505061095b81600061245b565b6060816000816001600160401b03811115610edb57610edb6137e5565b604051908082528060200260200182016040528015610f2d57816020015b604080516080810182526000808252602080830182905292820181905260608201528252600019909201910181610ef95790505b50905060005b828114610f8057610f5b868683818110610f4f57610f4f613976565b90506020020135611bc5565b828281518110610f6d57610f6d613976565b6020908102919091010152600101610f33565b50949350505050565b60006104c982612280565b60006001600160a01b038216610fbd576040516323d3ad8160e21b815260040160405180910390fd5b6001600160401b03610fcd61206c565b6005016000846001600160a01b03166001600160a01b0316815260200190815260200160002054169050919050565b6110046121d4565b61100e60006125ca565b565b6060600080600061102085610f94565b90506000816001600160401b0381111561103c5761103c6137e5565b604051908082528060200260200182016040528015611065578160200160208202803683370190505b50905061109260408051608081018252600080825260208201819052918101829052606081019190915290565b60005b83861461110c576110a58161261c565b915081604001516111045781516001600160a01b0316156110c557815194505b876001600160a01b0316856001600160a01b03160361110457808387806001019850815181106110f7576110f7613976565b6020026020010181815250505b600101611095565b50909695505050505050565b606061112261206c565b60030180546104e79061393c565b606081831061115257604051631960ccad60e11b815260040160405180910390fd5b60008061115d612334565b90508084111561116b578093505b600061117687610f94565b905084861015611195578585038181101561118f578091505b50611199565b5060005b6000816001600160401b038111156111b3576111b36137e5565b6040519080825280602002602001820160405280156111dc578160200160208202803683370190505b509050816000036111f25793506112a192505050565b60006111fd88611bc5565b90506000816040015161120e575080515b885b8881141580156112205750848714155b156112955761122e8161261c565b9250826040015161128d5782516001600160a01b03161561124e57825191505b8a6001600160a01b0316826001600160a01b03160361128d578084888060010199508151811061128057611280613976565b6020026020010181815250505b600101611210565b50505092835250909150505b9392505050565b336001600160a01b038316036112d15760405163b06307db60e01b815260040160405180910390fd5b806112da61206c565b336000818152600792909201602090815260408084206001600160a01b03881680865290835293819020805460ff19169515159590951790945592518415158152919290917f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a35050565b61135984848461097d565b6001600160a01b0383163b156113925761137584848484612663565b611392576040516368d2bf6b60e11b815260040160405180910390fd5b50505050565b6113a06121d4565b6033546040516001600160a01b03909116904780156108fc02916000818181858888f1935050505015801561095b573d6000803e3d6000fd5b6000818152606660205260408120600101546060916113f9826002613bc4565b61140490600c613be3565b9050600080826001600160401b03811115611421576114216137e5565b60405190808252806020026020018201604052801561145457816020015b606081526020019060019003908161143f5790505b50905060405180606001604052806026815260200161475b60269139818361147b81613bf6565b94508151811061148d5761148d613976565b602002602001018190525060405180610100016040528060d5815260200161541a60d5913981836114bd81613bf6565b9450815181106114cf576114cf613976565b60200260200101819052506040518061030001604052806102d881526020016147816102d89139818361150181613bf6565b94508151811061151357611513613976565b6020026020010181905250604051806109a001604052806109618152602001614ab96109619139818361154581613bf6565b94508151811061155757611557613976565b60209081029190910101526102fb60005b858110156115e85761158d61157e826084613bc4565b6115889084613c0f565b6120cc565b60405160200161159d9190613c22565b6040516020818303038152906040528385806115b890613bf6565b9650815181106115ca576115ca613976565b602002602001018190525080806115e090613bf6565b915050611568565b506040518060a001604052806065815260200161469060659139828461160d81613bf6565b95508151811061161f5761161f613976565b60200260200101819052506040518060a00160405280606681526020016146f560669139828461164e81613bf6565b95508151811061166057611660613976565b60200260200101819052506040518060a001604052806066815260200161462a60669139828461168f81613bf6565b9550815181106116a1576116a1613976565b60200260200101819052506116b461274e565b6040516020016116c49190613cbf565b6040516020818303038152906040528284806116df90613bf6565b9550815181106116f1576116f1613976565b602002602001018190525061033b905060005b858110156117805761171a61157e826081613bc4565b6117248983610665565b604051602001611735929190613d50565b60405160208183030381529060405283858061175090613bf6565b96508151811061176257611762613976565b6020026020010181905250808061177890613bf6565b915050611704565b506117896127c5565b6040516020016117999190613df8565b6040516020818303038152906040528284806117b490613bf6565b9550815181106117c6576117c6613976565b60200260200101819052506117d96129d1565b6040516020016117e99190613e6b565b60405160208183030381529060405282848061180490613bf6565b95508151811061181657611816613976565b6020026020010181905250611829612aab565b6040516020016118399190613efd565b60405160208183030381529060405282848061185490613bf6565b95508151811061186657611866613976565b6020026020010181905250604051806040016040528060068152602001651e17b9bb339f60d11b8152508284815181106118a2576118a2613976565b60200260200101819052506000826000815181106118c2576118c2613976565b6020026020010151836001815181106118dd576118dd613976565b6020026020010151846002815181106118f8576118f8613976565b60200260200101518560038151811061191357611913613976565b602002602001015160405160200161192e9493929190613f71565b604051602081830303815290604052905060005b868110156119a4578184611957836004613be3565b8151811061196757611967613976565b6020026020010151604051602001611980929190613fc8565b6040516020818303038152906040529150808061199c90613bf6565b915050611942565b5080836119b2886004613be3565b815181106119c2576119c2613976565b6020026020010151848860056119d89190613be3565b815181106119e8576119e8613976565b6020026020010151858960066119fe9190613be3565b81518110611a0e57611a0e613976565b6020026020010151868a6007611a249190613be3565b81518110611a3457611a34613976565b6020026020010151604051602001611a50959493929190613ff7565b604051602081830303815290604052905060005b86811015611ad157818482611a7a8a6008613be3565b611a849190613be3565b81518110611a9457611a94613976565b6020026020010151604051602001611aad929190613fc8565b60405160208183030381529060405291508080611ac990613bf6565b915050611a64565b508083611adf886002613bc4565b611aea906008613be3565b81518110611afa57611afa613976565b602002602001015184886002611b109190613bc4565b611b1b906009613be3565b81518110611b2b57611b2b613976565b602002602001015185896002611b419190613bc4565b611b4c90600a613be3565b81518110611b5c57611b5c613976565b6020026020010151868a6002611b729190613bc4565b611b7d90600b613be3565b81518110611b8d57611b8d613976565b6020026020010151604051602001611ba9959493929190613ff7565b60408051601f1981840301815291905298975050505050505050565b6040805160808082018352600080835260208084018290528385018290526060808501839052855193840186528284529083018290529382018190529281019290925290611c11612334565b8310611c1d5792915050565b611c268361261c565b9050806040015115611c385792915050565b6112a183612b83565b6000805160206154ef83398151915254610100900460ff16611c76576000805160206154ef8339815191525460ff1615611c7a565b303b155b611cec5760405162461bcd60e51b815260206004820152603760248201527f455243373231415f5f496e697469616c697a61626c653a20636f6e747261637460448201527f20697320616c726561647920696e697469616c697a65640000000000000000006064820152608401610bae565b6000805160206154ef83398151915254610100900460ff16158015611d28576000805160206154ef833981519152805461ffff19166101011790555b600054610100900460ff1615808015611d485750600054600160ff909116105b80611d625750303b158015611d62575060005460ff166001145b611dc55760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610bae565b6000805460ff191660011790558015611de8576000805461ff0019166101001790555b611e466040518060400160405280601181526020017042616c616e63655661756c74536861726560781b8152506040518060400160405280601381526020017242414c414e43452d5641554c542d534841524560681b815250612bb8565b611e4e612bf6565b6001600160a01b038316611e945760405162461bcd60e51b815260206004820152600d60248201526c135254d4d25391d7d590555315609a1b6044820152606401610bae565b606580546001600160a01b0319166001600160a01b0385161790558015611ef5576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b508015611f15576000805160206154ef833981519152805461ff00191690555b5050565b60606000611f2683611f5e565b90506000611f3382612c25565b905080604051602001611f469190614062565b60405160208183030381529060405292505050919050565b60606000611f6b836113d9565b9050611f7561274e565b611f7e846120cc565b611f86612d77565b611f8f84612c25565b604051602001611fa294939291906140a7565b604051602081830303815290604052915050919050565b6000611fc361206c565b6001600160a01b039384166000908152600791909101602090815260408083209490951682529290925250205460ff1690565b611ffe6121d4565b6001600160a01b0381166120635760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610bae565b61095b816125ca565b7f2569078dfb4b0305704d3008e7403993ae9601b85f7ae5e742de3de8f8011c4090565b600061209a61206c565b54821080156104c95750600160e01b6120b161206c565b60008481526004919091016020526040902054161592915050565b6060816000036120f35750506040805180820190915260018152600360fc1b602082015290565b8160005b811561211d578061210781613bf6565b91506121169050600a83613ace565b91506120f7565b6000816001600160401b03811115612137576121376137e5565b6040519080825280601f01601f191660200182016040528015612161576020820181803683370190505b5090505b84156121cc57612176600183613c0f565b9150612183600a866141ae565b61218e906030613be3565b60f81b8183815181106121a3576121a3613976565b60200101906001600160f81b031916908160001a9053506121c5600a86613ace565b9450612165565b949350505050565b6033546001600160a01b0316331461100e5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610bae565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610e38908490612dc1565b60008161228b61206c565b548110156122f357600061229d61206c565b600083815260049190910160205260408120549150600160e01b821690036122f1575b806000036112a1576122d061206c565b600019909201600081815260049390930160205260409092205490506122c0565b505b604051636f96cda160e11b815260040160405180910390fd5b600080600061231961206c565b60009485526006016020525050604090912080549092909150565b600061233e61206c565b54919050565b600061234e61206c565b54905060008290036123735760405163b562e8dd60e01b815260040160405180910390fd5b68010000000000000001820261238761206c565b6001600160a01b038516600081815260059290920160205260409091208054929092019091554260a01b6001841460e11b17176123c261206c565b600083815260049190910160205260408120919091556001600160a01b038416908383019083908390600080516020614a998339815191528180a4600183015b8181146124285780836000600080516020614a99833981519152600080a4600101612402565b508160000361244957604051622e076360e81b815260040160405180910390fd5b8061245261206c565b5550610e389050565b600061246683612280565b9050806000806124758661230c565b9150915084156124b55761248a8184336109d7565b6124b5576124988333611fb9565b6124b557604051632ce44b5f60e11b815260040160405180910390fd5b80156124c057600082555b6fffffffffffffffffffffffffffffffff6124d961206c565b6001600160a01b038516600081815260059290920160205260409091208054929092019091554260a01b17600360e01b1761251261206c565b60008881526004919091016020526040812091909155600160e11b85169003612588576001860161254161206c565b6000828152600491909101602052604081205490036125865761256261206c565b548114612586578461257261206c565b600083815260049190910160205260409020555b505b60405186906000906001600160a01b03861690600080516020614a99833981519152908390a46125b661206c565b600190810180549091019055505050505050565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6040805160808101825260008082526020820181905291810182905260608101919091526104c961264b61206c565b60008481526004919091016020526040902054612e93565b604051630a85bd0160e11b81526000906001600160a01b0385169063150b7a02906126989033908990889088906004016141c2565b6020604051808303816000875af19250505080156126d3575060408051601f3d908101601f191682019092526126d0918101906141f5565b60015b612731573d808015612701576040519150601f19603f3d011682016040523d82523d6000602084013e612706565b606091505b508051600003612729576040516368d2bf6b60e11b815260040160405180910390fd5b805181602001fd5b6001600160e01b031916630a85bd0160e11b149050949350505050565b6065546040805163032d611960e51b815290516060926001600160a01b0316916365ac23209160048083019260009291908290030181865afa158015612798573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526127c09190810190613ae2565b905090565b60606000606560009054906101000a90046001600160a01b03166001600160a01b0316631addeaf56040518163ffffffff1660e01b8152600401602060405180830381865afa15801561281c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128409190613bab565b90508060000361287257505060408051808201909152600c81526b139bc81c995c185e5b595b9d60a21b602082015290565b600061288061158883612eda565b9050600061288d83612efa565b9050600061289a826120cc565b9050600a8210156128c857806040516020016128b69190614212565b60405160208183030381529060405290505b60006128d385612f14565b905060006128e0826120cc565b9050600a82101561290e57806040516020016128fc9190614212565b60405160208183030381529060405290505b600061291987612f26565b90506000612926826120cc565b9050600a82101561295457806040516020016129429190614212565b60405160208183030381529060405290505b600061295f89612f44565b9050600061296c826120cc565b9050600a82101561299a57806040516020016129889190614212565b60405160208183030381529060405290505b88878685846040516020016129b395949392919061423b565b6040516020818303038152906040529a505050505050505050505090565b60606000606560009054906101000a90046001600160a01b03166001600160a01b03166357ded9c96040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a4c9190613bab565b905080600003612a7857505060408051808201909152600681526527379020a82960d11b602082015290565b612a86611588606483613ace565b604051602001612a9691906142f2565b60405160208183030381529060405291505090565b6065546040516379fa8d5760e01b8152633b9aca00600482018190526060926000926001600160a01b03909116906379fa8d5790602401602060405180830381865afa158015612aff573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b239190613bab565b612b2f90612710613bc4565b612b399190613ace565b905080600003612b655750506040805180820190915260068152654e6f20524f4960d01b602082015290565b612b73611588606483613ace565b604051602001612a96919061432a565b6040805160808101825260008082526020820181905291810182905260608101919091526104c9612bb383612280565b612e93565b6000805160206154ef83398151915254610100900460ff16612bec5760405162461bcd60e51b8152600401610bae9061434a565b611f158282612f60565b600054610100900460ff16612c1d5760405162461bcd60e51b8152600401610bae9061439e565b61100e612fd3565b60608151600003612c4457505060408051602081019091526000815290565b6000604051806060016040528060408152602001614a596040913990506000600384516002612c739190613be3565b612c7d9190613ace565b612c88906004613bc4565b6001600160401b03811115612c9f57612c9f6137e5565b6040519080825280601f01601f191660200182016040528015612cc9576020820181803683370190505b509050600182016020820185865187015b80821015612d35576003820191508151603f8160121c168501518453600184019350603f81600c1c168501518453600184019350603f8160061c168501518453600184019350603f8116850151845350600183019250612cda565b5050600386510660018114612d515760028114612d6457612d6c565b603d6001830353603d6002830353612d6c565b603d60018303535b509195945050505050565b60655460408051630cdbe4cb60e41b815290516060926001600160a01b03169163cdbe4cb09160048083019260009291908290030181865afa158015612798573d6000803e3d6000fd5b6000612e16826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166130039092919063ffffffff16565b805190915015610e385780806020019051810190612e3491906143e9565b610e385760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610bae565b604080516080810182526001600160a01b038316815260a083901c6001600160401b03166020820152600160e01b831615159181019190915260e89190911c606082015290565b6000612ef1612eec6201518084613ace565b613012565b50909392505050565b6000612f0c612eec6201518084613ace565b509392505050565b60006121cc612eec6201518084613ace565b600080612f3662015180846141ae565b90506112a1610e1082613ace565b600080612f53610e10846141ae565b90506112a1603c82613ace565b6000805160206154ef83398151915254610100900460ff16612f945760405162461bcd60e51b8152600401610bae9061434a565b81612f9d61206c565b60020190612fab908261444c565b5080612fb561206c565b60030190612fc3908261444c565b506000612fce61206c565b555050565b600054610100900460ff16612ffa5760405162461bcd60e51b8152600401610bae9061439e565b61100e336125ca565b60606121cc8484600085613186565b60008080838162253d8c6130298362010bd961450b565b613033919061450b565b9050600062023ab1613046836004614533565b61305091906145b8565b905060046130618262023ab1614533565b61306c90600361450b565b61307691906145b8565b61308090836145e6565b9150600062164b0961309384600161450b565b61309f90610fa0614533565b6130a991906145b8565b905060046130b9826105b5614533565b6130c391906145b8565b6130cd90846145e6565b6130d890601f61450b565b9250600061098f6130ea856050614533565b6130f491906145b8565b9050600060506131068361098f614533565b61311091906145b8565b61311a90866145e6565b9050613127600b836145b8565b945061313485600c614533565b61313f83600261450b565b61314991906145e6565b915084836131586031876145e6565b613163906064614533565b61316d919061450b565b613177919061450b565b9a919950975095505050505050565b6060824710156131e75760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610bae565b6001600160a01b0385163b61323e5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610bae565b600080866001600160a01b0316858760405161325a919061460d565b60006040518083038185875af1925050503d8060008114613297576040519150601f19603f3d011682016040523d82523d6000602084013e61329c565b606091505b50915091506132ac8282866132b7565b979650505050505050565b606083156132c65750816112a1565b8251156132d65782518084602001fd5b8160405162461bcd60e51b8152600401610bae9190613442565b82805482825590600052602060002090810192821561332b579160200282015b8281111561332b578251825591602001919060010190613310565b506133379291506133aa565b5090565b82805482825590600052602060002090810192821561332b579160200282015b8281111561332b57825182546001600160a01b0319166001600160a01b0390911617825560209092019160019091019061335b565b508054600082559060005260206000209081019061095b91905b5b8082111561333757600081556001016133ab565b6001600160e01b03198116811461095b57600080fd5b6000602082840312156133e757600080fd5b81356112a1816133bf565b60005b8381101561340d5781810151838201526020016133f5565b50506000910152565b6000815180845261342e8160208601602086016133f2565b601f01601f19169290920160200192915050565b6020815260006112a16020830184613416565b60006020828403121561346757600080fd5b5035919050565b6001600160a01b038116811461095b57600080fd5b6000806040838503121561349657600080fd5b82356134a18161346e565b946020939093013593505050565b600080604083850312156134c257600080fd5b50508035926020909101359150565b6000602082840312156134e357600080fd5b81356112a18161346e565b60008060006060848603121561350357600080fd5b833561350e8161346e565b9250602084013561351e8161346e565b929592945050506040919091013590565b60008083601f84011261354157600080fd5b5081356001600160401b0381111561355857600080fd5b6020830191508360208260051b850101111561357357600080fd5b9250929050565b60008060008060006060868803121561359257600080fd5b853561359d8161346e565b945060208601356001600160401b03808211156135b957600080fd5b6135c589838a0161352f565b909650945060408801359150808211156135de57600080fd5b506135eb8882890161352f565b969995985093965092949392505050565b600081518084526020808501945080840160005b8381101561362c57815187529582019590820190600101613610565b509495945050505050565b60408152600061364a60408301856135fc565b82810360208481019190915284518083528582019282019060005b8181101561368a5784516001600160a01b031683529383019391830191600101613665565b5090979650505050505050565b600080602083850312156136aa57600080fd5b82356001600160401b038111156136c057600080fd5b6136cc8582860161352f565b90969095509350505050565b80516001600160a01b031682526020808201516001600160401b03169083015260408082015115159083015260609081015162ffffff16910152565b6020808252825182820181905260009190848201906040850190845b8181101561110c576137438385516136d8565b9284019260809290920191600101613730565b6020815260006112a160208301846135fc565b60008060006060848603121561377e57600080fd5b83356137898161346e565b95602085013595506040909401359392505050565b801515811461095b57600080fd5b600080604083850312156137bf57600080fd5b82356137ca8161346e565b915060208301356137da8161379e565b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715613823576138236137e5565b604052919050565b60006001600160401b03821115613844576138446137e5565b50601f01601f191660200190565b6000806000806080858703121561386857600080fd5b84356138738161346e565b935060208501356138838161346e565b92506040850135915060608501356001600160401b038111156138a557600080fd5b8501601f810187136138b657600080fd5b80356138c96138c48261382b565b6137fb565b8181528860208385010111156138de57600080fd5b8160208401602083013760006020838301015280935050505092959194509250565b608081016104c982846136d8565b6000806040838503121561392157600080fd5b823561392c8161346e565b915060208301356137da8161346e565b600181811c9082168061395057607f821691505b60208210810361397057634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561399e57600080fd5b815160ff811681146112a157600080fd5b634e487b7160e01b600052601160045260246000fd5b600181815b80851115613a005781600019048211156139e6576139e66139af565b808516156139f357918102915b93841c93908002906139ca565b509250929050565b600082613a17575060016104c9565b81613a24575060006104c9565b8160018114613a3a5760028114613a4457613a60565b60019150506104c9565b60ff841115613a5557613a556139af565b50506001821b6104c9565b5060208310610133831016604e8410600b8410161715613a83575081810a6104c9565b613a8d83836139c5565b8060001904821115613aa157613aa16139af565b029392505050565b60006112a160ff841683613a08565b634e487b7160e01b600052601260045260246000fd5b600082613add57613add613ab8565b500490565b600060208284031215613af457600080fd5b81516001600160401b03811115613b0a57600080fd5b8201601f81018413613b1b57600080fd5b8051613b296138c48261382b565b818152856020838501011115613b3e57600080fd5b613b4f8260208301602086016133f2565b95945050505050565b6a02232b837b9b4ba32b21d160ad1b815260008351613b7e81600b8501602088016133f2565b600160fd1b600b918401918201528351613b9f81600c8401602088016133f2565b01600c01949350505050565b600060208284031215613bbd57600080fd5b5051919050565b6000816000190483118215151615613bde57613bde6139af565b500290565b808201808211156104c9576104c96139af565b600060018201613c0857613c086139af565b5060010190565b818103818111156104c9576104c96139af565b7f3c726563742077696474683d2235383522206865696768743d2231303422207281527f783d22323322207472616e73666f726d3d227472616e736c6174652831303020602082015260008251613c808160408501602087016133f2565b7f29222066696c6c3d2272676261283235352c3235352c3235352c302e31312922604093909101928301525061179f60f11b6060820152606201919050565b7f3c74657874207472616e73666f726d3d227472616e736c61746528313030203381527f3636292220636c6173733d226822207374796c653d22666f6e742d66616d696c60208201526b3c9d13a0b934b0b6139d911f60a11b604082015260008251613d3281604c8501602087016133f2565b661e17ba32bc3a1f60c91b604c939091019283015250605301919050565b7f3c74657874207472616e73666f726d3d227472616e736c617465283133342000815260008351613d8881601f8501602088016133f2565b7f292220636c6173733d226222207374796c653d22666f6e742d66616d696c793a601f918401918201526913a0b934b0b6139d911f60b11b603f8201528351613dd88160498401602088016133f2565b661e17ba32bc3a1f60c91b60499290910191820152605001949350505050565b7f3c74657874207472616e73666f726d3d227472616e736c61746528313334203981527f3536292220636c6173733d226222207374796c653d22666f6e742d66616d696c60208201526b3c9d13a0b934b0b6139d911f60a11b604082015260008251613d3281604c8501602087016133f2565b7f3c74657874207472616e73666f726d3d227472616e736c61746528313334203181527f303835292220636c6173733d226222207374796c653d22666f6e742d66616d6960208201526c363c9d13a0b934b0b6139d911f60991b604082015260008251613edf81604d8501602087016133f2565b661e17ba32bc3a1f60c91b604d939091019283015250605401919050565b7f3c74657874207472616e73666f726d3d227472616e736c61746528313334203181527f323139292220636c6173733d226222207374796c653d22666f6e742d66616d6960208201526c363c9d13a0b934b0b6139d911f60991b604082015260008251613edf81604d8501602087016133f2565b60008551613f83818460208a016133f2565b855190830190613f97818360208a016133f2565b8551910190613faa8183602089016133f2565b8451910190613fbd8183602088016133f2565b019695505050505050565b60008351613fda8184602088016133f2565b835190830190613fee8183602088016133f2565b01949350505050565b60008651614009818460208b016133f2565b86519083019061401d818360208b016133f2565b8651910190614030818360208a016133f2565b85519101906140438183602089016133f2565b84519101906140568183602088016133f2565b01979650505050505050565b7f646174613a6170706c69636174696f6e2f6a736f6e3b6261736536342c00000081526000825161409a81601d8501602087016133f2565b91909101601d0192915050565b6803d913730b6b2911d160bd1b8152601160f91b600982015284516000906140d681600a850160208a016133f2565b72010142130b630b731b2902b30bab63a1490169606d1b600a91840191820152855161410981601d840160208a016133f2565b72111610113232b9b1b934b83a34b7b7111d101160691b601d9290910191820152845161413d8160308401602089016133f2565b7f222c2022696d616765223a2022646174613a696d6167652f7376672b786d6c3b603092909101918201526618985cd94d8d0b60ca1b6050820152835161418b8160578401602088016133f2565b6141a260578284010161227d60f01b815260020190565b98975050505050505050565b6000826141bd576141bd613ab8565b500690565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090610d4990830184613416565b60006020828403121561420757600080fd5b81516112a1816133bf565b600360fc1b81526000825161422e8160018501602087016133f2565b9190910160010192915050565b6a02932b830bcb6b2b73a1d160ad1b81526000865161426181600b850160208b016133f2565b8083019050602f60f81b80600b830152875161428481600c850160208c016133f2565b600c920191820152855161429f81600d840160208a016133f2565b600160fd1b600d929091019182015284516142c181600e8401602089016133f2565b601d60f91b600e929091019182015283516142e381600f8401602088016133f2565b01600f01979650505050505050565b64020a8291d160dd1b8152600082516143128160058501602087016133f2565b602560f81b6005939091019283015250600601919050565b6402927a49d160dd1b8152600082516143128160058501602087016133f2565b60208082526034908201527f455243373231415f5f496e697469616c697a61626c653a20636f6e7472616374604082015273206973206e6f7420696e697469616c697a696e6760601b606082015260800190565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b6000602082840312156143fb57600080fd5b81516112a18161379e565b601f821115610e3857600081815260208120601f850160051c8101602086101561442d5750805b601f850160051c820191505b81811015610b5a57828155600101614439565b81516001600160401b03811115614465576144656137e5565b61447981614473845461393c565b84614406565b602080601f8311600181146144ae57600084156144965750858301515b600019600386901b1c1916600185901b178555610b5a565b600085815260208120601f198616915b828110156144dd578886015182559484019460019091019084016144be565b50858210156144fb5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b808201828112600083128015821682158216171561452b5761452b6139af565b505092915050565b60006001600160ff1b0381841382841380821686840486111615614559576145596139af565b600160ff1b6000871282811687830589121615614578576145786139af565b60008712925087820587128484161615614594576145946139af565b878505871281841616156145aa576145aa6139af565b505050929093029392505050565b6000826145c7576145c7613ab8565b600160ff1b8214600019841416156145e1576145e16139af565b500590565b8181036000831280158383131683831282161715614606576146066139af565b5092915050565b6000825161461f8184602087016133f2565b919091019291505056fe3c726563742077696474683d2232343022206865696768743d22313034222072783d22323322207472616e73666f726d3d227472616e736c61746528313030203131353529222066696c6c3d2272676261283235352c3235352c3235352c302e313129222f3e3c726563742077696474683d2235383522206865696768743d22313034222072783d22323322207472616e73666f726d3d227472616e736c617465283130302038393529222066696c6c3d2272676261283235352c3235352c3235352c302e313129222f3e3c726563742077696474683d2232313122206865696768743d22313034222072783d22323322207472616e73666f726d3d227472616e736c61746528313030203130323529222066696c6c3d2272676261283235352c3235352c3235352c302e313129222f3e3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e3c646566733e3c636c6970506174682069643d22636c69702d70617468223e3c726563742069643d2252656374616e676c655f393934222077696474683d223130383022206865696768743d2231333539222072783d22333422207374726f6b653d222337303730373022207374726f6b652d77696474683d2231222f3e3c2f636c6970506174683e3c72616469616c4772616469656e742069643d2272616469616c2d6772616469656e74222063783d22302e35222063793d22302e352220723d22302e3522206772616469656e74556e6974733d226f626a656374426f756e64696e67426f78223e3c73746f70206f66667365743d2230222073746f702d636f6c6f723d2223333538303737222f3e3c73746f70206f66667365743d2231222073746f702d6f7061636974793d2230222f3e3c2f72616469616c4772616469656e743e3c72616469616c4772616469656e742069643d2272616469616c2d6772616469656e742d32222063783d22302e35222063793d22302e352220723d22302e3522206772616469656e74556e6974733d226f626a656374426f756e64696e67426f78223e3c73746f70206f66667365743d2230222073746f702d636f6c6f723d2223333933343933222f3e3c73746f70206f66667365743d2231222073746f702d636f6c6f723d2223316431613461222073746f702d6f7061636974793d2230222f3e3c2f72616469616c4772616469656e743e3c6c696e6561724772616469656e742069643d226c696e6561722d6772616469656e74222079313d22302e35222078323d2231222079323d22302e3522206772616469656e74556e6974733d226f626a656374426f756e64696e67426f78223e3c73746f70206f66667365743d2230222073746f702d636f6c6f723d2223666666222f3e3c73746f70206f66667365743d2231222073746f702d636f6c6f723d2267726179222f3e3c2f6c696e6561724772616469656e743e3c2f646566733e4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef3c672069643d2252656374616e676c655f39393322207374726f6b653d222337303730373022207374726f6b652d77696474683d2231223e3c726563742077696474683d223130383022206865696768743d2231333539222072783d22333422207374726f6b653d226e6f6e65222f3e3c7265637420783d22302e352220793d22302e35222077696474683d223130373922206865696768743d2231333538222072783d2233332e35222066696c6c3d226e6f6e65222f3e3c2f673e3c672069643d224d61736b5f47726f75705f312220636c69702d706174683d2275726c2823636c69702d7061746829223e3c672069643d2247726f75705f313236363022207472616e73666f726d3d227472616e736c617465282d31303235202d313533332e39303829223e3c656c6c697073652069643d22456c6c697073655f393735222063783d2231303432222063793d22313331312e35222072783d2231303432222072793d22313331312e3522207472616e73666f726d3d227472616e736c617465283020313936332e39303829222066696c6c3d2275726c282372616469616c2d6772616469656e7429222f3e3c656c6c697073652069643d22456c6c697073655f393736222063783d22393836222063793d2231323431222072783d22393836222072793d223132343122207472616e73666f726d3d227472616e736c6174652831303235202d302e30393229222066696c6c3d2275726c282372616469616c2d6772616469656e742d3229222f3e3c2f673e3c2f673e3c672069643d2252656374616e676c655f39393222207472616e73666f726d3d227472616e736c61746528353320353329222066696c6c3d226e6f6e6522207374726f6b653d2272676261283235352c3235352c3235352c302e31372922207374726f6b652d77696474683d2231223e3c726563742077696474683d2239373522206865696768743d2231323534222072783d22323322207374726f6b653d226e6f6e65222f3e3c7265637420783d22302e352220793d22302e35222077696474683d2239373422206865696768743d2231323533222072783d2232322e35222066696c6c3d226e6f6e65222f3e3c2f673e3c672069643d2247726f75705f313235353622207472616e73666f726d3d227472616e736c617465282d3334372e333931202d3236372e35323429223e3c672069643d2247726f75705f313235333922207472616e73666f726d3d227472616e736c617465283434372e333931203339352e38383329223e3c672069643d2247726f75705f313235343422207472616e73666f726d3d227472616e736c6174652830203029223e3c706174682069643d22506174685f333338312220643d224d3438342e3838322d313134332e3436316135312e3137322c35312e3137322c302c302c312d33392e3334392d33392e3334392c382e3732332c382e3732332c302c302c312c382e3530392d31302e353634683061382e3635352c382e3635352c302c302c312c382e352c362e3833352c33332e372c33332e372c302c302c302c32362e3036372c32362e3036382c382e3635352c382e3635352c302c302c312c362e3833352c382e35683041382e3732342c382e3732342c302c302c312c3438342e3838322d313134332e3436315a22207472616e73666f726d3d227472616e736c617465282d3431322e32363820313139332e39383729222066696c6c3d2275726c28236c696e6561722d6772616469656e7429222f3e3c706174682069643d22506174685f333338322220643d224d3337392e3932382d313131382e3634386135312e3137322c35312e3137322c302c302c312c33392e3334392c33392e3334392c382e3732332c382e3732332c302c302c312d382e3530392c31302e353634683061382e3635352c382e3635352c302c302c312d382e352d362e3833352c33332e372c33332e372c302c302c302d32362e3036372d32362e3036372c382e3635352c382e3635352c302c302c312d362e3833352d382e35683041382e3732332c382e3732332c302c302c312c3337392e3932382d313131382e3634385a22207472616e73666f726d3d227472616e736c617465282d3336392e33363420313135312e38393729222066696c6c3d2275726c28236c696e6561722d6772616469656e7429222f3e3c706174682069643d22506174685f333338332220643d224d3337392e3932382d313134342e3836396135312e3137312c35312e3137312c302c302c302c33392e3334392d33392e3334392c382e3732332c382e3732332c302c302c302d382e3530392d31302e353633683061382e3635352c382e3635352c302c302c302d382e352c362e3833352c33332e372c33332e372c302c302c312d32362e3036372c32362e3036372c382e3635342c382e3635342c302c302c302d362e3833352c382e35683041382e3732332c382e3732332c302c302c302c3337392e3932382d313134342e3836395a22207472616e73666f726d3d227472616e736c617465282d3336392e33363420313139342e37383129222066696c6c3d2223666666222f3e3c706174682069643d22506174685f333338342220643d224d3438342e3838322d313131382e3634386135312e3137322c35312e3137322c302c302c302d33392e3334392c33392e3334392c382e3732332c382e3732332c302c302c302c382e3530392c31302e353634683061382e3635352c382e3635352c302c302c302c382e352d362e3833352c33332e372c33332e372c302c302c312c32362e3036372d32362e3036372c382e3635362c382e3635362c302c302c302c362e3833352d382e35683041382e3732332c382e3732332c302c302c302c3438342e3838322d313131382e3634385a22207472616e73666f726d3d227472616e736c617465282d3431322e32363820313135312e38393729222066696c6c3d2223666666222f3e3c2f673e3c2f673e3c746578742069643d2262616c616e636522207472616e73666f726d3d227472616e736c617465283634352e393538203435302e31323129222066696c6c3d222366666622207374726f6b653d227267626128302c302c302c302922207374726f6b652d77696474683d22312220666f6e742d73697a653d22343122207374796c653d22666f6e742d66616d696c793a27417269616c273b22206c65747465722d73706163696e673d22302e3035656d223e3c747370616e20783d222d38372e3830312220793d2230223e62616c616e63653c2f747370616e3e3c2f746578743e3c2f673e3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667222077696474683d223130383022206865696768743d2231333539222076696577426f783d2230203020313038302031333539223e3c7374796c653e2e622c2e687b66696c6c3a236666663b666f6e742d66616d696c793a22417269616c227d2e687b666f6e742d73697a653a383370787d2e627b666f6e742d73697a653a333470783b6261636b67726f756e642d636f6c6f723a233030303b70616464696e673a323070787d3c2f7374796c653eee151c8401928dc223602bb187aff91b9a56c7cae5476ef1b3287b085a16c85fa26469706673582212209a04e3a0f9f28a9ef8e89ffe7b37ed938c44c3616df3409d3ec06ca201aa28ea64736f6c63430008100033
Age | Block | Fee Address | BC Fee Address | Voting Power | Jailed | Incoming |
---|
Validator ID :
0 FTM
Amount Staked
0
Amount Delegated
0
Staking Total
0
Staking Start Epoch
0
Staking Start Time
0
Proof of Importance
0
Origination Score
0
Validation Score
0
Active
0
Online
0
Downtime
0 s
Address | Amount | claimed Rewards | Created On Epoch | Created On |
---|
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.