file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './interfaces/IUniswapV2Factory.sol'; import './UniswapV2Pair.sol'; import './libraries/Math.sol'; import './interfaces/IUniswapV2Pair.sol'; import "@openzeppelin/contracts/access/Ownable.sol"; import './interfaces/IReferences.sol'; import "@openzeppelin/contracts/math/SafeMath.sol"; import './libraries/TransferHelper.sol'; contract UniswapV2Factory is IUniswapV2Factory ,Ownable{ address public override feeTo; address public override repurchaseTo; // using SafeMath for uint256; address public override feeToSetter; address public override migrator; using SafeMathUniswap for uint; mapping(address => mapping(address => address)) public override getPair; mapping(address => IFeeCalcutor) public pairFeeCalculators; address[] public override allPairs; address public refers; uint256 public referRatio; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeToSetter,address _refers,uint256 _referRatio) public { feeToSetter = _feeToSetter; refers = _refers; referRatio = _referRatio; } function allPairsLength() external override view returns (uint) { return allPairs.length; } function pairCodeHash() external pure returns (bytes32) { return keccak256(type(UniswapV2Pair).creationCode); } function calcTotalFee(address pair,uint rootK,uint rootKLast,uint totalSupply) external override view returns (uint256 liquidity,address repurchase,uint256 repurchaseAmount) { repurchase = repurchaseTo ; IFeeCalcutor calc = pairFeeCalculators[pair]; if(address(calc)==address(0x0)){ uint numerator = totalSupply.mul(rootK.sub(rootKLast)); // uint denominator = rootK.mul(2).add(rootKLast); uint denominator = rootK.wdiv(3).wmul(2).add(rootKLast); liquidity = numerator / denominator; if (liquidity > 0) { if(repurchase!=address(0)){ repurchaseAmount = liquidity.wdiv(15).wmul(14); } } }else{ (liquidity,repurchaseAmount) = calc.calcTotalFee(pair,rootK,rootKLast,totalSupply); } } function setPairCalculator(address pair,address calc) public onlyOwner{ pairFeeCalculators[pair]=IFeeCalcutor(calc); } function setRefers(address _refers,uint256 _referRatio) public onlyOwner{ refers = _refers; referRatio = _referRatio; } function getReferAmount(address _user, uint256 amount) public override view returns (uint256 upperFeeReal,uint256 upperFeeTotal){ return IReferences(refers).getReferAmount(_user, amount.wdiv(10000).wmul(referRatio)); } function rewardUpper(address ref,address token,uint256 upperFeeReal,uint256 upperFeeTotal) public override { if(refers!=address(0x0)){ TransferHelper.safeTransfer(token,refers,upperFeeReal); IReferences(refers).rewardUpper(ref,token,upperFeeReal,upperFeeTotal,feeTo); } } function createPair(address tokenA, address tokenB) external override returns (address pair) { require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } UniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeTo = _feeTo; } function setRepurchaseTo(address _repurchaseTo) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); repurchaseTo = _repurchaseTo; } function setMigrator(address _migrator) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); migrator = _migrator; } function setFeeToSetter(address _feeToSetter) external override { require(_feeToSetter != address(0), "_feeToSetter address cannot be 0"); require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeToSetter = _feeToSetter; } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) public override view returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address tokenA, address tokenB) public override view returns (address pair) { return getPair[tokenA][tokenB]; } // fetches and sorts the reserves for a pair function getReserves(address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(address pair,uint amountIn, uint reserveIn, uint reserveOut) public view override returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); IFeeCalcutor calc = pairFeeCalculators[pair]; if(address(calc)==address(0x0)){ uint amountInWithFee = amountIn.mul(9975);//997-->998 uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; }else{ return calc.getAmountOut(pair,amountIn,reserveIn,reserveOut); } } function feeParam(address pair) public view override returns (uint fee, uint feeBase) { IFeeCalcutor calc = pairFeeCalculators[pair]; if(address(calc)!=address(0x0)){ (uint feeTotal,uint feeBase,,) = calc.pairFeeParams(pair); if(feeTotal != 0){ return (feeBase.sub(feeTotal),feeBase); } } return (25,10000); } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(address pair,uint amountOut, uint reserveIn, uint reserveOut) public view override returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); IFeeCalcutor calc = pairFeeCalculators[pair]; if(address(calc)==address(0x0)){ uint numerator = reserveIn.mul(amountOut).mul(10000); uint denominator = reserveOut.sub(amountOut).mul(9975);//997-->998 amountIn = (numerator / denominator).add(1); }else{ return calc.getAmountIn(pair,amountOut,reserveIn,reserveOut); } } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address pair,uint amountIn, address[] memory path) public view override returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves( path[i], path[i + 1]); amounts[i + 1] = getAmountOut(pair,amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address pair,uint amountOut, address[] memory path) public view override returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves( path[i - 1], path[i]); amounts[i - 1] = getAmountIn(pair,amounts[i], reserveIn, reserveOut); } } }
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(address pair,uint amountIn, uint reserveIn, uint reserveOut) public view override returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); IFeeCalcutor calc = pairFeeCalculators[pair]; if(address(calc)==address(0x0)){ uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; return calc.getAmountOut(pair,amountIn,reserveIn,reserveOut); } }
1,831,556
// SPDX-License-Identifier: MIT 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() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @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, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @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 (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` 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 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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 ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT 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 pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @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); } } // SPDX-License-Identifier: MIT 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 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 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. */ library EnumerableSet { // 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; 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; assembly { result := store } return result; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol'; import './ERC721Ownable.sol'; import './ERC721WithMinters.sol'; import './ERC721WithRoyalties.sol'; /// @title ERC721Full /// @dev This contains all the different overrides needed on /// ERC721 / Enumerable / URIStorage / Royalties /// @author Simon Fremaux (@dievardump) abstract contract ERC721Full is ERC721Ownable, ERC721Burnable, ERC721URIStorage, ERC721WithMinters, ERC721WithRoyalties { /* * bytes4(keccak256('tokenCreator(uint256)')) == 0x40c1a064 */ bytes4 private constant _INTERFACE_TOKEN_CREATOR = 0x40c1a064; mapping(uint256 => address) private _tokenIdToCreator; /// @notice Helper for the owner to add new minter /// @dev needs to be owner /// @param newMinters list of new minters function addMinters(address[] memory newMinters) public onlyOwner { _addMinters(newMinters); } /// @notice Helper for the owner to remove a minter /// @dev needs to be owner /// @param removedMinters minters to remove function removeMinters(address[] memory removedMinters) public onlyOwner { for (uint256 i; i < removedMinters.length; i++) { _removeMinter(removedMinters[i]); } } /// @notice gets a token creator address /// @param tokenId the token id /// @return the creator's address function tokenCreator(uint256 tokenId) public view returns (address) { require(_exists(tokenId), 'Unknown token.'); return _tokenIdToCreator[tokenId]; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC721, ERC721WithRoyalties) returns (bool) { return // Taking this from FND contract // hoping this is what makes OpenSea display the creator's name in the description // and not the collection creator's name interfaceId == _INTERFACE_TOKEN_CREATOR || // or ERC721Enumerable ERC721Enumerable.supportsInterface(interfaceId) || // or Royalties ERC721WithRoyalties.supportsInterface(interfaceId); } /// @inheritdoc ERC721Ownable function isApprovedForAll(address owner_, address operator) public view override(ERC721, ERC721Ownable) returns (bool) { return ERC721Ownable.isApprovedForAll(owner_, operator); } /// @inheritdoc ERC721URIStorage function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return ERC721URIStorage.tokenURI(tokenId); } /// @inheritdoc ERC721 function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /// @inheritdoc ERC721 function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { // remove royalties _removeRoyalty(tokenId); // burn ERC721URIStorage ERC721URIStorage._burn(tokenId); } /// @notice internal helper for add minters batch so it can be used in constructor function _addMinters(address[] memory newMinters) internal { for (uint256 i; i < newMinters.length; i++) { _addMinter(newMinters[i]); } } /// @dev sets a token creator /// @param tokenId the token id /// @param creator the creator's address function _setTokenCreator(uint256 tokenId, address creator) internal { _tokenIdToCreator[tokenId] = creator; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '../OpenSea/BaseOpenSea.sol'; /// @title ERC721Ownable /// @author Simon Fremaux (@dievardump) contract ERC721Ownable is Ownable, ERC721Enumerable, BaseOpenSea { /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer) constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_ ) ERC721(name_, symbol_) { // set contract uri if present if (bytes(contractURI_).length > 0) { _setContractURI(contractURI_); } // set OpenSea proxyRegistry for gas-less trading if present if (address(0) != openseaProxyRegistry_) { _setOpenSeaRegistry(openseaProxyRegistry_); } // transferOwnership if needed if (address(0) != owner_) { transferOwnership(owner_); } } /// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user /// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy /// @inheritdoc ERC721 function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { // allows gas less trading on OpenSea return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /// @notice Helper for the owner of the contract to set the new contract URI /// @dev needs to be owner /// @param contractURI_ new contract URI function setContractURI(string memory contractURI_) external onlyOwner { _setContractURI(contractURI_); } /// @notice Helper for the owner to set OpenSea's proxy (allowing or not gas-less trading) /// @dev needs to be owner /// @param osProxyRegistry new opensea proxy registry function setOpenSeaRegistry(address osProxyRegistry) external onlyOwner { _setOpenSeaRegistry(osProxyRegistry); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; /// @title ERC721WithMinters /// @author Simon Fremaux (@dievardump) abstract contract ERC721WithMinters { using EnumerableSet for EnumerableSet.AddressSet; /// @notice emitted when a new Minter is added /// @param minter the minter address event MinterAdded(address indexed minter); /// @notice emitted when a Minter is removed /// @param minter the minter address event MinterRemoved(address indexed minter); /// @dev This is used internally to allow an address to access the minting function or not EnumerableSet.AddressSet private minters; /// @notice Helper to know is an address is minter /// @param minter the address to check function isMinter(address minter) public view returns (bool) { return minters.contains(minter); } /// @notice Helper to list all minters /// @return list of minters function listMinters() external view returns (address[] memory list) { uint256 count = minters.length(); list = new address[](count); for (uint256 i; i < count; i++) { list[i] = minters.at(i); } } /// @notice Helper for the owner to add new minter /// @param newMinter new signer function _addMinter(address newMinter) internal { minters.add(newMinter); emit MinterAdded(newMinter); } /// @notice Helper for the owner to remove a minter /// @param removedMinter minter to remove function _removeMinter(address removedMinter) internal { minters.remove(removedMinter); emit MinterRemoved(removedMinter); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../Royalties/ERC2981/ERC2981PerTokenRoyalties.sol'; import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol'; /// @dev This is a contract used for royalties on various platforms /// @author Simon Fremaux (@dievardump) contract ERC721WithRoyalties is ERC2981PerTokenRoyalties, IRaribleSecondarySales { /* * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * * => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584 */ bytes4 private constant _RARIBLE_FEES_ID = 0xb7799584; /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return ERC2981PerTokenRoyalties.supportsInterface(interfaceId) || interfaceId == _RARIBLE_FEES_ID; } /// @inheritdoc IRaribleSecondarySales function getFeeRecipients(uint256 tokenId) public view override returns (address payable[] memory recipients) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); } } /// @inheritdoc IRaribleSecondarySales function getFeeBps(uint256 tokenId) public view override returns (uint256[] memory fees) { // using ERC2981 implementation to get the amount (, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { fees = new uint256[](1); fees[0] = amount; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IMintingStation /// @author Simon Fremaux (@dievardump) interface IMintingStation { /// @notice helper to know if an address can mint or not /// @param operator the address to check function canMint(address operator) external returns (bool); /// @notice helper to know if everyone can mint or only minters /// @return if minting is open to all or not function isMintingOpenToAll() external returns (bool); /// @notice Toggle minting open to all state /// @param isOpen if the new state is open or not function setMintingOpenToAll(bool isOpen) external; /// @notice Mint one token for msg.sender /// @param tokenURI_ the token URI /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return the minted tokenId function mint( string memory tokenURI_, address feeRecipient, uint256 feeAmount ) external returns (uint256); /// @notice Mint one token to user `to` /// @param to the token recipient /// @param tokenURI_ the token URI /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenId the minted tokenId function mintTo( address to, string memory tokenURI_, address feeRecipient, uint256 feeAmount ) external returns (uint256 tokenId); /// @notice Mint several tokens for msg.sender /// @param tokenURIs_ the token URI for each id /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return all minted tokenIds function mintBatch( string[] memory tokenURIs_, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory); /// @notice Mint one token to user `to` /// @param to the token recipient /// @param tokenURIs_ the token URI for each id /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return all minted tokenIds function mintBatchTo( address to, string[] memory tokenURIs_, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory); /// @notice Mint one token to user `to` /// @param to the token recipient /// @param tokenURIs_ the token URI for each id /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds all minted tokenIds function mintBatchToMore( address[] memory to, string[] memory tokenURIs_, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory tokenIds); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './IMintingStation.sol'; import './ERC721Helpers/ERC721Full.sol'; /// @title MintingStation /// @author Simon Fremaux (@dievardump) abstract contract MintingStation is IMintingStation, ERC721Full { /// @dev This contains the last token id that was created uint256 public lastTokenId; bool internal _mintingOpenToAll; /// @notice modifier allowing only safe listed addresses to mint /// safeListed addresses are all user in the Minter or owner modifier onlyMinter(address minter) { require(_mintingOpenToAll || canMint(minter), 'Not minter.'); _; } /// @notice helper to know if an address can mint or not /// @param operator the address to check function canMint(address operator) public view virtual override returns (bool) { return isMinter(operator) || operator == owner(); } /// @notice helper to know if everyone can mint or only minters /// @inheritdoc IMintingStation function isMintingOpenToAll() public view override returns (bool) { return _mintingOpenToAll; } /// @notice Toggle minting open to all state /// @param isOpen if the new state is open or not /// @inheritdoc IMintingStation function setMintingOpenToAll(bool isOpen) external override onlyOwner { _mintingOpenToAll = isOpen; } /// @dev only a minter can call this /// @inheritdoc IMintingStation function mint( string memory tokenURI_, address royaltiesRecipient, uint256 royaltiesAmount ) public override onlyMinter(msg.sender) returns (uint256) { return mintTo(msg.sender, tokenURI_, royaltiesRecipient, royaltiesAmount); } /// @dev only a minter can call this /// @inheritdoc IMintingStation function mintTo( address to, string memory tokenURI_, address royaltiesRecipient, uint256 royaltiesAmount ) public override onlyMinter(msg.sender) returns (uint256 tokenId) { tokenId = lastTokenId + 1; // update lastTokenId before _safeMint is called lastTokenId = tokenId; _mintTo(tokenId, to, tokenURI_, royaltiesRecipient, royaltiesAmount); } /// @dev only a minter can call this /// @inheritdoc IMintingStation function mintBatch( string[] memory tokenURIs_, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory) { return mintBatchTo(msg.sender, tokenURIs_, feeRecipients, feeAmounts); } /// @dev only a minter can call this /// @inheritdoc IMintingStation function mintBatchTo( address to, string[] memory tokenURIs_, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory) { // build an array of address with only "to" inside uint256 count = tokenURIs_.length; address[] memory toBatch = new address[](count); for (uint256 i; i < count; i++) { toBatch[i] = to; } return mintBatchToMore(toBatch, tokenURIs_, feeRecipients, feeAmounts); } /// @dev only a minter can call this /// @inheritdoc IMintingStation function mintBatchToMore( address[] memory to, string[] memory tokenURIs_, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory tokenIds) { require( to.length == tokenURIs_.length && to.length == feeRecipients.length && to.length == feeAmounts.length, 'Length mismatch' ); uint256 tokenId = lastTokenId; uint256 count = tokenURIs_.length; tokenIds = new uint256[](count); for (uint256 i; i < count; i++) { tokenId++; _mintTo( tokenId, to[i], tokenURIs_[i], feeRecipients[i], feeAmounts[i] ); tokenIds[i] = tokenId; } // update lastTokenId lastTokenId = tokenId; } /// @notice Mint `tokenId` to `to` with `tokenURI_` and `royaltiesRecipient` getting secondary sales /// @dev Explain to a developer any extra details /// @param tokenId the tokenId to mint /// @param to the token recipient /// @param tokenURI_ the token URI /// @param royaltiesRecipient the recipient of royalties /// @param royaltiesAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% function _mintTo( uint256 tokenId, address to, string memory tokenURI_, address royaltiesRecipient, uint256 royaltiesAmount ) internal { _safeMint(to, tokenId, ''); _setTokenURI(tokenId, tokenURI_); _setTokenCreator(tokenId, to); if (royaltiesAmount > 0) { _setTokenRoyalty(tokenId, royaltiesRecipient, royaltiesAmount); } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's /// gas-less trading and contractURI support contract BaseOpenSea { string private _contractURI; ProxyRegistry private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Returns the current OS proxyRegistry address registered function proxyRegistry() public view returns (address) { return address(_proxyRegistry); } /// @notice Helper for OpenSea gas-less trading /// @dev Allows to check if `operator` is owner's OpenSea proxy /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { ProxyRegistry proxyRegistry_ = _proxyRegistry; return // we have a proxy registry address address(proxyRegistry_) != address(0) && // current operator is owner's proxy address address(proxyRegistry_.proxies(owner)) == operator; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = ProxyRegistry(proxyRegistryAddress); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; import './IERC2981Royalties.sol'; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 abstract contract ERC2981PerTokenRoyalties is ERC165, IERC2981Royalties { struct Royalty { address recipient; uint256 value; } mapping(uint256 => Royalty) private _royalties; /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId; } /// @dev Sets token royalties /// @param id the token id fir which we register the royalties function _removeRoyalty(uint256 id) internal { delete _royalties[id]; } /// @dev Sets token royalties /// @param id the token id fir which we register the royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setTokenRoyalty( uint256 id, address recipient, uint256 value ) internal { require(value <= 10000, 'ERC2981Royalties: Too high'); _royalties[id] = Royalty(recipient, value); } /// @dev Gets token royalties /// @param id the token id for which we check the royalties function _getTokenRoyalty(uint256 id) internal view returns (address, uint256) { Royalty memory royalty = _royalties[id]; return (royalty.recipient, royalty.value); } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256 tokenId, uint256 value) public view override returns (address receiver, uint256 royaltyAmount) { Royalty memory royalty = _royalties[tokenId]; return (royalty.recipient, (value * royalty.value) / 10000); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IRaribleSecondarySales { /// @notice returns a list of royalties recipients /// @param tokenId the token Id to check for /// @return all the recipients for tokenId function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); /// @notice returns a list of royalties amounts /// @param tokenId the token Id to check for /// @return all the amounts for tokenId function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './MintingStation.sol'; /// @title VerticalCrypto /// @author Simon Fremaux (@dievardump) contract VerticalCrypto is MintingStation { /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer) constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_, address[] memory minters ) ERC721Ownable( name_, symbol_, contractURI_, openseaProxyRegistry_, owner_ ) { if (minters.length > 0) { _addMinters(minters); } } }
gets a token creator address tokenId the token id return the creator's address
function tokenCreator(uint256 tokenId) public view returns (address) { require(_exists(tokenId), 'Unknown token.'); return _tokenIdToCreator[tokenId]; }
1,306,413
./full_match/11155111/0x039794dAe419d28AEF3d115F257eccF5125962be/sources/project_/contracts/World1.sol
return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); }
3,813,780
./full_match/3/0x967328588D821b4306fe8F0592faFE94eC930429/sources/contracts/Token5.sol
Returns the subtraction of two unsigned integers, reverting with custom message on overflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot overflow./
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
8,243,750
./full_match/1/0x31a91336414d3B955E494E7d485a6B06b55FC8fB/sources/contracts/vault/VaultAdmin.sol
Set the deposit paused flag to false to enable capital movement./
function unpauseCapital() external onlyGovernorOrStrategist { capitalPaused = false; emit CapitalUnpaused(); }
4,932,158
./full_match/84531/0x7c226aF12DC97a1280C786263d969dB2B70b7A8D/sources/GetBasedContract.sol
See {IERC721-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); }
11,506,949
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @dev Receive function. * Implemented entirely in `_fallback`. */ receive() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title UpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract UpgradeabilityProxy is Proxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /** * @title AdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor( address _logic, address _admin, bytes memory _data ) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } }
Only fall back when the sender is not the admin./
function _willFallback() internal virtual override { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); }
636,734
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // File: contracts/lib/AddressUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for addresses /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library AddressUtil { using AddressUtil for *; function isContract( address addr ) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function toPayable( address addr ) internal pure returns (address payable) { return payable(addr); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETH( address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.toPayable(); /* solium-disable-next-line */ (success, ) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETHAndVerify( address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.sendETH(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } // Works like call but is slightly more efficient when data // needs to be copied from memory to do the call. function fastCall( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bool success, bytes memory returnData) { if (to != address(0)) { assembly { // Do the call success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0) // Copy the return data let size := returndatasize() returnData := mload(0x40) mstore(returnData, size) returndatacopy(add(returnData, 32), 0, size) // Update free memory pointer mstore(0x40, add(returnData, add(32, size))) } } } // Like fastCall, but throws when the call is unsuccessful. function fastCallAndVerify( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bytes memory returnData) { bool success; (success, returnData) = fastCall(to, gasLimit, value, data); if (!success) { assembly { revert(add(returnData, 32), mload(returnData)) } } } } // File: contracts/lib/MathUint.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { using MathUint for uint; function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function add64( uint64 a, uint64 b ) internal pure returns (uint64 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } // File: contracts/thirdparty/BytesUtil.sol //Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesUtil { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) { require(_bytes.length >= (_start + 3)); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) { require(_bytes.length >= (_start + 20)); bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) { address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) { uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) { uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) { uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) { uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) { uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) { uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) { uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) { bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) { bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) { bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function fastSHA256( bytes memory data ) internal view returns (bytes32) { bytes32[] memory result = new bytes32[](1); bool success; assembly { let ptr := add(data, 32) success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32) } require(success, "SHA256_FAILED"); return result[0]; } } // File: contracts/core/iface/IAgentRegistry.sol // Copyright 2017 Loopring Technology Limited. interface IAgent{} abstract contract IAgentRegistry { /// @dev Returns whether an agent address is an agent of an account owner /// @param owner The account owner. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address owner, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is an agent of all account owners /// @param owners The account owners. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address[] calldata owners, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is a universal agent. /// @param agent The agent address /// @return True if the agent address is a universal agent, else false function isUniversalAgent(address agent) public virtual view returns (bool); } // File: contracts/lib/Ownable.sol // Copyright 2017 Loopring Technology Limited. /// @title Ownable /// @author Brecht Devos - <[email protected]> /// @dev The Ownable contract has an owner address, and provides basic /// authorization control functions, this simplifies the implementation of /// "user permissions". contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev The Ownable constructor sets the original `owner` of the contract /// to the sender. constructor() { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// new owner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public virtual onlyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } // File: contracts/lib/Claimable.sol // Copyright 2017 Loopring Technology Limited. /// @title Claimable /// @author Brecht Devos - <[email protected]> /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public override onlyOwner { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/core/iface/IBlockVerifier.sol // Copyright 2017 Loopring Technology Limited. /// @title IBlockVerifier /// @author Brecht Devos - <[email protected]> abstract contract IBlockVerifier is Claimable { // -- Events -- event CircuitRegistered( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); event CircuitDisabled( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); // -- Public functions -- /// @dev Sets the verifying key for the specified circuit. /// Every block permutation needs its own circuit and thus its own set of /// verification keys. Only a limited number of block sizes per block /// type are supported. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param vk The verification key function registerCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[18] calldata vk ) external virtual; /// @dev Disables the use of the specified circuit. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) function disableCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual; /// @dev Verifies blocks with the given public data and proofs. /// Verifying a block makes sure all requests handled in the block /// are correctly handled by the operator. /// @param blockType The type of block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param publicInputs The hash of all the public data of the blocks /// @param proofs The ZK proofs proving that the blocks are correct /// @return True if the block is valid, false otherwise function verifyProofs( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[] calldata publicInputs, uint[] calldata proofs ) external virtual view returns (bool); /// @dev Checks if a circuit with the specified parameters is registered. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is registered, false otherwise function isCircuitRegistered( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); /// @dev Checks if a circuit can still be used to commit new blocks. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is enabled, false otherwise function isCircuitEnabled( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); } // File: contracts/core/iface/IDepositContract.sol // Copyright 2017 Loopring Technology Limited. /// @title IDepositContract. /// @dev Contract storing and transferring funds for an exchange. /// /// ERC1155 tokens can be supported by registering pseudo token addresses calculated /// as `address(keccak256(real_token_address, token_params))`. Then the custom /// deposit contract can look up the real token address and paramsters with the /// pseudo token address before doing the transfers. /// @author Brecht Devos - <[email protected]> interface IDepositContract { /// @dev Returns if a token is suppoprted by this contract. function isTokenSupported(address token) external view returns (bool); /// @dev Transfers tokens from a user to the exchange. This function will /// be called when a user deposits funds to the exchange. /// In a simple implementation the funds are simply stored inside the /// deposit contract directly. More advanced implementations may store the funds /// in some DeFi application to earn interest, so this function could directly /// call the necessary functions to store the funds there. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens to transfer. /// @param extraData Opaque data that can be used by the contract to handle the deposit /// @return amountReceived The amount to deposit to the user's account in the Merkle tree function deposit( address from, address token, uint96 amount, bytes calldata extraData ) external payable returns (uint96 amountReceived); /// @dev Transfers tokens from the exchange to a user. This function will /// be called when a withdrawal is done for a user on the exchange. /// In the simplest implementation the funds are simply stored inside the /// deposit contract directly so this simply transfers the requested tokens back /// to the user. More advanced implementations may store the funds /// in some DeFi application to earn interest so the function would /// need to get those tokens back from the DeFi application first before they /// can be transferred to the user. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address from which 'amount' tokens are transferred. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens transferred. /// @param extraData Opaque data that can be used by the contract to handle the withdrawal function withdraw( address from, address to, address token, uint amount, bytes calldata extraData ) external payable; /// @dev Transfers tokens (ETH not supported) for a user using the allowance set /// for the exchange. This way the approval can be used for all functionality (and /// extended functionality) of the exchange. /// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw` /// should be used for that as they will contain specialised logic for those operations. /// This function can be called by the exchange to transfer onchain funds of users /// necessary for Agent functionality. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function transfer( address from, address to, address token, uint amount ) external payable; /// @dev Checks if the given address is used for depositing ETH or not. /// Is used while depositing to send the correct ETH amount to the deposit contract. /// /// Note that 0x0 is always registered for deposting ETH when the exchange is created! /// This function allows additional addresses to be used for depositing ETH, the deposit /// contract can implement different behaviour based on the address value. /// /// @param addr The address to check /// @return True if the address is used for depositing ETH, else false. function isETH(address addr) external view returns (bool); } // File: contracts/core/iface/ILoopringV3.sol // Copyright 2017 Loopring Technology Limited. /// @title ILoopringV3 /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract ILoopringV3 is Claimable { // == Events == event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time); // == Public Variables == mapping (address => uint) internal exchangeStake; uint public totalStake; address public blockVerifierAddress; uint public forcedWithdrawalFee; uint public tokenRegistrationFeeLRCBase; uint public tokenRegistrationFeeLRCDelta; uint8 public protocolTakerFeeBips; uint8 public protocolMakerFeeBips; address payable public protocolFeeVault; // == Public Functions == /// @dev Returns the LRC token address /// @return the LRC token address function lrcAddress() external view virtual returns (address); /// @dev Updates the global exchange settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateSettings( address payable _protocolFeeVault, // address(0) not allowed address _blockVerifierAddress, // address(0) not allowed uint _forcedWithdrawalFee ) external virtual; /// @dev Updates the global protocol fee settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateProtocolFeeSettings( uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external virtual; /// @dev Gets the amount of staked LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @return stakedLRC The amount of LRC function getExchangeStake( address exchangeAddr ) public virtual view returns (uint stakedLRC); /// @dev Burns a certain amount of staked LRC for a specific exchange. /// This function is meant to be called only from exchange contracts. /// @return burnedLRC The amount of LRC burned. If the amount is greater than /// the staked amount, all staked LRC will be burned. function burnExchangeStake( uint amount ) external virtual returns (uint burnedLRC); /// @dev Stakes more LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @param amountLRC The amount of LRC to stake /// @return stakedLRC The total amount of LRC staked for the exchange function depositExchangeStake( address exchangeAddr, uint amountLRC ) external virtual returns (uint stakedLRC); /// @dev Withdraws a certain amount of staked LRC for an exchange to the given address. /// This function is meant to be called only from within exchange contracts. /// @param recipient The address to receive LRC /// @param requestedAmount The amount of LRC to withdraw /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient, uint requestedAmount ) external virtual returns (uint amountLRC); /// @dev Gets the protocol fee values for an exchange. /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee function getProtocolFeeValues( ) public virtual view returns ( uint8 takerFeeBips, uint8 makerFeeBips ); } // File: contracts/core/iface/ExchangeData.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeData /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeData { // -- Enums -- enum TransactionType { NOOP, DEPOSIT, WITHDRAWAL, TRANSFER, SPOT_TRADE, ACCOUNT_UPDATE, AMM_UPDATE, SIGNATURE_VERIFICATION } // -- Structs -- struct Token { address token; } struct ProtocolFeeData { uint32 syncedAt; // only valid before 2105 (85 years to go) uint8 takerFeeBips; uint8 makerFeeBips; uint8 previousTakerFeeBips; uint8 previousMakerFeeBips; } // General auxiliary data for each conditional transaction struct AuxiliaryData { uint txIndex; bool approved; bytes data; } // This is the (virtual) block the owner needs to submit onchain to maintain the // per-exchange (virtual) blockchain. struct Block { uint8 blockType; uint16 blockSize; uint8 blockVersion; bytes data; uint256[8] proof; // Whether we should store the @BlockInfo for this block on-chain. bool storeBlockInfoOnchain; // Block specific data that is only used to help process the block on-chain. // It is not used as input for the circuits and it is not necessary for data-availability. // This bytes array contains the abi encoded AuxiliaryData[] data. bytes auxiliaryData; // Arbitrary data, mainly for off-chain data-availability, i.e., // the multihash of the IPFS file that contains the block data. bytes offchainData; } struct BlockInfo { // The time the block was submitted on-chain. uint32 timestamp; // The public data hash of the block (the 28 most significant bytes). bytes28 blockDataHash; } // Represents an onchain deposit request. struct Deposit { uint96 amount; uint64 timestamp; } // A forced withdrawal request. // If the actual owner of the account initiated the request (we don't know who the owner is // at the time the request is being made) the full balance will be withdrawn. struct ForcedWithdrawal { address owner; uint64 timestamp; } struct Constants { uint SNARK_SCALAR_FIELD; uint MAX_OPEN_FORCED_REQUESTS; uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE; uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS; uint MAX_NUM_ACCOUNTS; uint MAX_NUM_TOKENS; uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED; uint MIN_TIME_IN_SHUTDOWN; uint TX_DATA_AVAILABILITY_SIZE; uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; } // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint public constant MAX_OPEN_FORCED_REQUESTS = 4096; uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days; uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days; uint public constant MAX_NUM_ACCOUNTS = 2 ** 32; uint public constant MAX_NUM_TOKENS = 2 ** 16; uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days; uint public constant MIN_TIME_IN_SHUTDOWN = 30 days; // The amount of bytes each rollup transaction uses in the block data for data-availability. // This is the maximum amount of bytes of all different transaction types. uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days; uint32 public constant ACCOUNTID_PROTOCOLFEE = 0; uint public constant TX_DATA_AVAILABILITY_SIZE = 68; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39; struct AccountLeaf { uint32 accountID; address owner; uint pubKeyX; uint pubKeyY; uint32 nonce; uint feeBipsAMM; } struct BalanceLeaf { uint16 tokenID; uint96 balance; uint96 weightAMM; uint storageRoot; } struct MerkleProof { ExchangeData.AccountLeaf accountLeaf; ExchangeData.BalanceLeaf balanceLeaf; uint[48] accountMerkleProof; uint[24] balanceMerkleProof; } struct BlockContext { bytes32 DOMAIN_SEPARATOR; uint32 timestamp; } // Represents the entire exchange state except the owner of the exchange. struct State { uint32 maxAgeDepositUntilWithdrawable; bytes32 DOMAIN_SEPARATOR; ILoopringV3 loopring; IBlockVerifier blockVerifier; IAgentRegistry agentRegistry; IDepositContract depositContract; // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree // stores balances for users using an account model. bytes32 merkleRoot; // List of all blocks mapping(uint => BlockInfo) blocks; uint numBlocks; // List of all tokens Token[] tokens; // A map from a token to its tokenID + 1 mapping (address => uint16) tokenToTokenId; // A map from an accountID to a tokenID to if the balance is withdrawn mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode; // A map from an account to a token to the amount withdrawable for that account. // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (uint16 => uint)) amountWithdrawable; // A map from an account to a token to the forced withdrawal (always full balance) mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals; // A map from an address to a token to a deposit mapping (address => mapping (uint16 => Deposit)) pendingDeposits; // A map from an account owner to an approved transaction hash to if the transaction is approved or not mapping (address => mapping (bytes32 => bool)) approvedTx; // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient; // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner uint32 numPendingForcedTransactions; // Cached data for the protocol fee ProtocolFeeData protocolFeeData; // Time when the exchange was shutdown uint shutdownModeStartTime; // Time when the exchange has entered withdrawal mode uint withdrawalModeStartTime; // Last time the protocol fee was withdrawn for a specific token mapping (address => uint) protocolFeeLastWithdrawnTime; } } // File: contracts/core/impl/libtransactions/BlockReader.sol // Copyright 2017 Loopring Technology Limited. /// @title BlockReader /// @author Brecht Devos - <[email protected]> /// @dev Utility library to read block data. library BlockReader { using BlockReader for ExchangeData.Block; using BytesUtil for bytes; uint public constant OFFSET_TO_TRANSACTIONS = 20 + 32 + 32 + 4 + 1 + 1 + 4 + 4; struct BlockHeader { address exchange; bytes32 merkleRootBefore; bytes32 merkleRootAfter; uint32 timestamp; uint8 protocolTakerFeeBips; uint8 protocolMakerFeeBips; uint32 numConditionalTransactions; uint32 operatorAccountID; } function readHeader( bytes memory _blockData ) internal pure returns (BlockHeader memory header) { uint offset = 0; header.exchange = _blockData.toAddress(offset); offset += 20; header.merkleRootBefore = _blockData.toBytes32(offset); offset += 32; header.merkleRootAfter = _blockData.toBytes32(offset); offset += 32; header.timestamp = _blockData.toUint32(offset); offset += 4; header.protocolTakerFeeBips = _blockData.toUint8(offset); offset += 1; header.protocolMakerFeeBips = _blockData.toUint8(offset); offset += 1; header.numConditionalTransactions = _blockData.toUint32(offset); offset += 4; header.operatorAccountID = _blockData.toUint32(offset); offset += 4; assert(offset == OFFSET_TO_TRANSACTIONS); } function readTransactionData( bytes memory data, uint txIdx, uint blockSize, bytes memory txData ) internal pure { require(txIdx < blockSize, "INVALID_TX_IDX"); // The transaction was transformed to make it easier to compress. // Transform it back here. // Part 1 uint txDataOffset = OFFSET_TO_TRANSACTIONS + txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1; assembly { mstore(add(txData, 32), mload(add(data, add(txDataOffset, 32)))) } // Part 2 txDataOffset = OFFSET_TO_TRANSACTIONS + blockSize * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1 + txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_2; assembly { mstore(add(txData, 61 /*32 + 29*/), mload(add(data, add(txDataOffset, 32)))) mstore(add(txData, 68 ), mload(add(data, add(txDataOffset, 39)))) } } } // File: contracts/lib/EIP712.sol // Copyright 2017 Loopring Technology Limited. library EIP712 { struct Domain { string name; string version; address verifyingContract; } bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); string constant internal EIP191_HEADER = "\x19\x01"; function hash(Domain memory domain) internal pure returns (bytes32) { uint _chainid; assembly { _chainid := chainid() } return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(domain.name)), keccak256(bytes(domain.version)), _chainid, domain.verifyingContract ) ); } function hashPacked( bytes32 domainHash, bytes32 dataHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( EIP191_HEADER, domainHash, dataHash ) ); } } // File: contracts/thirdparty/SafeCast.sol // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits"); return uint40(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/lib/FloatUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for floats /// @author Brecht Devos - <[email protected]> library FloatUtil { using MathUint for uint; using SafeCast for uint; // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits for the exponent /// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent) /// @return value The decoded integer value. function decodeFloat( uint f, uint numBits ) internal pure returns (uint96 value) { if (f == 0) { return 0; } uint numBitsMantissa = numBits.sub(5); uint exponent = f >> numBitsMantissa; // log2(10**77) = 255.79 < 256 require(exponent <= 77, "EXPONENT_TOO_LARGE"); uint mantissa = f & ((1 << numBitsMantissa) - 1); value = mantissa.mul(10 ** exponent).toUint96(); } // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits exponent, 11 bits mantissa /// @return value The decoded integer value. function decodeFloat16( uint16 f ) internal pure returns (uint96) { uint value = ((uint(f) & 2047) * (10 ** (uint(f) >> 11))); require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits exponent, 19 bits mantissa /// @return value The decoded integer value. function decodeFloat24( uint24 f ) internal pure returns (uint96) { uint value = ((uint(f) & 524287) * (10 ** (uint(f) >> 19))); require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } } // File: contracts/lib/ERC1271.sol // Copyright 2017 Loopring Technology Limited. abstract contract ERC1271 { // bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function isValidSignature( bytes32 _hash, bytes memory _signature) public view virtual returns (bytes4 magicValueB32); } // File: contracts/lib/SignatureUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title SignatureUtil /// @author Daniel Wang - <[email protected]> /// @dev This method supports multihash standard. Each signature's last byte indicates /// the signature's type. library SignatureUtil { using BytesUtil for bytes; using MathUint for uint; using AddressUtil for address; enum SignatureType { ILLEGAL, INVALID, EIP_712, ETH_SIGN, WALLET // deprecated } bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function verifySignatures( bytes32 signHash, address[] memory signers, bytes[] memory signatures ) internal view returns (bool) { require(signers.length == signatures.length, "BAD_SIGNATURE_DATA"); address lastSigner; for (uint i = 0; i < signers.length; i++) { require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER"); lastSigner = signers[i]; if (!verifySignature(signHash, signers[i], signatures[i])) { return false; } } return true; } function verifySignature( bytes32 signHash, address signer, bytes memory signature ) internal view returns (bool) { if (signer == address(0)) { return false; } return signer.isContract()? verifyERC1271Signature(signHash, signer, signature): verifyEOASignature(signHash, signer, signature); } function recoverECDSASigner( bytes32 signHash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return address(0); } bytes32 r; bytes32 s; uint8 v; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := and(mload(add(signature, 0x41)), 0xff) } // See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v == 27 || v == 28) { return ecrecover(signHash, v, r, s); } else { return address(0); } } function verifyEOASignature( bytes32 signHash, address signer, bytes memory signature ) private pure returns (bool success) { if (signer == address(0)) { return false; } uint signatureTypeOffset = signature.length.sub(1); SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset)); // Strip off the last byte of the signature by updating the length assembly { mstore(signature, signatureTypeOffset) } if (signatureType == SignatureType.EIP_712) { success = (signer == recoverECDSASigner(signHash, signature)); } else if (signatureType == SignatureType.ETH_SIGN) { bytes32 hash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash) ); success = (signer == recoverECDSASigner(hash, signature)); } else { success = false; } // Restore the signature length assembly { mstore(signature, add(signatureTypeOffset, 1)) } return success; } function verifyERC1271Signature( bytes32 signHash, address signer, bytes memory signature ) private view returns (bool) { bytes memory callData = abi.encodeWithSelector( ERC1271.isValidSignature.selector, signHash, signature ); (bool success, bytes memory result) = signer.staticcall(callData); return ( success && result.length == 32 && result.toBytes4(0) == ERC1271_MAGICVALUE ); } } // File: contracts/core/impl/libexchange/ExchangeSignatures.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeSignatures. /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeSignatures { using SignatureUtil for bytes32; function requireAuthorizedTx( ExchangeData.State storage S, address signer, bytes memory signature, bytes32 txHash ) internal // inline call { require(signer != address(0), "INVALID_SIGNER"); // Verify the signature if one is provided, otherwise fall back to an approved tx if (signature.length > 0) { require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE"); } else { require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED"); delete S.approvedTx[signer][txHash]; } } } // File: contracts/core/impl/libtransactions/AccountUpdateTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title AccountUpdateTransaction /// @author Brecht Devos - <[email protected]> library AccountUpdateTransaction { using BytesUtil for bytes; using FloatUtil for uint16; using ExchangeSignatures for ExchangeData.State; bytes32 constant public ACCOUNTUPDATE_TYPEHASH = keccak256( "AccountUpdate(address owner,uint32 accountID,uint16 feeTokenID,uint96 maxFee,uint256 publicKey,uint32 validUntil,uint32 nonce)" ); struct AccountUpdate { address owner; uint32 accountID; uint16 feeTokenID; uint96 maxFee; uint96 fee; uint publicKey; uint32 validUntil; uint32 nonce; } // Auxiliary data for each account update struct AccountUpdateAuxiliaryData { bytes signature; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read the account update AccountUpdate memory accountUpdate; readTx(data, offset, accountUpdate); AccountUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AccountUpdateAuxiliaryData)); // Fill in withdrawal data missing from DA accountUpdate.validUntil = auxData.validUntil; accountUpdate.maxFee = auxData.maxFee == 0 ? accountUpdate.fee : auxData.maxFee; // Validate require(ctx.timestamp < accountUpdate.validUntil, "ACCOUNT_UPDATE_EXPIRED"); require(accountUpdate.fee <= accountUpdate.maxFee, "ACCOUNT_UPDATE_FEE_TOO_HIGH"); // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, accountUpdate); // Check onchain authorization S.requireAuthorizedTx(accountUpdate.owner, auxData.signature, txHash); } function readTx( bytes memory data, uint offset, AccountUpdate memory accountUpdate ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.ACCOUNT_UPDATE), "INVALID_TX_TYPE"); _offset += 1; // Check that this is a conditional offset require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA"); _offset += 1; // Extract the data from the tx data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. accountUpdate.owner = data.toAddressUnsafe(_offset); _offset += 20; accountUpdate.accountID = data.toUint32Unsafe(_offset); _offset += 4; accountUpdate.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; accountUpdate.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; accountUpdate.publicKey = data.toUintUnsafe(_offset); _offset += 32; accountUpdate.nonce = data.toUint32Unsafe(_offset); _offset += 4; } function hashTx( bytes32 DOMAIN_SEPARATOR, AccountUpdate memory accountUpdate ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( ACCOUNTUPDATE_TYPEHASH, accountUpdate.owner, accountUpdate.accountID, accountUpdate.feeTokenID, accountUpdate.maxFee, accountUpdate.publicKey, accountUpdate.validUntil, accountUpdate.nonce ) ) ); } } // File: contracts/core/impl/libtransactions/AmmUpdateTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title AmmUpdateTransaction /// @author Brecht Devos - <[email protected]> library AmmUpdateTransaction { using BytesUtil for bytes; using MathUint for uint; using ExchangeSignatures for ExchangeData.State; bytes32 constant public AMMUPDATE_TYPEHASH = keccak256( "AmmUpdate(address owner,uint32 accountID,uint16 tokenID,uint8 feeBips,uint96 tokenWeight,uint32 validUntil,uint32 nonce)" ); struct AmmUpdate { address owner; uint32 accountID; uint16 tokenID; uint8 feeBips; uint96 tokenWeight; uint32 validUntil; uint32 nonce; uint96 balance; } // Auxiliary data for each AMM update struct AmmUpdateAuxiliaryData { bytes signature; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read in the AMM update AmmUpdate memory update; readTx(data, offset, update); AmmUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AmmUpdateAuxiliaryData)); // Check validUntil require(ctx.timestamp < auxData.validUntil, "AMM_UPDATE_EXPIRED"); update.validUntil = auxData.validUntil; // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, update); // Check the on-chain authorization S.requireAuthorizedTx(update.owner, auxData.signature, txHash); } function readTx( bytes memory data, uint offset, AmmUpdate memory update ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.AMM_UPDATE), "INVALID_TX_TYPE"); _offset += 1; // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. update.owner = data.toAddressUnsafe(_offset); _offset += 20; update.accountID = data.toUint32Unsafe(_offset); _offset += 4; update.tokenID = data.toUint16Unsafe(_offset); _offset += 2; update.feeBips = data.toUint8Unsafe(_offset); _offset += 1; update.tokenWeight = data.toUint96Unsafe(_offset); _offset += 12; update.nonce = data.toUint32Unsafe(_offset); _offset += 4; update.balance = data.toUint96Unsafe(_offset); _offset += 12; } function hashTx( bytes32 DOMAIN_SEPARATOR, AmmUpdate memory update ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( AMMUPDATE_TYPEHASH, update.owner, update.accountID, update.tokenID, update.feeBips, update.tokenWeight, update.validUntil, update.nonce ) ) ); } } // File: contracts/lib/MathUint96.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint96 { function add( uint96 a, uint96 b ) internal pure returns (uint96 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function sub( uint96 a, uint96 b ) internal pure returns (uint96 c) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } } // File: contracts/core/impl/libtransactions/DepositTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title DepositTransaction /// @author Brecht Devos - <[email protected]> library DepositTransaction { using BytesUtil for bytes; using MathUint96 for uint96; struct Deposit { address to; uint32 toAccountID; uint16 tokenID; uint96 amount; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory /*ctx*/, bytes memory data, uint offset, bytes memory /*auxiliaryData*/ ) internal { // Read in the deposit Deposit memory deposit; readTx(data, offset, deposit); if (deposit.amount == 0) { return; } // Process the deposit ExchangeData.Deposit memory pendingDeposit = S.pendingDeposits[deposit.to][deposit.tokenID]; // Make sure the deposit was actually done require(pendingDeposit.timestamp > 0, "DEPOSIT_DOESNT_EXIST"); // Processing partial amounts of the deposited amount is allowed. // This is done to ensure the user can do multiple deposits after each other // without invalidating work done by the exchange owner for previous deposit amounts. require(pendingDeposit.amount >= deposit.amount, "INVALID_AMOUNT"); pendingDeposit.amount = pendingDeposit.amount.sub(deposit.amount); // If the deposit was fully consumed, reset it so the storage is freed up // and the owner receives a gas refund. if (pendingDeposit.amount == 0) { delete S.pendingDeposits[deposit.to][deposit.tokenID]; } else { S.pendingDeposits[deposit.to][deposit.tokenID] = pendingDeposit; } } function readTx( bytes memory data, uint offset, Deposit memory deposit ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.DEPOSIT), "INVALID_TX_TYPE"); _offset += 1; // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. deposit.to = data.toAddressUnsafe(_offset); _offset += 20; deposit.toAccountID = data.toUint32Unsafe(_offset); _offset += 4; deposit.tokenID = data.toUint16Unsafe(_offset); _offset += 2; deposit.amount = data.toUint96Unsafe(_offset); _offset += 12; } } // File: contracts/core/impl/libtransactions/TransferTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title TransferTransaction /// @author Brecht Devos - <[email protected]> library TransferTransaction { using BytesUtil for bytes; using FloatUtil for uint24; using FloatUtil for uint16; using MathUint for uint; using ExchangeSignatures for ExchangeData.State; bytes32 constant public TRANSFER_TYPEHASH = keccak256( "Transfer(address from,address to,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,uint32 validUntil,uint32 storageID)" ); struct Transfer { uint32 fromAccountID; uint32 toAccountID; address from; address to; uint16 tokenID; uint96 amount; uint16 feeTokenID; uint96 maxFee; uint96 fee; uint32 validUntil; uint32 storageID; } // Auxiliary data for each transfer struct TransferAuxiliaryData { bytes signature; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read the transfer Transfer memory transfer; readTx(data, offset, transfer); TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData)); // Fill in withdrawal data missing from DA transfer.validUntil = auxData.validUntil; transfer.maxFee = auxData.maxFee == 0 ? transfer.fee : auxData.maxFee; // Validate require(ctx.timestamp < transfer.validUntil, "TRANSFER_EXPIRED"); require(transfer.fee <= transfer.maxFee, "TRANSFER_FEE_TOO_HIGH"); // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, transfer); // Check the on-chain authorization S.requireAuthorizedTx(transfer.from, auxData.signature, txHash); } function readTx( bytes memory data, uint offset, Transfer memory transfer ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.TRANSFER), "INVALID_TX_TYPE"); _offset += 1; // Check that this is a conditional transfer require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA"); _offset += 1; // Extract the transfer data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. transfer.fromAccountID = data.toUint32Unsafe(_offset); _offset += 4; transfer.toAccountID = data.toUint32Unsafe(_offset); _offset += 4; transfer.tokenID = data.toUint16Unsafe(_offset); _offset += 2; transfer.amount = data.toUint24Unsafe(_offset).decodeFloat24(); _offset += 3; transfer.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; transfer.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; transfer.storageID = data.toUint32Unsafe(_offset); _offset += 4; transfer.to = data.toAddressUnsafe(_offset); _offset += 20; transfer.from = data.toAddressUnsafe(_offset); _offset += 20; } function hashTx( bytes32 DOMAIN_SEPARATOR, Transfer memory transfer ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( TRANSFER_TYPEHASH, transfer.from, transfer.to, transfer.tokenID, transfer.amount, transfer.feeTokenID, transfer.maxFee, transfer.validUntil, transfer.storageID ) ) ); } } // File: contracts/core/impl/libexchange/ExchangeMode.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeMode. /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeMode { using MathUint for uint; function isInWithdrawalMode( ExchangeData.State storage S ) internal // inline call view returns (bool result) { result = S.withdrawalModeStartTime > 0; } function isShutdown( ExchangeData.State storage S ) internal // inline call view returns (bool) { return S.shutdownModeStartTime > 0; } function getNumAvailableForcedSlots( ExchangeData.State storage S ) internal view returns (uint) { return ExchangeData.MAX_OPEN_FORCED_REQUESTS - S.numPendingForcedTransactions; } } // File: contracts/lib/Poseidon.sol // Copyright 2017 Loopring Technology Limited. /// @title Poseidon hash function /// See: https://eprint.iacr.org/2019/458.pdf /// Code auto-generated by generate_poseidon_EVM_code.py /// @author Brecht Devos - <[email protected]> library Poseidon { // // hash_t5f6p52 // struct HashInputs5 { uint t0; uint t1; uint t2; uint t3; uint t4; } function hash_t5f6p52_internal( uint t0, uint t1, uint t2, uint t3, uint t4, uint q ) internal pure returns (uint) { assembly { function mix(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 { nt0 := mulmod(_t0, 4977258759536702998522229302103997878600602264560359702680165243908162277980, _q) nt0 := addmod(nt0, mulmod(_t1, 19167410339349846567561662441069598364702008768579734801591448511131028229281, _q), _q) nt0 := addmod(nt0, mulmod(_t2, 14183033936038168803360723133013092560869148726790180682363054735190196956789, _q), _q) nt0 := addmod(nt0, mulmod(_t3, 9067734253445064890734144122526450279189023719890032859456830213166173619761, _q), _q) nt0 := addmod(nt0, mulmod(_t4, 16378664841697311562845443097199265623838619398287411428110917414833007677155, _q), _q) nt1 := mulmod(_t0, 107933704346764130067829474107909495889716688591997879426350582457782826785, _q) nt1 := addmod(nt1, mulmod(_t1, 17034139127218860091985397764514160131253018178110701196935786874261236172431, _q), _q) nt1 := addmod(nt1, mulmod(_t2, 2799255644797227968811798608332314218966179365168250111693473252876996230317, _q), _q) nt1 := addmod(nt1, mulmod(_t3, 2482058150180648511543788012634934806465808146786082148795902594096349483974, _q), _q) nt1 := addmod(nt1, mulmod(_t4, 16563522740626180338295201738437974404892092704059676533096069531044355099628, _q), _q) nt2 := mulmod(_t0, 13596762909635538739079656925495736900379091964739248298531655823337482778123, _q) nt2 := addmod(nt2, mulmod(_t1, 18985203040268814769637347880759846911264240088034262814847924884273017355969, _q), _q) nt2 := addmod(nt2, mulmod(_t2, 8652975463545710606098548415650457376967119951977109072274595329619335974180, _q), _q) nt2 := addmod(nt2, mulmod(_t3, 970943815872417895015626519859542525373809485973005165410533315057253476903, _q), _q) nt2 := addmod(nt2, mulmod(_t4, 19406667490568134101658669326517700199745817783746545889094238643063688871948, _q), _q) nt3 := mulmod(_t0, 2953507793609469112222895633455544691298656192015062835263784675891831794974, _q) nt3 := addmod(nt3, mulmod(_t1, 19025623051770008118343718096455821045904242602531062247152770448380880817517, _q), _q) nt3 := addmod(nt3, mulmod(_t2, 9077319817220936628089890431129759976815127354480867310384708941479362824016, _q), _q) nt3 := addmod(nt3, mulmod(_t3, 4770370314098695913091200576539533727214143013236894216582648993741910829490, _q), _q) nt3 := addmod(nt3, mulmod(_t4, 4298564056297802123194408918029088169104276109138370115401819933600955259473, _q), _q) nt4 := mulmod(_t0, 8336710468787894148066071988103915091676109272951895469087957569358494947747, _q) nt4 := addmod(nt4, mulmod(_t1, 16205238342129310687768799056463408647672389183328001070715567975181364448609, _q), _q) nt4 := addmod(nt4, mulmod(_t2, 8303849270045876854140023508764676765932043944545416856530551331270859502246, _q), _q) nt4 := addmod(nt4, mulmod(_t3, 20218246699596954048529384569730026273241102596326201163062133863539137060414, _q), _q) nt4 := addmod(nt4, mulmod(_t4, 1712845821388089905746651754894206522004527237615042226559791118162382909269, _q), _q) } function ark(_t0, _t1, _t2, _t3, _t4, _q, c) -> nt0, nt1, nt2, nt3, nt4 { nt0 := addmod(_t0, c, _q) nt1 := addmod(_t1, c, _q) nt2 := addmod(_t2, c, _q) nt3 := addmod(_t3, c, _q) nt4 := addmod(_t4, c, _q) } function sbox_full(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 { nt0 := mulmod(_t0, _t0, _q) nt0 := mulmod(nt0, nt0, _q) nt0 := mulmod(_t0, nt0, _q) nt1 := mulmod(_t1, _t1, _q) nt1 := mulmod(nt1, nt1, _q) nt1 := mulmod(_t1, nt1, _q) nt2 := mulmod(_t2, _t2, _q) nt2 := mulmod(nt2, nt2, _q) nt2 := mulmod(_t2, nt2, _q) nt3 := mulmod(_t3, _t3, _q) nt3 := mulmod(nt3, nt3, _q) nt3 := mulmod(_t3, nt3, _q) nt4 := mulmod(_t4, _t4, _q) nt4 := mulmod(nt4, nt4, _q) nt4 := mulmod(_t4, nt4, _q) } function sbox_partial(_t, _q) -> nt { nt := mulmod(_t, _t, _q) nt := mulmod(nt, nt, _q) nt := mulmod(_t, nt, _q) } // round 0 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 1 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 2 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 3 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 4 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 5 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 6 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 7 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 8 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 9 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 10 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 11 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 12 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 13 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 14 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 15 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 16 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 17 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 18 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 19 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 20 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 21 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 22 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 23 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 24 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 25 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 26 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 27 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 28 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 29 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 30 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 31 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 32 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 33 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 34 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 35 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 36 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 37 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 38 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 71447649211767888770311304010816315780740050029903404046389165015534756512) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 39 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 40 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 41 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 42 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 43 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 44 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 45 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 46 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 47 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 48 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 49 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 50 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 51 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 52 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 53 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 54 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 55 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 56 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 57 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) } return t0; } function hash_t5f6p52(HashInputs5 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); require(i.t4 < q, "INVALID_INPUT"); return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q); } // // hash_t7f6p52 // struct HashInputs7 { uint t0; uint t1; uint t2; uint t3; uint t4; uint t5; uint t6; } function mix(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q); o.t0 = addmod(o.t0, mulmod(i.t1, 9067734253445064890734144122526450279189023719890032859456830213166173619761, q), q); o.t0 = addmod(o.t0, mulmod(i.t2, 16378664841697311562845443097199265623838619398287411428110917414833007677155, q), q); o.t0 = addmod(o.t0, mulmod(i.t3, 12968540216479938138647596899147650021419273189336843725176422194136033835172, q), q); o.t0 = addmod(o.t0, mulmod(i.t4, 3636162562566338420490575570584278737093584021456168183289112789616069756675, q), q); o.t0 = addmod(o.t0, mulmod(i.t5, 8949952361235797771659501126471156178804092479420606597426318793013844305422, q), q); o.t0 = addmod(o.t0, mulmod(i.t6, 13586657904816433080148729258697725609063090799921401830545410130405357110367, q), q); o.t1 = mulmod(i.t0, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q); o.t1 = addmod(o.t1, mulmod(i.t1, 2482058150180648511543788012634934806465808146786082148795902594096349483974, q), q); o.t1 = addmod(o.t1, mulmod(i.t2, 16563522740626180338295201738437974404892092704059676533096069531044355099628, q), q); o.t1 = addmod(o.t1, mulmod(i.t3, 10468644849657689537028565510142839489302836569811003546969773105463051947124, q), q); o.t1 = addmod(o.t1, mulmod(i.t4, 3328913364598498171733622353010907641674136720305714432354138807013088636408, q), q); o.t1 = addmod(o.t1, mulmod(i.t5, 8642889650254799419576843603477253661899356105675006557919250564400804756641, q), q); o.t1 = addmod(o.t1, mulmod(i.t6, 14300697791556510113764686242794463641010174685800128469053974698256194076125, q), q); o.t2 = mulmod(i.t0, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q); o.t2 = addmod(o.t2, mulmod(i.t1, 970943815872417895015626519859542525373809485973005165410533315057253476903, q), q); o.t2 = addmod(o.t2, mulmod(i.t2, 19406667490568134101658669326517700199745817783746545889094238643063688871948, q), q); o.t2 = addmod(o.t2, mulmod(i.t3, 17049854690034965250221386317058877242629221002521630573756355118745574274967, q), q); o.t2 = addmod(o.t2, mulmod(i.t4, 4964394613021008685803675656098849539153699842663541444414978877928878266244, q), q); o.t2 = addmod(o.t2, mulmod(i.t5, 15474947305445649466370538888925567099067120578851553103424183520405650587995, q), q); o.t2 = addmod(o.t2, mulmod(i.t6, 1016119095639665978105768933448186152078842964810837543326777554729232767846, q), q); o.t3 = mulmod(i.t0, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q); o.t3 = addmod(o.t3, mulmod(i.t1, 4770370314098695913091200576539533727214143013236894216582648993741910829490, q), q); o.t3 = addmod(o.t3, mulmod(i.t2, 4298564056297802123194408918029088169104276109138370115401819933600955259473, q), q); o.t3 = addmod(o.t3, mulmod(i.t3, 6905514380186323693285869145872115273350947784558995755916362330070690839131, q), q); o.t3 = addmod(o.t3, mulmod(i.t4, 4783343257810358393326889022942241108539824540285247795235499223017138301952, q), q); o.t3 = addmod(o.t3, mulmod(i.t5, 1420772902128122367335354247676760257656541121773854204774788519230732373317, q), q); o.t3 = addmod(o.t3, mulmod(i.t6, 14172871439045259377975734198064051992755748777535789572469924335100006948373, q), q); o.t4 = mulmod(i.t0, 8303849270045876854140023508764676765932043944545416856530551331270859502246, q); o.t4 = addmod(o.t4, mulmod(i.t1, 20218246699596954048529384569730026273241102596326201163062133863539137060414, q), q); o.t4 = addmod(o.t4, mulmod(i.t2, 1712845821388089905746651754894206522004527237615042226559791118162382909269, q), q); o.t4 = addmod(o.t4, mulmod(i.t3, 13001155522144542028910638547179410124467185319212645031214919884423841839406, q), q); o.t4 = addmod(o.t4, mulmod(i.t4, 16037892369576300958623292723740289861626299352695838577330319504984091062115, q), q); o.t4 = addmod(o.t4, mulmod(i.t5, 19189494548480259335554606182055502469831573298885662881571444557262020106898, q), q); o.t4 = addmod(o.t4, mulmod(i.t6, 19032687447778391106390582750185144485341165205399984747451318330476859342654, q), q); o.t5 = mulmod(i.t0, 13272957914179340594010910867091459756043436017766464331915862093201960540910, q); o.t5 = addmod(o.t5, mulmod(i.t1, 9416416589114508529880440146952102328470363729880726115521103179442988482948, q), q); o.t5 = addmod(o.t5, mulmod(i.t2, 8035240799672199706102747147502951589635001418759394863664434079699838251138, q), q); o.t5 = addmod(o.t5, mulmod(i.t3, 21642389080762222565487157652540372010968704000567605990102641816691459811717, q), q); o.t5 = addmod(o.t5, mulmod(i.t4, 20261355950827657195644012399234591122288573679402601053407151083849785332516, q), q); o.t5 = addmod(o.t5, mulmod(i.t5, 14514189384576734449268559374569145463190040567900950075547616936149781403109, q), q); o.t5 = addmod(o.t5, mulmod(i.t6, 19038036134886073991945204537416211699632292792787812530208911676638479944765, q), q); o.t6 = mulmod(i.t0, 15627836782263662543041758927100784213807648787083018234961118439434298020664, q); o.t6 = addmod(o.t6, mulmod(i.t1, 5655785191024506056588710805596292231240948371113351452712848652644610823632, q), q); o.t6 = addmod(o.t6, mulmod(i.t2, 8265264721707292643644260517162050867559314081394556886644673791575065394002, q), q); o.t6 = addmod(o.t6, mulmod(i.t3, 17151144681903609082202835646026478898625761142991787335302962548605510241586, q), q); o.t6 = addmod(o.t6, mulmod(i.t4, 18731644709777529787185361516475509623264209648904603914668024590231177708831, q), q); o.t6 = addmod(o.t6, mulmod(i.t5, 20697789991623248954020701081488146717484139720322034504511115160686216223641, q), q); o.t6 = addmod(o.t6, mulmod(i.t6, 6200020095464686209289974437830528853749866001482481427982839122465470640886, q), q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function ark(HashInputs7 memory i, uint q, uint c) internal pure { HashInputs7 memory o; o.t0 = addmod(i.t0, c, q); o.t1 = addmod(i.t1, c, q); o.t2 = addmod(i.t2, c, q); o.t3 = addmod(i.t3, c, q); o.t4 = addmod(i.t4, c, q); o.t5 = addmod(i.t5, c, q); o.t6 = addmod(i.t6, c, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function sbox_full(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); o.t1 = mulmod(i.t1, i.t1, q); o.t1 = mulmod(o.t1, o.t1, q); o.t1 = mulmod(i.t1, o.t1, q); o.t2 = mulmod(i.t2, i.t2, q); o.t2 = mulmod(o.t2, o.t2, q); o.t2 = mulmod(i.t2, o.t2, q); o.t3 = mulmod(i.t3, i.t3, q); o.t3 = mulmod(o.t3, o.t3, q); o.t3 = mulmod(i.t3, o.t3, q); o.t4 = mulmod(i.t4, i.t4, q); o.t4 = mulmod(o.t4, o.t4, q); o.t4 = mulmod(i.t4, o.t4, q); o.t5 = mulmod(i.t5, i.t5, q); o.t5 = mulmod(o.t5, o.t5, q); o.t5 = mulmod(i.t5, o.t5, q); o.t6 = mulmod(i.t6, i.t6, q); o.t6 = mulmod(o.t6, o.t6, q); o.t6 = mulmod(i.t6, o.t6, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function sbox_partial(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); i.t0 = o.t0; } function hash_t7f6p52(HashInputs7 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); require(i.t4 < q, "INVALID_INPUT"); require(i.t5 < q, "INVALID_INPUT"); require(i.t6 < q, "INVALID_INPUT"); // round 0 ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522); sbox_full(i, q); mix(i, q); // round 1 ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128); sbox_full(i, q); mix(i, q); // round 2 ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509); sbox_full(i, q); mix(i, q); // round 3 ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615); sbox_partial(i, q); mix(i, q); // round 4 ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514); sbox_partial(i, q); mix(i, q); // round 5 ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619); sbox_partial(i, q); mix(i, q); // round 6 ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153); sbox_partial(i, q); mix(i, q); // round 7 ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608); sbox_partial(i, q); mix(i, q); // round 8 ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567); sbox_partial(i, q); mix(i, q); // round 9 ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471); sbox_partial(i, q); mix(i, q); // round 10 ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765); sbox_partial(i, q); mix(i, q); // round 11 ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772); sbox_partial(i, q); mix(i, q); // round 12 ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850); sbox_partial(i, q); mix(i, q); // round 13 ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375); sbox_partial(i, q); mix(i, q); // round 14 ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136); sbox_partial(i, q); mix(i, q); // round 15 ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374); sbox_partial(i, q); mix(i, q); // round 16 ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107); sbox_partial(i, q); mix(i, q); // round 17 ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214); sbox_partial(i, q); mix(i, q); // round 18 ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455); sbox_partial(i, q); mix(i, q); // round 19 ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212); sbox_partial(i, q); mix(i, q); // round 20 ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626); sbox_partial(i, q); mix(i, q); // round 21 ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417); sbox_partial(i, q); mix(i, q); // round 22 ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006); sbox_partial(i, q); mix(i, q); // round 23 ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766); sbox_partial(i, q); mix(i, q); // round 24 ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832); sbox_partial(i, q); mix(i, q); // round 25 ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231); sbox_partial(i, q); mix(i, q); // round 26 ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114); sbox_partial(i, q); mix(i, q); // round 27 ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q); // round 28 ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018); sbox_partial(i, q); mix(i, q); // round 29 ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562); sbox_partial(i, q); mix(i, q); // round 30 ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826); sbox_partial(i, q); mix(i, q); // round 31 ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245); sbox_partial(i, q); mix(i, q); // round 32 ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748); sbox_partial(i, q); mix(i, q); // round 33 ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508); sbox_partial(i, q); mix(i, q); // round 34 ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523); sbox_partial(i, q); mix(i, q); // round 35 ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410); sbox_partial(i, q); mix(i, q); // round 36 ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935); sbox_partial(i, q); mix(i, q); // round 37 ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643); sbox_partial(i, q); mix(i, q); // round 38 ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512); sbox_partial(i, q); mix(i, q); // round 39 ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393); sbox_partial(i, q); mix(i, q); // round 40 ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525); sbox_partial(i, q); mix(i, q); // round 41 ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006); sbox_partial(i, q); mix(i, q); // round 42 ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058); sbox_partial(i, q); mix(i, q); // round 43 ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739); sbox_partial(i, q); mix(i, q); // round 44 ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548); sbox_partial(i, q); mix(i, q); // round 45 ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311); sbox_partial(i, q); mix(i, q); // round 46 ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q); // round 47 ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706); sbox_partial(i, q); mix(i, q); // round 48 ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232); sbox_partial(i, q); mix(i, q); // round 49 ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q); // round 50 ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266); sbox_partial(i, q); mix(i, q); // round 51 ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210); sbox_partial(i, q); mix(i, q); // round 52 ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743); sbox_partial(i, q); mix(i, q); // round 53 ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373); sbox_partial(i, q); mix(i, q); // round 54 ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q); // round 55 ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076); sbox_full(i, q); mix(i, q); // round 56 ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047); sbox_full(i, q); mix(i, q); // round 57 ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544); sbox_full(i, q); mix(i, q); return i.t0; } } // File: contracts/core/impl/libexchange/ExchangeBalances.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeBalances. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeBalances { using MathUint for uint; function verifyAccountBalance( uint merkleRoot, ExchangeData.MerkleProof calldata merkleProof ) public pure { require( isAccountBalanceCorrect(merkleRoot, merkleProof), "INVALID_MERKLE_TREE_DATA" ); } function isAccountBalanceCorrect( uint merkleRoot, ExchangeData.MerkleProof memory merkleProof ) public pure returns (bool) { // Calculate the Merkle root using the Merkle paths provided uint calculatedRoot = getBalancesRoot( merkleProof.balanceLeaf.tokenID, merkleProof.balanceLeaf.balance, merkleProof.balanceLeaf.weightAMM, merkleProof.balanceLeaf.storageRoot, merkleProof.balanceMerkleProof ); calculatedRoot = getAccountInternalsRoot( merkleProof.accountLeaf.accountID, merkleProof.accountLeaf.owner, merkleProof.accountLeaf.pubKeyX, merkleProof.accountLeaf.pubKeyY, merkleProof.accountLeaf.nonce, merkleProof.accountLeaf.feeBipsAMM, calculatedRoot, merkleProof.accountMerkleProof ); // Check against the expected Merkle root return (calculatedRoot == merkleRoot); } function getBalancesRoot( uint16 tokenID, uint balance, uint weightAMM, uint storageRoot, uint[24] memory balanceMerkleProof ) private pure returns (uint) { // Hash the balance leaf uint balanceItem = hashImpl(balance, weightAMM, storageRoot, 0); // Calculate the Merkle root of the balance quad Merkle tree uint _id = tokenID; for (uint depth = 0; depth < 8; depth++) { uint base = depth * 3; if (_id & 3 == 0) { balanceItem = hashImpl( balanceItem, balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceMerkleProof[base + 2] ); } else if (_id & 3 == 1) { balanceItem = hashImpl( balanceMerkleProof[base], balanceItem, balanceMerkleProof[base + 1], balanceMerkleProof[base + 2] ); } else if (_id & 3 == 2) { balanceItem = hashImpl( balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceItem, balanceMerkleProof[base + 2] ); } else if (_id & 3 == 3) { balanceItem = hashImpl( balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceMerkleProof[base + 2], balanceItem ); } _id = _id >> 2; } return balanceItem; } function getAccountInternalsRoot( uint32 accountID, address owner, uint pubKeyX, uint pubKeyY, uint nonce, uint feeBipsAMM, uint balancesRoot, uint[48] memory accountMerkleProof ) private pure returns (uint) { // Hash the account leaf uint accountItem = hashAccountLeaf(uint(owner), pubKeyX, pubKeyY, nonce, feeBipsAMM, balancesRoot); // Calculate the Merkle root of the account quad Merkle tree uint _id = accountID; for (uint depth = 0; depth < 16; depth++) { uint base = depth * 3; if (_id & 3 == 0) { accountItem = hashImpl( accountItem, accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2] ); } else if (_id & 3 == 1) { accountItem = hashImpl( accountMerkleProof[base], accountItem, accountMerkleProof[base + 1], accountMerkleProof[base + 2] ); } else if (_id & 3 == 2) { accountItem = hashImpl( accountMerkleProof[base], accountMerkleProof[base + 1], accountItem, accountMerkleProof[base + 2] ); } else if (_id & 3 == 3) { accountItem = hashImpl( accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2], accountItem ); } _id = _id >> 2; } return accountItem; } function hashAccountLeaf( uint t0, uint t1, uint t2, uint t3, uint t4, uint t5 ) public pure returns (uint) { Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7(t0, t1, t2, t3, t4, t5, 0); return Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); } function hashImpl( uint t0, uint t1, uint t2, uint t3 ) private pure returns (uint) { Poseidon.HashInputs5 memory inputs = Poseidon.HashInputs5(t0, t1, t2, t3, 0); return Poseidon.hash_t5f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); } } // File: contracts/lib/ERC20SafeTransfer.sol // Copyright 2017 Loopring Technology Limited. /// @title ERC20 safe transfer /// @dev see https://github.com/sec-bit/badERC20Fix /// @author Brecht Devos - <[email protected]> library ERC20SafeTransfer { function safeTransferAndVerify( address token, address to, uint value ) internal { safeTransferWithGasLimitAndVerify( token, to, value, gasleft() ); } function safeTransfer( address token, address to, uint value ) internal returns (bool) { return safeTransferWithGasLimit( token, to, value, gasleft() ); } function safeTransferWithGasLimitAndVerify( address token, address to, uint value, uint gasLimit ) internal { require( safeTransferWithGasLimit(token, to, value, gasLimit), "TRANSFER_FAILURE" ); } function safeTransferWithGasLimit( address token, address to, uint value, uint gasLimit ) internal returns (bool) { // A transfer is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb bytes memory callData = abi.encodeWithSelector( bytes4(0xa9059cbb), to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return checkReturnValue(success); } function safeTransferFromAndVerify( address token, address from, address to, uint value ) internal { safeTransferFromWithGasLimitAndVerify( token, from, to, value, gasleft() ); } function safeTransferFrom( address token, address from, address to, uint value ) internal returns (bool) { return safeTransferFromWithGasLimit( token, from, to, value, gasleft() ); } function safeTransferFromWithGasLimitAndVerify( address token, address from, address to, uint value, uint gasLimit ) internal { bool result = safeTransferFromWithGasLimit( token, from, to, value, gasLimit ); require(result, "TRANSFER_FAILURE"); } function safeTransferFromWithGasLimit( address token, address from, address to, uint value, uint gasLimit ) internal returns (bool) { // A transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd bytes memory callData = abi.encodeWithSelector( bytes4(0x23b872dd), from, to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return checkReturnValue(success); } function checkReturnValue( bool success ) internal pure returns (bool) { // A transfer/transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) if (success) { assembly { switch returndatasize() // Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded case 0 { success := 1 } // Standard ERC20: a single boolean value is returned which needs to be true case 32 { returndatacopy(0, 0, 32) success := mload(0) } // None of the above: not successful default { success := 0 } } } return success; } } // File: contracts/core/impl/libexchange/ExchangeTokens.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeTokens. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeTokens { using MathUint for uint; using ERC20SafeTransfer for address; using ExchangeMode for ExchangeData.State; event TokenRegistered( address token, uint16 tokenId ); function getTokenAddress( ExchangeData.State storage S, uint16 tokenID ) public view returns (address) { require(tokenID < S.tokens.length, "INVALID_TOKEN_ID"); return S.tokens[tokenID].token; } function registerToken( ExchangeData.State storage S, address tokenAddress ) public returns (uint16 tokenID) { require(!S.isInWithdrawalMode(), "INVALID_MODE"); require(S.tokenToTokenId[tokenAddress] == 0, "TOKEN_ALREADY_EXIST"); require(S.tokens.length < ExchangeData.MAX_NUM_TOKENS, "TOKEN_REGISTRY_FULL"); // Check if the deposit contract supports the new token if (S.depositContract != IDepositContract(0)) { require( S.depositContract.isTokenSupported(tokenAddress), "UNSUPPORTED_TOKEN" ); } // Assign a tokenID and store the token ExchangeData.Token memory token = ExchangeData.Token( tokenAddress ); tokenID = uint16(S.tokens.length); S.tokens.push(token); S.tokenToTokenId[tokenAddress] = tokenID + 1; emit TokenRegistered(tokenAddress, tokenID); } function getTokenID( ExchangeData.State storage S, address tokenAddress ) internal // inline call view returns (uint16 tokenID) { tokenID = S.tokenToTokenId[tokenAddress]; require(tokenID != 0, "TOKEN_NOT_FOUND"); tokenID = tokenID - 1; } } // File: contracts/core/impl/libexchange/ExchangeWithdrawals.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeWithdrawals. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeWithdrawals { enum WithdrawalCategory { DISTRIBUTION, FROM_MERKLE_TREE, FROM_DEPOSIT_REQUEST, FROM_APPROVED_WITHDRAWAL } using AddressUtil for address; using AddressUtil for address payable; using BytesUtil for bytes; using MathUint for uint; using ExchangeBalances for ExchangeData.State; using ExchangeMode for ExchangeData.State; using ExchangeTokens for ExchangeData.State; event ForcedWithdrawalRequested( address owner, address token, uint32 accountID ); event WithdrawalCompleted( uint8 category, address from, address to, address token, uint amount ); event WithdrawalFailed( uint8 category, address from, address to, address token, uint amount ); function forceWithdraw( ExchangeData.State storage S, address owner, address token, uint32 accountID ) public { require(!S.isInWithdrawalMode(), "INVALID_MODE"); // Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed. require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN"); require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID"); uint16 tokenID = S.getTokenID(token); // A user needs to pay a fixed ETH withdrawal fee, set by the protocol. uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee(); // Check ETH value sent, can be larger than the expected withdraw fee require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE"); // Send surplus of ETH back to the sender uint feeSurplus = msg.value.sub(withdrawalFeeETH); if (feeSurplus > 0) { msg.sender.sendETHAndVerify(feeSurplus, gasleft()); } // There can only be a single forced withdrawal per (account, token) pair. require( S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0, "WITHDRAWAL_ALREADY_PENDING" ); // Store the forced withdrawal request data S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({ owner: owner, timestamp: uint64(block.timestamp) }); // Increment the number of pending forced transactions so we can keep count. S.numPendingForcedTransactions++; emit ForcedWithdrawalRequested( owner, token, accountID ); } // We alow anyone to withdraw these funds for the account owner function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public { require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE"); address owner = merkleProof.accountLeaf.owner; uint32 accountID = merkleProof.accountLeaf.accountID; uint16 tokenID = merkleProof.balanceLeaf.tokenID; uint96 balance = merkleProof.balanceLeaf.balance; // Make sure the funds aren't withdrawn already. require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY"); // Verify that the provided Merkle tree data is valid by using the Merkle proof. ExchangeBalances.verifyAccountBalance( uint(S.merkleRoot), merkleProof ); // Make sure the balance can only be withdrawn once S.withdrawnInWithdrawMode[accountID][tokenID] = true; // Transfer the tokens to the account owner transferTokens( S, uint8(WithdrawalCategory.FROM_MERKLE_TREE), owner, owner, tokenID, balance, new bytes(0), gasleft(), false ); } function withdrawFromDepositRequest( ExchangeData.State storage S, address owner, address token ) public { uint16 tokenID = S.getTokenID(token); ExchangeData.Deposit storage deposit = S.pendingDeposits[owner][tokenID]; require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET"); // Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount; // Reset the deposit request delete S.pendingDeposits[owner][tokenID]; // Transfer the tokens transferTokens( S, uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST), owner, owner, tokenID, amount, new bytes(0), gasleft(), false ); } function withdrawFromApprovedWithdrawals( ExchangeData.State storage S, address[] memory owners, address[] memory tokens ) public { require(owners.length == tokens.length, "INVALID_INPUT_DATA"); for (uint i = 0; i < owners.length; i++) { address owner = owners[i]; uint16 tokenID = S.getTokenID(tokens[i]); uint amount = S.amountWithdrawable[owner][tokenID]; // Make sure this amount can't be withdrawn again delete S.amountWithdrawable[owner][tokenID]; // Transfer the tokens to the owner transferTokens( S, uint8(WithdrawalCategory.FROM_APPROVED_WITHDRAWAL), owner, owner, tokenID, amount, new bytes(0), gasleft(), false ); } } function distributeWithdrawal( ExchangeData.State storage S, address from, address to, uint16 tokenID, uint amount, bytes memory extraData, uint gasLimit ) public { // Try to transfer the tokens bool success = transferTokens( S, uint8(WithdrawalCategory.DISTRIBUTION), from, to, tokenID, amount, extraData, gasLimit, true ); // If the transfer was successful there's nothing left to do. // However, if the transfer failed the tokens are still in the contract and can be // withdrawn later to `to` by anyone by using `withdrawFromApprovedWithdrawal. if (!success) { S.amountWithdrawable[to][tokenID] = S.amountWithdrawable[to][tokenID].add(amount); } } // == Internal and Private Functions == // If allowFailure is true the transfer can fail because of a transfer error or // because the transfer uses more than `gasLimit` gas. The function // will return true when successful, false otherwise. // If allowFailure is false the transfer is guaranteed to succeed using // as much gas as needed, otherwise it throws. The function always returns true. function transferTokens( ExchangeData.State storage S, uint8 category, address from, address to, uint16 tokenID, uint amount, bytes memory extraData, uint gasLimit, bool allowFailure ) private returns (bool success) { // Redirect withdrawals to address(0) to the protocol fee vault if (to == address(0)) { to = S.loopring.protocolFeeVault(); } address token = S.getTokenAddress(tokenID); // Transfer the tokens from the deposit contract to the owner if (gasLimit > 0) { try S.depositContract.withdraw{gas: gasLimit}(from, to, token, amount, extraData) { success = true; } catch { success = false; } } else { success = false; } require(allowFailure || success, "TRANSFER_FAILURE"); if (success) { emit WithdrawalCompleted(category, from, to, token, amount); // Keep track of when the protocol fees were last withdrawn // (only done to make this data easier available). if (from == address(0)) { S.protocolFeeLastWithdrawnTime[token] = block.timestamp; } } else { emit WithdrawalFailed(category, from, to, token, amount); } } } // File: contracts/core/impl/libtransactions/WithdrawTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title WithdrawTransaction /// @author Brecht Devos - <[email protected]> /// @dev The following 4 types of withdrawals are supported: /// - withdrawType = 0: offchain withdrawals with EdDSA signatures /// - withdrawType = 1: offchain withdrawals with ECDSA signatures or onchain appprovals /// - withdrawType = 2: onchain valid forced withdrawals (owner and accountID match), or /// offchain operator-initiated withdrawals for protocol fees or for /// users in shutdown mode /// - withdrawType = 3: onchain invalid forced withdrawals (owner and accountID mismatch) library WithdrawTransaction { using BytesUtil for bytes; using FloatUtil for uint16; using MathUint for uint; using ExchangeMode for ExchangeData.State; using ExchangeSignatures for ExchangeData.State; using ExchangeWithdrawals for ExchangeData.State; bytes32 constant public WITHDRAWAL_TYPEHASH = keccak256( "Withdrawal(address owner,uint32 accountID,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,address to,bytes extraData,uint256 minGas,uint32 validUntil,uint32 storageID)" ); struct Withdrawal { uint withdrawalType; address from; uint32 fromAccountID; uint16 tokenID; uint96 amount; uint16 feeTokenID; uint96 maxFee; uint96 fee; address to; bytes extraData; uint minGas; uint32 validUntil; uint32 storageID; bytes20 onchainDataHash; } // Auxiliary data for each withdrawal struct WithdrawalAuxiliaryData { bool storeRecipient; uint gasLimit; bytes signature; uint minGas; address to; bytes extraData; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { Withdrawal memory withdrawal; readTx(data, offset, withdrawal); WithdrawalAuxiliaryData memory auxData = abi.decode(auxiliaryData, (WithdrawalAuxiliaryData)); // Validate the withdrawal data not directly part of the DA bytes20 onchainDataHash = hashOnchainData( auxData.minGas, auxData.to, auxData.extraData ); // Only the 20 MSB are used, which is still 80-bit of security, which is more // than enough, especially when combined with validUntil. require(withdrawal.onchainDataHash == onchainDataHash, "INVALID_WITHDRAWAL_DATA"); // Fill in withdrawal data missing from DA withdrawal.to = auxData.to; withdrawal.minGas = auxData.minGas; withdrawal.extraData = auxData.extraData; withdrawal.maxFee = auxData.maxFee == 0 ? withdrawal.fee : auxData.maxFee; withdrawal.validUntil = auxData.validUntil; // If the account has an owner, don't allow withdrawing to the zero address // (which will be the protocol fee vault contract). require(withdrawal.from == address(0) || withdrawal.to != address(0), "INVALID_WITHDRAWAL_RECIPIENT"); if (withdrawal.withdrawalType == 0) { // Signature checked offchain, nothing to do } else if (withdrawal.withdrawalType == 1) { // Validate require(ctx.timestamp < withdrawal.validUntil, "WITHDRAWAL_EXPIRED"); require(withdrawal.fee <= withdrawal.maxFee, "WITHDRAWAL_FEE_TOO_HIGH"); // Check appproval onchain // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, withdrawal); // Check onchain authorization S.requireAuthorizedTx(withdrawal.from, auxData.signature, txHash); } else if (withdrawal.withdrawalType == 2 || withdrawal.withdrawalType == 3) { // Forced withdrawals cannot make use of certain features because the // necessary data is not authorized by the account owner. // For protocol fee withdrawals, `owner` and `to` are both address(0). require(withdrawal.from == withdrawal.to, "INVALID_WITHDRAWAL_ADDRESS"); // Forced withdrawal fees are charged when the request is submitted. require(withdrawal.fee == 0, "FEE_NOT_ZERO"); require(withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED"); ExchangeData.ForcedWithdrawal memory forcedWithdrawal = S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID]; if (forcedWithdrawal.timestamp != 0) { if (withdrawal.withdrawalType == 2) { require(withdrawal.from == forcedWithdrawal.owner, "INCONSISENT_OWNER"); } else { //withdrawal.withdrawalType == 3 require(withdrawal.from != forcedWithdrawal.owner, "INCONSISENT_OWNER"); require(withdrawal.amount == 0, "UNAUTHORIZED_WITHDRAWAL"); } // delete the withdrawal request and free a slot delete S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID]; S.numPendingForcedTransactions--; } else { // Allow the owner to submit full withdrawals without authorization // - when in shutdown mode // - to withdraw protocol fees require( withdrawal.fromAccountID == ExchangeData.ACCOUNTID_PROTOCOLFEE || S.isShutdown(), "FULL_WITHDRAWAL_UNAUTHORIZED" ); } } else { revert("INVALID_WITHDRAWAL_TYPE"); } // Check if there is a withdrawal recipient address recipient = S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID]; if (recipient != address(0)) { // Auxiliary data is not supported require (withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED"); // Set the new recipient address withdrawal.to = recipient; // Allow any amount of gas to be used on this withdrawal (which allows the transfer to be skipped) withdrawal.minGas = 0; // Do NOT delete the recipient to prevent replay attack // delete S.withdrawalRecipient[withdrawal.owner][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID]; } else if (auxData.storeRecipient) { // Store the destination address to mark the withdrawal as done require(withdrawal.to != address(0), "INVALID_DESTINATION_ADDRESS"); S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID] = withdrawal.to; } // Validate gas provided require(auxData.gasLimit >= withdrawal.minGas, "OUT_OF_GAS_FOR_WITHDRAWAL"); // Try to transfer the tokens with the provided gas limit S.distributeWithdrawal( withdrawal.from, withdrawal.to, withdrawal.tokenID, withdrawal.amount, withdrawal.extraData, auxData.gasLimit ); } function readTx( bytes memory data, uint offset, Withdrawal memory withdrawal ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.WITHDRAWAL), "INVALID_TX_TYPE"); _offset += 1; // Extract the transfer data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. withdrawal.withdrawalType = data.toUint8Unsafe(_offset); _offset += 1; withdrawal.from = data.toAddressUnsafe(_offset); _offset += 20; withdrawal.fromAccountID = data.toUint32Unsafe(_offset); _offset += 4; withdrawal.tokenID = data.toUint16Unsafe(_offset); _offset += 2; withdrawal.amount = data.toUint96Unsafe(_offset); _offset += 12; withdrawal.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; withdrawal.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; withdrawal.storageID = data.toUint32Unsafe(_offset); _offset += 4; withdrawal.onchainDataHash = data.toBytes20Unsafe(_offset); _offset += 20; } function hashTx( bytes32 DOMAIN_SEPARATOR, Withdrawal memory withdrawal ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( WITHDRAWAL_TYPEHASH, withdrawal.from, withdrawal.fromAccountID, withdrawal.tokenID, withdrawal.amount, withdrawal.feeTokenID, withdrawal.maxFee, withdrawal.to, keccak256(withdrawal.extraData), withdrawal.minGas, withdrawal.validUntil, withdrawal.storageID ) ) ); } function hashOnchainData( uint minGas, address to, bytes memory extraData ) internal pure returns (bytes20) { // Only the 20 MSB are used, which is still 80-bit of security, which is more // than enough, especially when combined with validUntil. return bytes20(keccak256( abi.encodePacked( minGas, to, extraData ) )); } } // File: contracts/core/impl/libexchange/ExchangeBlocks.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeBlocks. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeBlocks { using AddressUtil for address; using AddressUtil for address payable; using BlockReader for bytes; using BytesUtil for bytes; using MathUint for uint; using ExchangeMode for ExchangeData.State; using ExchangeWithdrawals for ExchangeData.State; using SignatureUtil for bytes32; event BlockSubmitted( uint indexed blockIdx, bytes32 merkleRoot, bytes32 publicDataHash ); event ProtocolFeesUpdated( uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); function submitBlocks( ExchangeData.State storage S, ExchangeData.Block[] memory blocks ) public { // Exchange cannot be in withdrawal mode require(!S.isInWithdrawalMode(), "INVALID_MODE"); // Commit the blocks bytes32[] memory publicDataHashes = new bytes32[](blocks.length); for (uint i = 0; i < blocks.length; i++) { // Hash all the public data to a single value which is used as the input for the circuit publicDataHashes[i] = blocks[i].data.fastSHA256(); // Commit the block commitBlock(S, blocks[i], publicDataHashes[i]); } // Verify the blocks - blocks are verified in a batch to save gas. verifyBlocks(S, blocks, publicDataHashes); } // == Internal Functions == function commitBlock( ExchangeData.State storage S, ExchangeData.Block memory _block, bytes32 _publicDataHash ) private { // Read the block header BlockReader.BlockHeader memory header = _block.data.readHeader(); // Validate the exchange require(header.exchange == address(this), "INVALID_EXCHANGE"); // Validate the Merkle roots require(header.merkleRootBefore == S.merkleRoot, "INVALID_MERKLE_ROOT"); require(header.merkleRootAfter != header.merkleRootBefore, "EMPTY_BLOCK_DISABLED"); require(uint(header.merkleRootAfter) < ExchangeData.SNARK_SCALAR_FIELD, "INVALID_MERKLE_ROOT"); // Validate the timestamp require( header.timestamp > block.timestamp - ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS && header.timestamp < block.timestamp + ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS, "INVALID_TIMESTAMP" ); // Validate the protocol fee values require( validateAndSyncProtocolFees(S, header.protocolTakerFeeBips, header.protocolMakerFeeBips), "INVALID_PROTOCOL_FEES" ); // Process conditional transactions processConditionalTransactions( S, _block, header ); // Emit an event uint numBlocks = S.numBlocks; emit BlockSubmitted(numBlocks, header.merkleRootAfter, _publicDataHash); S.merkleRoot = header.merkleRootAfter; if (_block.storeBlockInfoOnchain) { S.blocks[numBlocks] = ExchangeData.BlockInfo( uint32(block.timestamp), bytes28(_publicDataHash) ); } S.numBlocks = numBlocks + 1; } function verifyBlocks( ExchangeData.State storage S, ExchangeData.Block[] memory blocks, bytes32[] memory publicDataHashes ) private view { IBlockVerifier blockVerifier = S.blockVerifier; uint numBlocksVerified = 0; bool[] memory blockVerified = new bool[](blocks.length); ExchangeData.Block memory firstBlock; uint[] memory batch = new uint[](blocks.length); while (numBlocksVerified < blocks.length) { // Find all blocks of the same type uint batchLength = 0; for (uint i = 0; i < blocks.length; i++) { if (blockVerified[i] == false) { if (batchLength == 0) { firstBlock = blocks[i]; batch[batchLength++] = i; } else { ExchangeData.Block memory _block = blocks[i]; if (_block.blockType == firstBlock.blockType && _block.blockSize == firstBlock.blockSize && _block.blockVersion == firstBlock.blockVersion) { batch[batchLength++] = i; } } } } // Prepare the data for batch verification uint[] memory publicInputs = new uint[](batchLength); uint[] memory proofs = new uint[](batchLength * 8); for (uint i = 0; i < batchLength; i++) { uint blockIdx = batch[i]; // Mark the block as verified blockVerified[blockIdx] = true; // Strip the 3 least significant bits of the public data hash // so we don't have any overflow in the snark field publicInputs[i] = uint(publicDataHashes[blockIdx]) >> 3; // Copy proof ExchangeData.Block memory _block = blocks[blockIdx]; for (uint j = 0; j < 8; j++) { proofs[i*8 + j] = _block.proof[j]; } } // Verify the proofs require( blockVerifier.verifyProofs( uint8(firstBlock.blockType), firstBlock.blockSize, firstBlock.blockVersion, publicInputs, proofs ), "INVALID_PROOF" ); numBlocksVerified += batchLength; } } function processConditionalTransactions( ExchangeData.State storage S, ExchangeData.Block memory _block, BlockReader.BlockHeader memory header ) private { if (header.numConditionalTransactions > 0) { // Cache the domain seperator to save on SLOADs each time it is accessed. ExchangeData.BlockContext memory ctx = ExchangeData.BlockContext({ DOMAIN_SEPARATOR: S.DOMAIN_SEPARATOR, timestamp: header.timestamp }); ExchangeData.AuxiliaryData[] memory block_auxiliaryData; bytes memory blockAuxData = _block.auxiliaryData; assembly { block_auxiliaryData := add(blockAuxData, 64) } require( block_auxiliaryData.length == header.numConditionalTransactions, "AUXILIARYDATA_INVALID_LENGTH" ); // Run over all conditional transactions uint minTxIndex = 0; bytes memory txData = new bytes(ExchangeData.TX_DATA_AVAILABILITY_SIZE); for (uint i = 0; i < block_auxiliaryData.length; i++) { // Load the data from auxiliaryData, which is still encoded as calldata uint txIndex; bool approved; bytes memory auxData; assembly { // Offset to block_auxiliaryData[i] let auxOffset := mload(add(block_auxiliaryData, add(32, mul(32, i)))) // Load `txIndex` (pos 0) and `approved` (pos 1) in block_auxiliaryData[i] txIndex := mload(add(add(32, block_auxiliaryData), auxOffset)) approved := mload(add(add(64, block_auxiliaryData), auxOffset)) // Load `data` (pos 2) let auxDataOffset := mload(add(add(96, block_auxiliaryData), auxOffset)) auxData := add(add(32, block_auxiliaryData), add(auxOffset, auxDataOffset)) } // Each conditional transaction needs to be processed from left to right require(txIndex >= minTxIndex, "AUXILIARYDATA_INVALID_ORDER"); minTxIndex = txIndex + 1; if (approved) { continue; } // Get the transaction data _block.data.readTransactionData(txIndex, _block.blockSize, txData); // Process the transaction ExchangeData.TransactionType txType = ExchangeData.TransactionType( txData.toUint8(0) ); uint txDataOffset = 0; if (txType == ExchangeData.TransactionType.DEPOSIT) { DepositTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.WITHDRAWAL) { WithdrawTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.TRANSFER) { TransferTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.ACCOUNT_UPDATE) { AccountUpdateTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.AMM_UPDATE) { AmmUpdateTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else { // ExchangeData.TransactionType.NOOP, // ExchangeData.TransactionType.SPOT_TRADE and // ExchangeData.TransactionType.SIGNATURE_VERIFICATION // are not supported revert("UNSUPPORTED_TX_TYPE"); } } } } function validateAndSyncProtocolFees( ExchangeData.State storage S, uint8 takerFeeBips, uint8 makerFeeBips ) private returns (bool) { ExchangeData.ProtocolFeeData memory data = S.protocolFeeData; if (block.timestamp > data.syncedAt + ExchangeData.MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED) { // Store the current protocol fees in the previous protocol fees data.previousTakerFeeBips = data.takerFeeBips; data.previousMakerFeeBips = data.makerFeeBips; // Get the latest protocol fees for this exchange (data.takerFeeBips, data.makerFeeBips) = S.loopring.getProtocolFeeValues(); data.syncedAt = uint32(block.timestamp); if (data.takerFeeBips != data.previousTakerFeeBips || data.makerFeeBips != data.previousMakerFeeBips) { emit ProtocolFeesUpdated( data.takerFeeBips, data.makerFeeBips, data.previousTakerFeeBips, data.previousMakerFeeBips ); } // Update the data in storage S.protocolFeeData = data; } // The given fee values are valid if they are the current or previous protocol fee values return (takerFeeBips == data.takerFeeBips && makerFeeBips == data.makerFeeBips) || (takerFeeBips == data.previousTakerFeeBips && makerFeeBips == data.previousMakerFeeBips); } }
Check that this is a conditional transfer Extract the transfer data We don't use abi.decode for this because of the large amount of zero-padding bytes the circuit would also have to hash.
function readTx( bytes memory data, uint offset, Transfer memory transfer ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.TRANSFER), "INVALID_TX_TYPE"); _offset += 1; require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA"); _offset += 1; transfer.fromAccountID = data.toUint32Unsafe(_offset); _offset += 4; transfer.toAccountID = data.toUint32Unsafe(_offset); _offset += 4; transfer.tokenID = data.toUint16Unsafe(_offset); _offset += 2; transfer.amount = data.toUint24Unsafe(_offset).decodeFloat24(); _offset += 3; transfer.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; transfer.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; transfer.storageID = data.toUint32Unsafe(_offset); _offset += 4; transfer.to = data.toAddressUnsafe(_offset); _offset += 20; transfer.from = data.toAddressUnsafe(_offset); _offset += 20; }
334,321
// SPDX-License-Identifier: MIT pragma solidity >=0.8.5 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./CharlieToken.sol"; contract Wrapper is Ownable { CharlieToken private outputToken; constructor(address outputTokenAddress) { outputToken = CharlieToken(outputTokenAddress); } /** * Convert an amount of input token_ to an equivalent amount of the output token * * @param token_ address of token to swap * @param amount amount of token to swap/receive */ function swap(address token_, uint256 amount) external { IERC20 inputToken = IERC20(token_); address currentAddress = address(this); require(inputToken.allowance(msg.sender, currentAddress) >= amount, "Wrapper: Insufficient Allowance."); // Transfer A || B token from sender to wrapper inputToken.transferFrom(msg.sender, currentAddress, amount); // Mint the give amount of C token outputToken.mintForWrapper(amount); // Transfer C token to sender outputToken.transfer(msg.sender, amount); } /** * Convert an amount of the output token to an equivalent amount of input token_ * * @param token_ address of token to receive * @param amount amount of token to swap/receive */ function unswap(address token_, uint256 amount) external { IERC20 inputToken = IERC20(token_); address currentAddress = address(this); require(outputToken.allowance(msg.sender, currentAddress) >= amount, "Wrapper: Insufficient Allowance."); require(inputToken.balanceOf(currentAddress) >= amount, "Wrapper: Insufficient Balance."); // Transfer C token from sender to wrapper outputToken.transferFrom(msg.sender, currentAddress, amount); // Burn the given amount of C token outputToken.burnForWrapper(amount); // Transfer A || B token to sender inputToken.transfer(msg.sender, amount); } /** * Transfer input token to the owner, only way to take the balance for the owner * * @param token_ address of token to transfer * @param amount amount of token */ function transfer(address token_, uint256 amount) external onlyOwner { IERC20 inputToken = IERC20(token_); address currentAddress = address(this); require(inputToken.balanceOf(currentAddress) > amount, "Wrapper: Insufficient Balance."); inputToken.transfer(msg.sender, amount); } }
Convert an amount of the output token to an equivalent amount of input token_ token_ address of token to receive amount amount of token to swap/receive/ Transfer C token from sender to wrapper Burn the given amount of C token Transfer A || B token to sender
function unswap(address token_, uint256 amount) external { IERC20 inputToken = IERC20(token_); address currentAddress = address(this); require(outputToken.allowance(msg.sender, currentAddress) >= amount, "Wrapper: Insufficient Allowance."); require(inputToken.balanceOf(currentAddress) >= amount, "Wrapper: Insufficient Balance."); outputToken.transferFrom(msg.sender, currentAddress, amount); outputToken.burnForWrapper(amount); inputToken.transfer(msg.sender, amount); }
2,495,145
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./TellorStaking.sol"; import "./interfaces/IController.sol"; import "./Transition.sol"; import "./Getters.sol"; /** @author Tellor Inc. @title Controller @dev This is the Controller contract which defines the functionality for * changing contract addresses, as well as minting and migrating tokens */ contract Controller is TellorStaking, Transition, Getters { // Events event NewContractAddress(address _newContract, string _contractName); // Functions /** * @dev Saves new Tellor contract addresses. Available to Transition init function after fork vote * @param _governance is the address of the Governance contract * @param _oracle is the address of the Oracle contract * @param _treasury is the address of the Treasury contract */ constructor( address _governance, address _oracle, address _treasury ) Transition(_governance, _oracle, _treasury) {} /** * @dev Changes Controller contract to a new address * Note: this function is only callable by the Governance contract. * @param _newController is the address of the new Controller contract */ function changeControllerContract(address _newController) external { require( msg.sender == addresses[_GOVERNANCE_CONTRACT], "Only the Governance contract can change the Controller contract address" ); require(_isValid(_newController)); addresses[_TELLOR_CONTRACT] = _newController; //name _TELLOR_CONTRACT is hardcoded in assembly { sstore(_EIP_SLOT, _newController) } emit NewContractAddress(_newController, "Controller"); } /** * @dev Changes Governance contract to a new address * Note: this function is only callable by the Governance contract. * @param _newGovernance is the address of the new Governance contract */ function changeGovernanceContract(address _newGovernance) external { require( msg.sender == addresses[_GOVERNANCE_CONTRACT], "Only the Governance contract can change the Governance contract address" ); require(_isValid(_newGovernance)); addresses[_GOVERNANCE_CONTRACT] = _newGovernance; emit NewContractAddress(_newGovernance, "Governance"); } /** * @dev Changes Oracle contract to a new address * Note: this function is only callable by the Governance contract. * @param _newOracle is the address of the new Oracle contract */ function changeOracleContract(address _newOracle) external { require( msg.sender == addresses[_GOVERNANCE_CONTRACT], "Only the Governance contract can change the Oracle contract address" ); require(_isValid(_newOracle)); addresses[_ORACLE_CONTRACT] = _newOracle; emit NewContractAddress(_newOracle, "Oracle"); } /** * @dev Changes Treasury contract to a new address * Note: this function is only callable by the Governance contract. * @param _newTreasury is the address of the new Treasury contract */ function changeTreasuryContract(address _newTreasury) external { require( msg.sender == addresses[_GOVERNANCE_CONTRACT], "Only the Governance contract can change the Treasury contract address" ); require(_isValid(_newTreasury)); addresses[_TREASURY_CONTRACT] = _newTreasury; emit NewContractAddress(_newTreasury, "Treasury"); } /** * @dev Changes a uint for a specific target index * Note: this function is only callable by the Governance contract. * @param _target is the index of the uint to change * @param _amount is the amount to change the given uint to */ function changeUint(bytes32 _target, uint256 _amount) external { require( msg.sender == addresses[_GOVERNANCE_CONTRACT], "Only the Governance contract can change the uint" ); uints[_target] = _amount; } /** * @dev Mints tokens of the sender from the old contract to the sender */ function migrate() external { require(!migrated[msg.sender], "Already migrated"); _doMint( msg.sender, IController(addresses[_OLD_TELLOR]).balanceOf(msg.sender) ); migrated[msg.sender] = true; } /** * @dev Mints TRB to a given receiver address * @param _receiver is the address that will receive the minted tokens * @param _amount is the amount of tokens that will be minted to the _receiver address */ function mint(address _receiver, uint256 _amount) external { require( msg.sender == addresses[_GOVERNANCE_CONTRACT] || msg.sender == addresses[_TREASURY_CONTRACT] || msg.sender == TELLOR_ADDRESS, "Only governance, treasury, or master can mint tokens" ); _doMint(_receiver, _amount); } /** * @dev Used during the upgrade process to verify valid Tellor Contracts */ function verify() external pure returns (uint256) { return 9999; } /** * @dev Used during the upgrade process to verify valid Tellor Contracts and ensure * they have the right signature * @param _contract is the address of the Tellor contract to verify * @return bool of whether or not the address is a valid Tellor contract */ function _isValid(address _contract) internal returns (bool) { (bool _success, bytes memory _data) = address(_contract).call( abi.encodeWithSelector(0xfc735e99, "") // verify() signature ); require( _success && abi.decode(_data, (uint256)) > 9000, // An arbitrary number to ensure that the contract is valid "New contract is invalid" ); return true; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./Token.sol"; import "./interfaces/IGovernance.sol"; /** @author Tellor Inc. @title TellorStaking @dev This is the TellorStaking contract which defines the functionality for * updating staking statuses for reporters, including depositing and withdrawing * stakes. */ contract TellorStaking is Token { // Events event NewStaker(address _staker); event StakeWithdrawRequested(address _staker); event StakeWithdrawn(address _staker); // Functions /** * @dev Changes staking status of a reporter * Note: this function is only callable by the Governance contract. * @param _reporter is the address of the reporter to change staking status for * @param _status is the new status of the reporter */ function changeStakingStatus(address _reporter, uint256 _status) external { require( IGovernance(addresses[_GOVERNANCE_CONTRACT]) .isApprovedGovernanceContract(msg.sender), "Only approved governance contract can change staking status" ); StakeInfo storage stakes = stakerDetails[_reporter]; stakes.currentStatus = _status; } /** * @dev Allows a reporter to submit stake */ function depositStake() external { // Ensure staker has enough balance to stake require( balances[msg.sender][balances[msg.sender].length - 1].value >= uints[_STAKE_AMOUNT], "Balance is lower than stake amount" ); // Ensure staker is currently either not staked or locked for withdraw. // Note that slashed reporters cannot stake again from a slashed address. require( stakerDetails[msg.sender].currentStatus == 0 || stakerDetails[msg.sender].currentStatus == 2, "Reporter is in the wrong state" ); // Increment number of stakers, create new staker, and update dispute fee uints[_STAKE_COUNT] += 1; stakerDetails[msg.sender] = StakeInfo({ currentStatus: 1, startDate: block.timestamp // This resets their stake start date to now }); emit NewStaker(msg.sender); IGovernance(addresses[_GOVERNANCE_CONTRACT]).updateMinDisputeFee(); } /** * @dev Allows a reporter to request to withdraw their stake */ function requestStakingWithdraw() external { // Ensures reporter is already staked StakeInfo storage stakes = stakerDetails[msg.sender]; require(stakes.currentStatus == 1, "Reporter is not staked"); // Change status to reflect withdraw request and updates start date for staking stakes.currentStatus = 2; stakes.startDate = block.timestamp; // Update number of stakers and dispute fee uints[_STAKE_COUNT] -= 1; IGovernance(addresses[_GOVERNANCE_CONTRACT]).updateMinDisputeFee(); emit StakeWithdrawRequested(msg.sender); } /** * @dev Slashes a reporter and transfers their stake amount to their disputer * Note: this function is only callable by the Governance contract. * @param _reporter is the address of the reporter being slashed * @param _disputer is the address of the disputer receiving the reporter's stake */ function slashReporter(address _reporter, address _disputer) external { require( IGovernance(addresses[_GOVERNANCE_CONTRACT]) .isApprovedGovernanceContract(msg.sender), "Only approved governance contract can slash reporter" ); stakerDetails[_reporter].currentStatus = 5; // Change status of reporter to slashed // Transfer stake amount of reporter has a balance bigger than the stake amount if (balanceOf(_reporter) >= uints[_STAKE_AMOUNT]) { _doTransfer(_reporter, _disputer, uints[_STAKE_AMOUNT]); } // Else, transfer all of the reporter's balance else if (balanceOf(_reporter) > 0) { _doTransfer(_reporter, _disputer, balanceOf(_reporter)); } } /** * @dev Withdraws a reporter's stake */ function withdrawStake() external { StakeInfo storage _s = stakerDetails[msg.sender]; // Ensure reporter is locked and that enough time has passed require(block.timestamp - _s.startDate >= 7 days, "7 days didn't pass"); require(_s.currentStatus == 2, "Reporter not locked for withdrawal"); _s.currentStatus = 0; // Updates status to withdrawn emit StakeWithdrawn(msg.sender); } /**GETTERS**/ /** * @dev Allows users to retrieve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256) { return ( stakerDetails[_staker].currentStatus, stakerDetails[_staker].startDate ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IController{ function addresses(bytes32) external returns(address); function uints(bytes32) external returns(uint256); function burn(uint256 _amount) external; function changeDeity(address _newDeity) external; function changeOwner(address _newOwner) external; function changeTellorContract(address _tContract) external; function changeControllerContract(address _newController) external; function changeGovernanceContract(address _newGovernance) external; function changeOracleContract(address _newOracle) external; function changeTreasuryContract(address _newTreasury) external; function changeUint(bytes32 _target, uint256 _amount) external; function migrate() external; function mint(address _reciever, uint256 _amount) external; function init() external; function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); function getAddressVars(bytes32 _data) external view returns (address); function getUintVar(bytes32 _data) external view returns (uint256); function totalSupply() external view returns (uint256); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function allowance(address _user, address _spender) external view returns (uint256); function allowedToTrade(address _user, uint256 _amount) external view returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function approveAndTransferFrom(address _from, address _to, uint256 _amount) external returns(bool); function balanceOf(address _user) external view returns (uint256); function balanceOfAt(address _user, uint256 _blockNumber)external view returns (uint256); function transfer(address _to, uint256 _amount)external returns (bool success); function transferFrom(address _from,address _to,uint256 _amount) external returns (bool success) ; function depositStake() external; function requestStakingWithdraw() external; function withdrawStake() external; function changeStakingStatus(address _reporter, uint _status) external; function slashReporter(address _reporter, address _disputer) external; function getStakerInfo(address _staker) external view returns (uint256, uint256); function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); function getNewCurrentVariables()external view returns (bytes32 _c,uint256[5] memory _r,uint256 _d,uint256 _t); //in order to call fallback function function beginDispute(uint256 _requestId, uint256 _timestamp,uint256 _minerIndex) external; function unlockDisputeFee(uint256 _disputeId) external; function vote(uint256 _disputeId, bool _supportsDispute) external; function tallyVotes(uint256 _disputeId) external; //test functions function tipQuery(uint,uint,bytes memory) external; function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./tellor3/TellorStorage.sol"; import "./TellorVars.sol"; import "./interfaces/IOracle.sol"; import "./interfaces/IController.sol"; /** @author Tellor Inc. @title Transition * @dev The Transition contract links to the Oracle contract and * allows parties (like Liquity) to continue to use the master * address to access values. All parties should be reading values * through this address */ contract Transition is TellorStorage, TellorVars { // Functions /** * @dev Saves new Tellor contract addresses. Available to init function after fork vote * @param _governance is the address of the Governance contract * @param _oracle is the address of the Oracle contract * @param _treasury is the address of the Treasury contract */ constructor( address _governance, address _oracle, address _treasury ) { require(_governance != address(0), "must set governance address"); addresses[_GOVERNANCE_CONTRACT] = _governance; addresses[_ORACLE_CONTRACT] = _oracle; addresses[_TREASURY_CONTRACT] = _treasury; } /** * @dev Runs once Tellor is migrated over. Changes the underlying storage. */ function init() external { require( addresses[_GOVERNANCE_CONTRACT] == address(0), "Only good once" ); // Set state amount, switch time, and minimum dispute fee uints[_STAKE_AMOUNT] = 100e18; uints[_SWITCH_TIME] = block.timestamp; uints[_MINIMUM_DISPUTE_FEE] = 10e18; // Define contract addresses Transition _controller = Transition(addresses[_TELLOR_CONTRACT]); addresses[_GOVERNANCE_CONTRACT] = _controller.addresses( _GOVERNANCE_CONTRACT ); addresses[_ORACLE_CONTRACT] = _controller.addresses(_ORACLE_CONTRACT); addresses[_TREASURY_CONTRACT] = _controller.addresses( _TREASURY_CONTRACT ); // Mint to oracle, parachute, and team operating grant contracts IController(TELLOR_ADDRESS).mint( addresses[_ORACLE_CONTRACT], 105120e18 ); IController(TELLOR_ADDRESS).mint( 0xAa304E98f47D4a6a421F3B1cC12581511dD69C55, 105120e18 ); IController(TELLOR_ADDRESS).mint( 0x83eB2094072f6eD9F57d3F19f54820ee0BaE6084, 18201e18 ); } //Getters /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8) { return 18; } /** * @dev Allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * @return address of the requested variable */ function getAddressVars(bytes32 _data) external view returns (address) { return addresses[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * bool executed where true if it has been voted on * bool disputeVotePassed * bool isPropFork true if the dispute is a proposed fork * address of reportedMiner * address of reportingParty * address of proposedForkAddress * uint256 of requestId * uint256 of timestamp * uint256 of value * uint256 of minExecutionDate * uint256 of numberOfVotes * uint256 of blocknumber * uint256 of minerSlot * uint256 of quorum * uint256 of fee * int256 count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ) { Dispute storage disp = disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty, disp.proposedForkAddress, [ disp.disputeUintVars[_REQUEST_ID], disp.disputeUintVars[_TIMESTAMP], disp.disputeUintVars[_VALUE], disp.disputeUintVars[_MIN_EXECUTION_DATE], disp.disputeUintVars[_NUM_OF_VOTES], disp.disputeUintVars[_BLOCK_NUMBER], disp.disputeUintVars[_MINER_SLOT], disp.disputeUintVars[keccak256("quorum")], disp.disputeUintVars[_FEE] ], disp.tally ); } /** * @dev Gets id if a given hash has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId,_timestamp)); * @return uint256 disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256) { return disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint256 value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256) { return disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Returns the latest value for a specific request ID. * @param _requestId the requestId to look up * @return uint256 of the value of the latest value of the request ID * @return bool of whether or not the value was successfully retrieved */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool) { // Try the new contract first uint256 _timeCount = IOracle(addresses[_ORACLE_CONTRACT]) .getTimestampCountById(bytes32(_requestId)); if (_timeCount != 0) { // If timestamps for the ID exist, there is value, so return the value return ( retrieveData( _requestId, IOracle(addresses[_ORACLE_CONTRACT]) .getReportTimestampByIndex( bytes32(_requestId), _timeCount - 1 ) ), true ); } else { // Else, look at old value + timestamps since mining has not started Request storage _request = requestDetails[_requestId]; if (_request.requestTimestamps.length != 0) { return ( retrieveData( _requestId, _request.requestTimestamps[ _request.requestTimestamps.length - 1 ] ), true ); } else { return (0, false); } } } /** * @dev Function is solely for the parachute contract */ function getNewCurrentVariables() external view returns ( bytes32 _c, uint256[5] memory _r, uint256 _diff, uint256 _tip ) { _r = [uint256(1), uint256(1), uint256(1), uint256(1), uint256(1)]; _diff = 0; _tip = 0; _c = keccak256( abi.encode( IOracle(addresses[_ORACLE_CONTRACT]).getTimeOfLastNewValue() ) ); } /** * @dev Counts the number of values that have been submitted for the request. * @param _requestId the requestId to look up * @return uint256 count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256) { // Defaults to new one, but will give old value if new mining has not started uint256 _val = IOracle(addresses[_ORACLE_CONTRACT]) .getTimestampCountById(bytes32(_requestId)); if (_val > 0) { return _val; } else { return requestDetails[_requestId].requestTimestamps.length; } } /** * @dev Gets the timestamp for the value based on their index * @param _requestId is the requestId to look up * @param _index is the value index to look up * @return uint256 timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestId, uint256 _index) external view returns (uint256) { // Try new contract first, but give old timestamp if new mining has not started try IOracle(addresses[_ORACLE_CONTRACT]).getReportTimestampByIndex( bytes32(_requestId), _index ) returns (uint256 _val) { return _val; } catch { return requestDetails[_requestId].requestTimestamps[_index]; } } /** * @dev Getter for the variables saved under the TellorStorageStruct uints variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") * where variable_name is the variables/strings used to save the data in the mapping. * The variables names in the TellorVariables contract * @return uint256 of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256) { return uints[_data]; } /** * @dev Getter for if the party is migrated * @param _addy address of party * @return bool if the party is migrated */ function isMigrated(address _addy) external view returns (bool) { return migrated[_addy]; } /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Retrieve value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retrieve data/value from * @return uint256 value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) public view returns (uint256) { if (_timestamp < uints[_SWITCH_TIME]) { return requestDetails[_requestId].finalValues[_timestamp]; } return _sliceUint( IOracle(addresses[_ORACLE_CONTRACT]).getValueByTimestamp( bytes32(_requestId), _timestamp ) ); } /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory) { return "TRB"; } /** * @dev Getter for the total_supply of tokens * @return uint256 total supply */ function totalSupply() external view returns (uint256) { return uints[_TOTAL_SUPPLY]; } /** * @dev Allows Tellor X to fallback to the old Tellor if there are current open disputes * (or disputes on old Tellor values) */ fallback() external { address _addr = 0x2754da26f634E04b26c4deCD27b3eb144Cf40582; // Main Tellor address (Harcode this in?) // Obtain function header from msg.data bytes4 _function; for (uint256 i = 0; i < 4; i++) { _function |= bytes4(msg.data[i] & 0xFF) >> (i * 8); } // Ensure that the function is allowed and related to disputes, voting, and dispute fees require( _function == bytes4( bytes32(keccak256("beginDispute(uint256,uint256,uint256)")) ) || _function == bytes4(bytes32(keccak256("vote(uint256,bool)"))) || _function == bytes4(bytes32(keccak256("tallyVotes(uint256)"))) || _function == bytes4(bytes32(keccak256("unlockDisputeFee(uint256)"))), "function should be allowed" ); //should autolock out after a week (no disputes can begin past a week) // Calls the function in msg.data from main Tellor address (bool _result, ) = _addr.delegatecall(msg.data); assembly { returndatacopy(0, 0, returndatasize()) switch _result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } // Internal /** * @dev Utilized to help slice a bytes variable into a uint * @param _b is the bytes variable to be sliced * @return _x of the sliced uint256 */ function _sliceUint(bytes memory _b) public pure returns (uint256 _x) { uint256 _number = 0; for (uint256 _i = 0; _i < _b.length; _i++) { _number = _number * 2**8; _number = _number + uint8(_b[_i]); } return _number; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./tellor3/TellorStorage.sol"; import "./TellorVars.sol"; import "./interfaces/IOracle.sol"; /** @author Tellor Inc. @title Getters * @dev The Getters contract links to the Oracle contract and * allows parties to continue to use the master * address to access bytes values. All parties should be reading values * through this address */ contract Getters is TellorStorage, TellorVars { // Functions /** * @dev Counts the number of values that have been submitted for the request. * @param _queryId the id to look up * @return uint256 count of the number of values received for the id */ function getNewValueCountbyQueryId(bytes32 _queryId) public view returns (uint256) { return ( IOracle(addresses[_ORACLE_CONTRACT]).getTimestampCountById(_queryId) ); } /** * @dev Gets the timestamp for the value based on their index * @param _queryId is the id to look up * @param _index is the value index to look up * @return uint256 timestamp */ function getTimestampbyQueryIdandIndex(bytes32 _queryId, uint256 _index) public view returns (uint256) { return ( IOracle(addresses[_ORACLE_CONTRACT]).getReportTimestampByIndex( _queryId, _index ) ); } /** * @dev Retrieve value from oracle based on timestamp * @param _queryId being requested * @param _timestamp to retrieve data/value from * @return bytes value for timestamp submitted */ function retrieveData(bytes32 _queryId, uint256 _timestamp) public view returns (bytes memory) { return ( IOracle(addresses[_ORACLE_CONTRACT]).getValueByTimestamp( _queryId, _timestamp ) ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./tellor3/TellorStorage.sol"; import "./TellorVars.sol"; import "./interfaces/IGovernance.sol"; /** @author Tellor Inc. @title Token @dev Contains the methods related to transfers and ERC20, its storage * and hashes of tellor variables that are used to save gas on transactions. */ contract Token is TellorStorage, TellorVars { // Events event Approval( address indexed _owner, address indexed _spender, uint256 _value ); // ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); // ERC20 Transfer Event // Functions /** * @dev Getter function for remaining spender balance * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return uint256 Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256) { return _allowances[_user][_spender]; } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return bool true if they are allowed to spend the amount being checked */ function allowedToTrade(address _user, uint256 _amount) public view returns (bool) { if ( stakerDetails[_user].currentStatus != 0 && stakerDetails[_user].currentStatus < 5 ) { // Subtracts the stakeAmount from balance if the _user is staked return (balanceOf(_user) - uints[_STAKE_AMOUNT] >= _amount); } return (balanceOf(_user) >= _amount); // Else, check if balance is greater than amount they want to spend } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return bool true if spender approved successfully */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "ERC20: approve to the zero address"); _allowances[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev This function approves a transfer of _amount tokens from _from to _to * @param _from is the address the tokens will be transferred from * @param _to is the address the tokens will be transferred to * @param _amount is the number of tokens to transfer * @return bool true if spender approved successfully */ function approveAndTransferFrom( address _from, address _to, uint256 _amount ) external returns (bool) { require( (IGovernance(addresses[_GOVERNANCE_CONTRACT]) .isApprovedGovernanceContract(msg.sender) || msg.sender == addresses[_TREASURY_CONTRACT] || msg.sender == addresses[_ORACLE_CONTRACT]), "Only the Governance, Treasury, or Oracle Contract can approve and transfer tokens" ); _doTransfer(_from, _to, _amount); return true; } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return uint256 Returns the balance associated with the passed in _user */ function balanceOf(address _user) public view returns (uint256) { return balanceOfAt(_user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return uint256 The balance at _blockNumber specified */ function balanceOfAt(address _user, uint256 _blockNumber) public view returns (uint256) { TellorStorage.Checkpoint[] storage checkpoints = balances[_user]; if ( checkpoints.length == 0 || checkpoints[0].fromBlock > _blockNumber ) { return 0; } else { if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; // Binary search of the value in the array uint256 _min = 0; uint256 _max = checkpoints.length - 2; while (_max > _min) { uint256 _mid = (_max + _min + 1) / 2; if (checkpoints[_mid].fromBlock == _blockNumber) { return checkpoints[_mid].value; } else if (checkpoints[_mid].fromBlock < _blockNumber) { _min = _mid; } else { _max = _mid - 1; } } return checkpoints[_min].value; } } /** * @dev Burns an amount of tokens * @param _amount is the amount of tokens to burn */ function burn(uint256 _amount) external { _doBurn(msg.sender, _amount); } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return success whether the transfer was successful */ function transfer(address _to, uint256 _amount) external returns (bool success) { _doTransfer(msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return success whether the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool success) { require( _allowances[_from][msg.sender] >= _amount, "Allowance is wrong" ); _allowances[_from][msg.sender] -= _amount; _doTransfer(_from, _to, _amount); return true; } // Internal /** * @dev Helps burn TRB Tokens * @param _from is the address to burn or remove TRB amount * @param _amount is the amount of TRB to burn */ function _doBurn(address _from, uint256 _amount) internal { // Ensure that amount of balance are valid if (_amount == 0) return; require( allowedToTrade(_from, _amount), "Should have sufficient balance to trade" ); uint128 _previousBalance = uint128(balanceOf(_from)); uint128 _sizedAmount = uint128(_amount); // Update total supply and balance of _from _updateBalanceAtNow(_from, _previousBalance - _sizedAmount); uints[_TOTAL_SUPPLY] -= _amount; } /** * @dev Helps mint new TRB * @param _to is the address to send minted amount to * @param _amount is the amount of TRB to send */ function _doMint(address _to, uint256 _amount) internal { // Ensure to address and mint amount are valid require(_amount != 0, "Tried to mint non-positive amount"); require(_to != address(0), "Receiver is 0 address"); uint128 _previousBalance = uint128(balanceOf(_to)); uint128 _sizedAmount = uint128(_amount); // Update total supply and balance of _to address uints[_TOTAL_SUPPLY] += _amount; _updateBalanceAtNow(_to, _previousBalance + _sizedAmount); emit Transfer(address(0), _to, _amount); } /** * @dev Completes transfers by updating the balances on the current block number * and ensuring the amount does not contain tokens staked for reporting * @param _from address to transfer from * @param _to address to transfer to * @param _amount to transfer */ function _doTransfer( address _from, address _to, uint256 _amount ) internal { // Ensure user has a correct balance and to address require(_amount != 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); require( allowedToTrade(_from, _amount), "Should have sufficient balance to trade" ); // Update balance of _from address uint128 _previousBalance = uint128(balanceOf(_from)); uint128 _sizedAmount = uint128(_amount); _updateBalanceAtNow(_from, _previousBalance - _sizedAmount); // Update balance of _to address _previousBalance = uint128(balanceOf(_to)); _updateBalanceAtNow(_to, _previousBalance + _sizedAmount); emit Transfer(_from, _to, _amount); } /** * @dev Updates balance checkpoint for from and to on the current block number via doTransfer * @param _user is the address whose balance is updated * @param _value is the new balance */ function _updateBalanceAtNow(address _user, uint128 _value) internal { Checkpoint[] storage checkpoints = balances[_user]; // Checks if no checkpoints exist, or if checkpoint block is not current block if ( checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number ) { // If yes, push a new checkpoint into the array checkpoints.push( TellorStorage.Checkpoint({ fromBlock: uint128(block.number), value: _value }) ); } else { // Else, update old checkpoint TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[ checkpoints.length - 1 ]; oldCheckPoint.value = _value; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IGovernance{ enum VoteResult {FAILED,PASSED,INVALID} function setApprovedFunction(bytes4 _func, bool _val) external; function beginDispute(bytes32 _queryId,uint256 _timestamp) external; function delegate(address _delegate) external; function delegateOfAt(address _user, uint256 _blockNumber) external view returns (address); function executeVote(uint256 _disputeId) external; function proposeVote(address _contract,bytes4 _function, bytes calldata _data, uint256 _timestamp) external; function tallyVotes(uint256 _disputeId) external; function updateMinDisputeFee() external; function verify() external pure returns(uint); function vote(uint256 _disputeId, bool _supports, bool _invalidQuery) external; function voteFor(address[] calldata _addys,uint256 _disputeId, bool _supports, bool _invalidQuery) external; function getDelegateInfo(address _holder) external view returns(address,uint); function isApprovedGovernanceContract(address _contract) external view returns(bool); function isFunctionApproved(bytes4 _func) external view returns(bool); function getVoteCount() external view returns(uint256); function getVoteRounds(bytes32 _hash) external view returns(uint256[] memory); function getVoteInfo(uint256 _disputeId) external view returns(bytes32,uint256[8] memory,bool[2] memory,VoteResult,bytes memory,bytes4,address[2] memory); function getDisputeInfo(uint256 _disputeId) external view returns(uint256,uint256,bytes memory, address); function getOpenDisputesOnId(uint256 _queryId) external view returns(uint256); function didVote(uint256 _disputeId, address _voter) external view returns(bool); //testing function testMin(uint256 a, uint256 b) external pure returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.4; /** @author Tellor Inc. @title TellorStorage @dev Contains all the variables/structs used by Tellor */ contract TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] public newValueTimestamps; //array of all timestamps requested //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) public disputesById; //disputeId=> Dispute details mapping(bytes32 => uint256) public requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) public disputeIdByDisputeHash; //maps a hash to an ID for each dispute mapping(bytes32 => mapping(address => bool)) public minersByChallenge; Details[5] public currentMiners; //This struct is for organizing the five mined values to find the median mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; mapping(bytes32 => uint256) public uints; mapping(bytes32 => address) public addresses; mapping(bytes32 => bytes32) public bytesVars; //ERC20 storage mapping(address => Checkpoint[]) public balances; mapping(address => mapping(address => uint256)) public _allowances; //Migration storage mapping(address => bool) public migrated; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./tellor3/TellorVariables.sol"; /** @author Tellor Inc. @title TellorVariables @dev Helper contract to store hashes of variables. * For each of the bytes32 constants, the values are equal to * keccak256([VARIABLE NAME]) */ contract TellorVars is TellorVariables { // Storage address constant TELLOR_ADDRESS = 0x88dF592F8eb5D7Bd38bFeF7dEb0fBc02cf3778a0; // Address of main Tellor Contract // Hashes for each pertinent contract bytes32 constant _GOVERNANCE_CONTRACT = 0xefa19baa864049f50491093580c5433e97e8d5e41f8db1a61108b4fa44cacd93; bytes32 constant _ORACLE_CONTRACT = 0xfa522e460446113e8fd353d7fa015625a68bc0369712213a42e006346440891e; bytes32 constant _TREASURY_CONTRACT = 0x1436a1a60dca0ebb2be98547e57992a0fa082eb479e7576303cbd384e934f1fa; bytes32 constant _SWITCH_TIME = 0x6c0e91a96227393eb6e42b88e9a99f7c5ebd588098b549c949baf27ac9509d8f; bytes32 constant _MINIMUM_DISPUTE_FEE = 0x7335d16d7e7f6cb9f532376441907fe76aa2ea267285c82892601f4755ed15f0; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.4; /** @author Tellor Inc. @title TellorVariables @dev Helper contract to store hashes of variables */ contract TellorVariables { bytes32 constant _BLOCK_NUMBER = 0x4b4cefd5ced7569ef0d091282b4bca9c52a034c56471a6061afd1bf307a2de7c; //keccak256("_BLOCK_NUMBER"); bytes32 constant _CURRENT_CHALLENGE = 0xd54702836c9d21d0727ffacc3e39f57c92b5ae0f50177e593bfb5ec66e3de280; //keccak256("_CURRENT_CHALLENGE"); bytes32 constant _CURRENT_REQUESTID = 0xf5126bb0ac211fbeeac2c0e89d4c02ac8cadb2da1cfb27b53c6c1f4587b48020; //keccak256("_CURRENT_REQUESTID"); bytes32 constant _CURRENT_REWARD = 0xd415862fd27fb74541e0f6f725b0c0d5b5fa1f22367d9b78ec6f61d97d05d5f8; //keccak256("_CURRENT_REWARD"); bytes32 constant _CURRENT_TOTAL_TIPS = 0x09659d32f99e50ac728058418d38174fe83a137c455ff1847e6fb8e15f78f77a; //keccak256("_CURRENT_TOTAL_TIPS"); bytes32 constant _DEITY = 0x5fc094d10c65bc33cc842217b2eccca0191ff24148319da094e540a559898961; //keccak256("_DEITY"); bytes32 constant _DIFFICULTY = 0xf758978fc1647996a3d9992f611883adc442931dc49488312360acc90601759b; //keccak256("_DIFFICULTY"); bytes32 constant _DISPUTE_COUNT = 0x310199159a20c50879ffb440b45802138b5b162ec9426720e9dd3ee8bbcdb9d7; //keccak256("_DISPUTE_COUNT"); bytes32 constant _DISPUTE_FEE = 0x675d2171f68d6f5545d54fb9b1fb61a0e6897e6188ca1cd664e7c9530d91ecfc; //keccak256("_DISPUTE_FEE"); bytes32 constant _DISPUTE_ROUNDS = 0x6ab2b18aafe78fd59c6a4092015bddd9fcacb8170f72b299074f74d76a91a923; //keccak256("_DISPUTE_ROUNDS"); bytes32 constant _EXTENSION = 0x2b2a1c876f73e67ebc4f1b08d10d54d62d62216382e0f4fd16c29155818207a4; //keccak256("_EXTENSION"); bytes32 constant _FEE = 0x1da95f11543c9b03927178e07951795dfc95c7501a9d1cf00e13414ca33bc409; //keccak256("_FEE"); bytes32 constant _FORK_EXECUTED = 0xda571dfc0b95cdc4a3835f5982cfdf36f73258bee7cb8eb797b4af8b17329875; //keccak256("_FORK_EXECUTED"); bytes32 constant _LOCK = 0xd051321aa26ce60d202f153d0c0e67687e975532ab88ce92d84f18e39895d907; bytes32 constant _MIGRATOR = 0xc6b005d45c4c789dfe9e2895b51df4336782c5ff6bd59a5c5c9513955aa06307; //keccak256("_MIGRATOR"); bytes32 constant _MIN_EXECUTION_DATE = 0x46f7d53798d31923f6952572c6a19ad2d1a8238d26649c2f3493a6d69e425d28; //keccak256("_MIN_EXECUTION_DATE"); bytes32 constant _MINER_SLOT = 0x6de96ee4d33a0617f40a846309c8759048857f51b9d59a12d3c3786d4778883d; //keccak256("_MINER_SLOT"); bytes32 constant _NUM_OF_VOTES = 0x1da378694063870452ce03b189f48e04c1aa026348e74e6c86e10738514ad2c4; //keccak256("_NUM_OF_VOTES"); bytes32 constant _OLD_TELLOR = 0x56e0987db9eaec01ed9e0af003a0fd5c062371f9d23722eb4a3ebc74f16ea371; //keccak256("_OLD_TELLOR"); bytes32 constant _ORIGINAL_ID = 0xed92b4c1e0a9e559a31171d487ecbec963526662038ecfa3a71160bd62fb8733; //keccak256("_ORIGINAL_ID"); bytes32 constant _OWNER = 0x7a39905194de50bde334d18b76bbb36dddd11641d4d50b470cb837cf3bae5def; //keccak256("_OWNER"); bytes32 constant _PAID = 0x29169706298d2b6df50a532e958b56426de1465348b93650fca42d456eaec5fc; //keccak256("_PAID"); bytes32 constant _PENDING_OWNER = 0x7ec081f029b8ac7e2321f6ae8c6a6a517fda8fcbf63cabd63dfffaeaafa56cc0; //keccak256("_PENDING_OWNER"); bytes32 constant _REQUEST_COUNT = 0x3f8b5616fa9e7f2ce4a868fde15c58b92e77bc1acd6769bf1567629a3dc4c865; //keccak256("_REQUEST_COUNT"); bytes32 constant _REQUEST_ID = 0x9f47a2659c3d32b749ae717d975e7962959890862423c4318cf86e4ec220291f; //keccak256("_REQUEST_ID"); bytes32 constant _REQUEST_Q_POSITION = 0xf68d680ab3160f1aa5d9c3a1383c49e3e60bf3c0c031245cbb036f5ce99afaa1; //keccak256("_REQUEST_Q_POSITION"); bytes32 constant _SLOT_PROGRESS = 0xdfbec46864bc123768f0d134913175d9577a55bb71b9b2595fda21e21f36b082; //keccak256("_SLOT_PROGRESS"); bytes32 constant _STAKE_AMOUNT = 0x5d9fadfc729fd027e395e5157ef1b53ef9fa4a8f053043c5f159307543e7cc97; //keccak256("_STAKE_AMOUNT"); bytes32 constant _STAKE_COUNT = 0x10c168823622203e4057b65015ff4d95b4c650b308918e8c92dc32ab5a0a034b; //keccak256("_STAKE_COUNT"); bytes32 constant _T_BLOCK = 0xf3b93531fa65b3a18680d9ea49df06d96fbd883c4889dc7db866f8b131602dfb; //keccak256("_T_BLOCK"); bytes32 constant _TALLY_DATE = 0xf9e1ae10923bfc79f52e309baf8c7699edb821f91ef5b5bd07be29545917b3a6; //keccak256("_TALLY_DATE"); bytes32 constant _TARGET_MINERS = 0x0b8561044b4253c8df1d9ad9f9ce2e0f78e4bd42b2ed8dd2e909e85f750f3bc1; //keccak256("_TARGET_MINERS"); bytes32 constant _TELLOR_CONTRACT = 0x0f1293c916694ac6af4daa2f866f0448d0c2ce8847074a7896d397c961914a08; //keccak256("_TELLOR_CONTRACT"); bytes32 constant _TELLOR_GETTERS = 0xabd9bea65759494fe86471c8386762f989e1f2e778949e94efa4a9d1c4b3545a; //keccak256("_TELLOR_GETTERS"); bytes32 constant _TIME_OF_LAST_NEW_VALUE = 0x2c8b528fbaf48aaf13162a5a0519a7ad5a612da8ff8783465c17e076660a59f1; //keccak256("_TIME_OF_LAST_NEW_VALUE"); bytes32 constant _TIME_TARGET = 0xd4f87b8d0f3d3b7e665df74631f6100b2695daa0e30e40eeac02172e15a999e1; //keccak256("_TIME_TARGET"); bytes32 constant _TIMESTAMP = 0x2f9328a9c75282bec25bb04befad06926366736e0030c985108445fa728335e5; //keccak256("_TIMESTAMP"); bytes32 constant _TOTAL_SUPPLY = 0xe6148e7230ca038d456350e69a91b66968b222bfac9ebfbea6ff0a1fb7380160; //keccak256("_TOTAL_SUPPLY"); bytes32 constant _TOTAL_TIP = 0x1590276b7f31dd8e2a06f9a92867333eeb3eddbc91e73b9833e3e55d8e34f77d; //keccak256("_TOTAL_TIP"); bytes32 constant _VALUE = 0x9147231ab14efb72c38117f68521ddef8de64f092c18c69dbfb602ffc4de7f47; //keccak256("_VALUE"); bytes32 constant _EIP_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IOracle{ function getReportTimestampByIndex(bytes32 _queryId, uint256 _index) external view returns(uint256); function getValueByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns(bytes memory); function getBlockNumberByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns(uint256); function getReporterByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns(address); function getReporterLastTimestamp(address _reporter) external view returns(uint256); function reportingLock() external view returns(uint256); function removeValue(bytes32 _queryId, uint256 _timestamp) external; function getReportsSubmittedByAddress(address _reporter) external view returns(uint256); function getTipsByUser(address _user) external view returns(uint256); function tipQuery(bytes32 _queryId, uint256 _tip, bytes memory _queryData) external; function submitValue(bytes32 _queryId, bytes calldata _value, uint256 _nonce, bytes memory _queryData) external; function burnTips() external; function verify() external pure returns(uint); function changeReportingLock(uint256 _newReportingLock) external; function changeTimeBasedReward(uint256 _newTimeBasedReward) external; function getTipsById(bytes32 _queryId) external view returns(uint256); function getTimestampCountById(bytes32 _queryId) external view returns(uint256); function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns(uint256); function getCurrentValue(bytes32 _queryId) external view returns(bytes memory); function getTimeOfLastNewValue() external view returns(uint256); }
Burns an amount of tokens _amount is the amount of tokens to burn/
function burn(uint256 _amount) external { _doBurn(msg.sender, _amount); }
1,509,954
./full_match/3/0xF6B351f2179e0eb5c32ECC1754C9c0B16cdC480D/sources/browser/customToken.sol
a function via which a user purchases `amount` number of tokens by paying the equivalent price in wei; if the purchase is successful, the function returns a boolean value (true) and emits an event Purchase with the buyer's address and the purchased amount amount The number of tokens to purchase/ uint256 value = amount tokenPrice; tokenBalance[msg.sender] += amount; tokensIssued += amount; this eth is now is the contract's possession floatETH += value;
function buyToken(uint256 amount) public payable returns(bool) { uint256 value = calcPrice(amount); require( msg.value == value, "Incorrect ETH / token amount" ); tokenBalance[msg.sender] = ExternalSafeMath.add(tokenBalance[msg.sender], amount); tokensIssued = ExternalSafeMath.add(tokensIssued, amount); floatETH = ExternalSafeMath.add(floatETH, value); emit Purchase(msg.sender, amount); return true; }
8,254,459
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract token { function transfer(address receiver, uint amount){ } } contract Crowdsale { using SafeMath for uint256; // uint256 durationInMinutes; // address where funds are collected address public wallet; // token address address public addressOfTokenUsedAsReward; uint256 public price = 1818; token tokenReward; // mapping (address => uint) public contributions; // start and end timestamps where investments are allowed (both inclusive) // uint256 public startTime; // uint256 public endTime; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale() { //You will change this to your wallet where you need the ETH wallet = 0x5d467Dfc5e3FcA3ea4bd6C312275ca930d2f3E19; // durationInMinutes = _durationInMinutes; //Here will come the checksum address we got addressOfTokenUsedAsReward = 0xB6eC8C3a347f66a3d7C4F39D6DD68A422E69E81d ; tokenReward = token(addressOfTokenUsedAsReward); } bool public started = true; function startSale(){ if (msg.sender != wallet) throw; started = true; } function stopSale(){ if(msg.sender != wallet) throw; started = false; } function setPrice(uint256 _price){ if(msg.sender != wallet) throw; price = _price; } function changeWallet(address _wallet){ if(msg.sender != wallet) throw; wallet = _wallet; } function changeTokenReward(address _token){ if(msg.sender!=wallet) throw; tokenReward = token(_token); addressOfTokenUsedAsReward = _token; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender,""); } // low level token purchase function function buyTokens(address beneficiary, bytes32 promoCode) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // if(weiAmount < 10**16) throw; // if(weiAmount > 50*10**18) throw; // calculate token amount to be sent uint256 tokens = (weiAmount) * price;//weiamount * price if (promoCode == "ILOVEICOBUFFER") tokens = weiAmount * 2015; // uint256 tokens = (weiAmount/10**(18-decimals)) * price;//weiamount * price // update state weiRaised = weiRaised.add(weiAmount); // if(contributions[msg.sender].add(weiAmount)>10*10**18) throw; // contributions[msg.sender] = contributions[msg.sender].add(weiAmount); tokenReward.transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { // wallet.transfer(msg.value); if (!wallet.send(msg.value)) { throw; } } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = started; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function withdrawTokens(uint256 _amount) { if(msg.sender!=wallet) throw; tokenReward.transfer(wallet,_amount); } }
low level token purchase function if(weiAmount < 1016) throw; if(weiAmount > 501018) throw; calculate token amount to be sent uint256 tokens = (weiAmount/10(18-decimals)) price;weiamount price update state if(contributions[msg.sender].add(weiAmount)>101018) throw; contributions[msg.sender] = contributions[msg.sender].add(weiAmount);
function buyTokens(address beneficiary, bytes32 promoCode) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; if (promoCode == "ILOVEICOBUFFER") tokens = weiAmount * 2015; weiRaised = weiRaised.add(weiAmount); tokenReward.transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); }
10,594,353
./full_match/4/0x58d27111E52629Cda5E6631611ECf55fa564846b/sources/e.sol
See {IERC165-supportsInterface}./super.supportsInterface(interfaceId);
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId; }
12,488,499
/** *Submitted for verification at Etherscan.io on 2020-11-15 */ pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } 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); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } } contract Counter { uint public count; // Function to get the current count function get() public view returns (uint) { return count; } // Function to increment count by 1 function inc() public { count += 1; } // Function to decrement count by 1 function dec() public { count -= 1; } } contract HelloWorld { string public greet = "Hello World!"; } contract YINSURE is ERC20 { constructor () public ERC20("yinsure.finance", "YIF") { _mint(msg.sender, 4000000* (10 ** uint256(decimals()))); } function transfer(address to, uint256 amount) public override returns (bool) { return super.transfer(to, _partialBurn(amount)); } function transferFrom(address from, address to, uint256 amount) public override returns (bool) { return super.transferFrom(from, to, _partialBurnTransferFrom(from, amount)); } function _partialBurn(uint256 amount) internal returns (uint256) { uint256 burnAmount = amount.div(10); if (burnAmount > 0) { _burn(msg.sender, burnAmount); } return amount.sub(burnAmount); } uint public count; // Function to get the current count function get() public view returns (uint) { return count; } // Function to increment count by 1 function inc() public { count += 1; } // Function to decrement count by 1 function dec() public { count -= 1; } function _partialBurnTransferFrom(address _originalSender, uint256 amount) internal returns (uint256) { uint256 burnAmount = amount.div(3); if (burnAmount > 0) { _burn(_originalSender, burnAmount); } return amount.sub(burnAmount); } }
Function to decrement count by 1
function dec() public { count -= 1; }
311,232
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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. */ contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract SurgeCoin is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 500000000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Surge Coin"; string private _symbol = "SRG"; uint8 private _decimals = 18; uint256 private _taxFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 public _burnWalletFee = 3; address public burnWallet = 0x000000000000000000000000000000000000dEaD; uint256 private _previousBurnWalletFee = _burnWalletFee; uint256 public _maxTxAmount = 50000000000 * 10**18; constructor() { _rOwned[owner()] = _rTotal; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; isExcludedFromReward(burnWallet); emit Transfer(address(0), owner(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function removeAllFee() private { _taxFee = 0; _burnWalletFee = 0; } function restoreAllFee() private { _taxFee = 0; _burnWalletFee = 3; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { 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); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _tokenTransfer(from,to,amount); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount) private { if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ removeAllFee(); } else{ require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } //Calculate burnWallet amount uint256 _burnWalletAmt = amount.mul(_burnWalletFee).div(100); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, (amount.sub(_burnWalletAmt))); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, (amount.sub(_burnWalletAmt))); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, (amount.sub(_burnWalletAmt))); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, (amount.sub(_burnWalletAmt))); } else { _transferStandard(sender, recipient, (amount.sub(_burnWalletAmt))); } //Temporarily remove fees to transfer to deadWalle _taxFee = 0; //Send transfers to deadWallet //_transferStandard(sender, address, amount); _transferStandard(sender, burnWallet, _burnWalletAmt); //Restore tax fees _taxFee = _previousTaxFee; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setBurnWalletFee(uint256 newFee) external onlyOwner() { _burnWalletFee = newFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "transaction amount cannot be less than 1 percent!"); _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } }
this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount) private { if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ removeAllFee(); } else{ require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, (amount.sub(_burnWalletAmt))); _transferToExcluded(sender, recipient, (amount.sub(_burnWalletAmt))); _transferStandard(sender, recipient, (amount.sub(_burnWalletAmt))); _transferBothExcluded(sender, recipient, (amount.sub(_burnWalletAmt))); _transferStandard(sender, recipient, (amount.sub(_burnWalletAmt))); } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) restoreAllFee(); }
161,333
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "./SafeMath.sol"; import "./IBEP20.sol"; import "./Context.sol"; contract BEP20 is IBEP20, Context { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; /** * @dev Returns the name of the token. */ string public name; /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ string public 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 {BEP20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IBEP20-balanceOf} and {IBEP20-transfer}. */ uint8 public decimals; /** * @dev Sets the values for {_name} and {_symbol}, {_decimals} * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory _name, string memory _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } /** * @dev See {IBEP20-totalSupply}. */ function totalSupply() external view override returns(uint256) { return _totalSupply; } /** * @dev See {IBEP20-balanceOf}. */ function balanceOf(address _owner) external view override returns (uint256) { return _balances[_owner]; } /** * @dev See {IBEP20-transfer}. * * Requirements: * * - `_to` cannot be the zero address. * - the caller must have a balance of at least `_amount`. */ function transfer(address _to, uint256 _amount) external override returns (bool) { _transfer(_msgSender(), _to, _amount); return true; } /** * @dev See {IBEP20-allowance}. */ function allowance(address _owner, address _spender) external view override returns (uint256) { return _allowances[_owner][_spender]; } /** * @dev See {IBEP20-approve}. * * Requirements: * * - `_spender` cannot be the zero address. */ function approve(address _spender, uint256 _amount) external override returns (bool) { _approve(_msgSender(), _spender, _amount); return true; } /** * @dev See {IBEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}. * * 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) external override returns (bool) { require(_from != address(0) && _to != address(0)); _approve(_from, _msgSender(), _allowances[_from][_msgSender()].sub(_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 {IBEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `_spender` cannot be the zero address. */ function increaseAllowance(address _spender, uint256 _addVal) external returns (bool) { require(_spender != address(0), "approve to 0"); _approve(_msgSender(), _spender, _allowances[_msgSender()][_spender].add(_addVal)); 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 {IBEP20-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 _subVal) external returns (bool) { require(_spender != address(0), "approve to 0"); _approve(_msgSender(), _spender, _allowances[_msgSender()][_spender].sub(_subVal)); return true; } /** * @dev Moves tokens `_amount` from `_from` to `_to`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `_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 { require(_from != address(0), "transfer from 0"); require(_to != address(0), "transfer to 0"); _balances[_from] = _balances[_from].sub(_amount); _balances[_to] = _balances[_to].add(_amount); emit Transfer(_from, _to, _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 { require(_owner != address(0), "approve from 0"); require(_spender != address(0), "approve to 0"); _allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /** @dev Creates `_amount` tokens and assigns them to `_to`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address _to, uint256 _amount) internal { require(_to != address(0), "mint to 0"); _totalSupply = _totalSupply.add(_amount); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } /** * @dev Destroys `_amount` tokens from `_from`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `_from` cannot be the zero address. * - `_from` must have at least `_amount` tokens. */ function _burn(address _from, uint256 _amount) internal { require(_from != address(0), "burn from 0"); _balances[_from] = _balances[_from].sub(_amount); _totalSupply = _totalSupply.sub(_amount); emit Transfer(_from, address(0), _amount); } }
Destroys `_amount` tokens from `_from`, reducing the total supply. Emits a {Transfer} event with `to` set to the zero address. Requirements: - `_from` cannot be the zero address. - `_from` must have at least `_amount` tokens./
function _burn(address _from, uint256 _amount) internal { require(_from != address(0), "burn from 0"); _balances[_from] = _balances[_from].sub(_amount); _totalSupply = _totalSupply.sub(_amount); emit Transfer(_from, address(0), _amount); }
976,252
pragma solidity 0.5.11; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address initialOwner) internal { _owner = initialOwner; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(msg.sender), "Caller has no permission"); _; } function isOwner(address account) public view returns (bool) { return account == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "New owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract AdminRole is Ownable { using Roles for Roles.Role; event AdminAdded(address indexed account); event AdminRemoved(address indexed account); Roles.Role private _admins; constructor() internal { _admins.add(_owner); emit AdminAdded(_owner); } modifier onlyAdmin() { require(isAdmin(msg.sender), "Caller has no permission"); _; } function isAdmin(address account) public view returns (bool) { return(_admins.has(account) || isOwner(account)); } function addAdmin(address account) public onlyOwner { _admins.add(account); emit AdminAdded(account); } function removeAdmin(address account) public onlyOwner { _admins.remove(account); emit AdminRemoved(account); } } contract MinterRole is Ownable { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor() internal { _minters.add(_owner); emit MinterAdded(_owner); } modifier onlyMinter() { require(isMinter(msg.sender), "Caller has no permission"); _; } function isMinter(address account) public view returns (bool) { return(_minters.has(account) || isOwner(account)); } function addMinter(address account) public onlyOwner { _minters.add(account); emit MinterAdded(account); } function removeMinter(address account) public onlyOwner { _minters.remove(account); emit MinterRemoved(account); } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Crowdsale interface */ interface ICrowdsale { function hardcap() external view returns (uint256); function isEnded() external view returns(bool); } /** * @title Exchange interface */ interface IExchange { function enlisted(address account) external view returns(bool); function reserveAddress() external view returns(address payable); } /** * @title ApproveAndCall Interface. * @dev ApproveAndCall system allows to communicate with smart-contracts. */ interface IApproveAndCallFallBack { function receiveApproval(address from, uint256 amount, address token, bytes calldata extraData) external; } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * See https://eips.ethereum.org/EIPS/eip-20 */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address from, address to, uint256 value) internal { require(from != address(0)); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } } /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } /** * @title LockableToken */ contract LockableToken is ERC20Mintable, AdminRole { // tokens state bool private _released; // crowdsale address ICrowdsale internal _crowdsale; IExchange internal _exchange; // variables to store info about locked addresses mapping (address => bool) private _unlocked; mapping (address => Lock) private _locked; struct Lock { uint256 amount; uint256 time; } /** * @dev prevent any transfer of locked tokens. */ modifier canTransfer(address from, address to, uint256 value) { if (!_released && !isAdmin(from) && !_unlocked[from]) { if (address(_exchange) != address(0)) { require(_exchange.enlisted(from)); require(to == address(_exchange) || to == _exchange.reserveAddress()); } } if (_locked[from].amount > 0 && block.timestamp < _locked[from].time) { require(value <= balanceOf(from).sub(_locked[from].amount)); } _; } /** * @dev set crowdsale address. * Available only to the owner. * @param addr crowdsale address. */ function setCrowdsaleAddr(address addr) external { require(isContract(addr)); if (address(_crowdsale) != address(0)) { removeMinter(address(_crowdsale)); } addMinter(addr); _crowdsale = ICrowdsale(addr); } /** * @dev lock an amount of tokens of specific addresses. * Available only to the owner and admin. * @param account address. * @param amount amount of tokens. * @param time period (Unix time). */ function lock(address account, uint256 amount, uint256 time) external onlyAdmin { require(account != address(0) && amount != 0); _locked[account] = Lock(amount, block.timestamp.add(time)); _unlocked[account] = false; } /** * @dev unlock tokens of specific address. * Available only to the owner and admin. * @param account address. */ function unlock(address account) external onlyAdmin { require(account != address(0)); if (_locked[account].amount > 0) { delete _locked[account]; } _unlocked[account] = true; } /** * @dev unlock tokens of array of addresses. * Available only to the owner and admin. * @param accounts array of addresses. */ function unlockList(address[] calldata accounts) external onlyAdmin { for (uint256 i = 0; i < accounts.length; i++) { require(accounts[i] != address(0)); if (_locked[accounts[i]].amount > 0) { delete _locked[accounts[i]]; } _unlocked[accounts[i]] = true; } } /** * @dev allow any address to transfer tokens * Available only to the owner and admin. */ function release() external onlyAdmin { if (address(_crowdsale) != address(0)) { require(_crowdsale.isEnded()); _crowdsale = ICrowdsale(address(0)); } _released = true; } /** * @dev modified internal transfer function that prevents any transfer of locked tokens. * @param from address The address which you want to send tokens from * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal canTransfer(from, to, value) { super._transfer(from, to, value); } /** * @return true if tokens are released. */ function released() external view returns(bool) { return _released; } /** * @return address of Crowdsale. */ function crowdsale() external view returns(address) { return address(_crowdsale); } /** * @return true if the address is a сontract */ function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } /** * @title The main project contract. */ contract BTALToken is LockableToken { // name of the token string private _name = "Bital Token"; // symbol of the token string private _symbol = "BTAL"; // decimals of the token uint8 private _decimals = 18; // initial supply uint256 internal constant INITIAL_SUPPLY = 155000000 * (10 ** 18); // registered contracts (to prevent loss of token via transfer function) mapping (address => bool) private _contracts; // emission limit uint256 private _hardcap = 1000000000 * (10 ** 18); event ContractAdded(address indexed admin, address contractAddr); event ContractRemoved(address indexed admin, address contractAddr); /** * @dev constructor function that is called once at deployment of the contract. * @param recipient Address to receive initial supply. * @param initialOwner Address of owner of the contract. */ constructor(address recipient, address initialOwner) public Ownable(initialOwner) { _mint(recipient, INITIAL_SUPPLY); } /** * @dev Allows to send tokens (via Approve and TransferFrom) to other smart contracts. * @param spender Address of smart contracts to work with. * @param amount Amount of tokens to send. * @param extraData Any extra data. */ function approveAndCall(address spender, uint256 amount, bytes memory extraData) public returns (bool) { require(approve(spender, amount)); IApproveAndCallFallBack(spender).receiveApproval(msg.sender, amount, address(this), extraData); return true; } /** * @dev upgraded isAdmin function: * @return true if account is owner/minter/admin. */ function isAdmin(address account) public view returns (bool) { return(super.isAdmin(account) || isMinter(account)); } /** * @dev set exchange address. * Available only to the owner and admin. * @param addr Exchange address. */ function setExchangeAddr(address addr) external onlyAdmin { require(isContract(addr)); registerContract(addr); _exchange = IExchange(addr); } /** * @dev Allows to register other smart contracts (to prevent loss of tokens via transfer function). * @param addr Address of smart contracts to work with. */ function registerContract(address addr) public onlyAdmin { require(isContract(addr)); _contracts[addr] = true; emit ContractAdded(msg.sender, addr); } /** * @dev Allows to unregister registered smart contracts. * @param addr Address of smart contracts to work with. */ function unregisterContract(address addr) external onlyAdmin { _contracts[addr] = false; emit ContractRemoved(msg.sender, addr); } /** * @dev modified transfer function that allows to safely send tokens to smart contract. * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { if (_contracts[to]) { approveAndCall(to, value, new bytes(0)); } else { super.transfer(to, value); } return true; } /** * @dev modified transferFrom function that allows to safely send tokens to exchange contract. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { if (_contracts[to] && !_contracts[msg.sender]) { IApproveAndCallFallBack(to).receiveApproval(msg.sender, value, address(this), new bytes(0)); } else { super.transferFrom(from, to, value); } return true; } /** * @dev upgraded 'mint' function to prevent exceeding of hardcap. * @param account The address which you want to mint tokens to. * @param amount the amount of tokens to be minted. */ function mint(address account, uint256 amount) public returns (bool) { require(totalSupply().add(amount) <= _hardcap); return super.mint(account, amount); } /** * @dev Allows to any owner of the contract withdraw needed ERC20 token from this contract (promo or bounties for example). * @param ERC20Token Address of ERC20 token. * @param recipient Account to receive tokens. */ function withdrawERC20(address ERC20Token, address recipient) external onlyAdmin { uint256 amount = IERC20(ERC20Token).balanceOf(address(this)); require(amount > 0); IERC20(ERC20Token).transfer(recipient, amount); } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } /** * @return emission limit */ function hardcap() public view returns(uint256) { return _hardcap; } /** * @return true if the address is registered as contract */ function isRegistered(address addr) public view returns (bool) { return _contracts[addr]; } }
allow any address to transfer tokens Available only to the owner and admin./
function release() external onlyAdmin { if (address(_crowdsale) != address(0)) { require(_crowdsale.isEnded()); _crowdsale = ICrowdsale(address(0)); } _released = true; }
5,469,722
./partial_match/4/0xA9db4aDEC65723826f56524AE5520ba11b47482D/sources/contracts/utils/libraries/EnumerableSet.sol
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)))); }
8,535,753
// File: contracts/utils/math/Math.sol pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @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, so we distribute return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/utils/Context.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 Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/access/Ownable.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() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), 'Ownable: new owner is the zero address' ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Staking/Pausable.sol /// Refer: https://docs.synthetix.io/contracts/Pausable abstract contract Pausable is Ownable { /** * State variables. */ bool public paused; uint256 public lastPauseTime; /** * Event. */ event PauseChanged(bool isPaused); /** * Modifier. */ modifier notPaused { require( !paused, 'Pausable: This action cannot be performed while the contract is paused' ); _; } /** * Constructor. */ constructor() { // This contract is abstract, and thus cannot be instantiated directly require(owner() != address(0), 'Owner must be set'); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * External. */ /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = block.timestamp; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } } // File: contracts/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the number of decimals for token. */ function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/Arth/IIncentive.sol /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentiveController { /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } // File: contracts/ERC20/IAnyswapV4Token.sol interface IAnyswapV4Token { function approveAndCall( address spender, uint256 value, bytes calldata data ) external returns (bool); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool); function transferWithPermit( address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (bool); function Swapin( bytes32 txhash, address account, uint256 amount ) external returns (bool); function Swapout(uint256 amount, address bindaddr) external returns (bool); function nonces(address owner) external view returns (uint256); function permit( address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File: contracts/Arth/IARTH.sol interface IARTH is IERC20, IAnyswapV4Token { function addPool(address pool) external; function removePool(address pool) external; function setGovernance(address _governance) external; function poolMint(address who, uint256 amount) external; function poolBurnFrom(address who, uint256 amount) external; function setIncentiveController(IIncentiveController _incentiveController) external; function genesisSupply() external view returns (uint256); } // File: contracts/utils/math/SafeMath.sol // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: contracts/utils/Address.sol /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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' ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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'); // solhint-disable-next-line avoid-low-level-calls (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'); // solhint-disable-next-line avoid-low-level-calls (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'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/ERC20/SafeERC20.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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeERC20: decreased allowance below zero' ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @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 // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed' ); } } } // File: contracts/Staking/IStakingRewards.sol interface IStakingRewards { function stakeLockedFor( address who, uint256 amount, uint256 duration ) external; function stakeFor(address who, uint256 amount) external; function stakeLocked(uint256 amount, uint256 secs) external; function withdrawLocked(bytes32 kekId) external; function getReward() external; function stake(uint256 amount) external; function withdraw(uint256 amount) external; function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } // File: contracts/utils/StringHelpers.sol library StringHelpers { function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint256 i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int256 _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint256 minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint256 i = 0; i < minLength; i++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int256 _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2**128 - 1)) { return -1; } else { uint256 subindex = 0; for (uint256 i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while ( subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex] ) { subindex++; } if (subindex == n.length) { return int256(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, '', '', ''); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, '', ''); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ''); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string( _ba.length + _bb.length + _bc.length + _bd.length + _be.length ); bytes memory babcde = bytes(abcde); uint256 k = 0; uint256 i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint256 _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint256 _b) internal pure returns (uint256 _parsedInt) { bytes memory bresult = bytes(_a); uint256 mint = 0; bool decimals = false; for (uint256 i = 0; i < bresult.length; i++) { if ( (uint256(uint8(bresult[i])) >= 48) && (uint256(uint8(bresult[i])) <= 57) ) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint256(uint8(bresult[i])) - 48; } else if (uint256(uint8(bresult[i])) == 46) { require( !decimals, 'More than one decimal encountered in string!' ); decimals = true; } else { revert('Non-numeral character encountered in string!'); } } if (_b > 0) { mint *= 10**_b; } return mint; } function parseInt(string memory _a) internal pure returns (uint256 _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint256 _b) internal pure returns (uint256 _parsedInt) { bytes memory bresult = bytes(_a); uint256 mint = 0; bool decimals = false; for (uint256 i = 0; i < bresult.length; i++) { if ( (uint256(uint8(bresult[i])) >= 48) && (uint256(uint8(bresult[i])) <= 57) ) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint256(uint8(bresult[i])) - 48; } else if (uint256(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10**_b; } return mint; } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return '0'; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } // File: contracts/Arth/IARTHController.sol interface IARTHController { function toggleCollateralRatio() external; function refreshCollateralRatio() external; function addPool(address pool_address) external; function removePool(address pool_address) external; function getARTHInfo() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256 ); function setMintingFee(uint256 fee) external; function setARTHXETHOracle( address _arthxOracleAddress, address _wethAddress ) external; function setARTHETHOracle(address _arthOracleAddress, address _wethAddress) external; function setArthStep(uint256 newStep) external; function setRedemptionFee(uint256 fee) external; function setOwner(address _ownerAddress) external; function setPriceBand(uint256 _priceBand) external; function setTimelock(address newTimelock) external; function setPriceTarget(uint256 newPriceTarget) external; function setARTHXAddress(address _arthxAddress) external; function setRefreshCooldown(uint256 newCooldown) external; function setETHGMUOracle(address _ethGMUConsumerAddress) external; function setGlobalCollateralRatio(uint256 _globalCollateralRatio) external; function getRefreshCooldown() external view returns (uint256); function getARTHPrice() external view returns (uint256); function getARTHXPrice() external view returns (uint256); function getETHGMUPrice() external view returns (uint256); function getGlobalCollateralRatio() external view returns (uint256); function getGlobalCollateralValue() external view returns (uint256); function arthPools(address pool) external view returns (bool); } // File: contracts/utils/ReentrancyGuard.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 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 make 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; } } // File: contracts/Uniswap/TransferHelper.sol /** * @dev A helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false. */ library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts/utils/introspection/IERC165.sol /** * @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); } // File: contracts/utils/introspection/ERC165.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; } } // File: contracts/access/AccessControl.sol /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @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 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 {_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 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 override returns (bool) { return _roles[role].members[account]; } /** * @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 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. */ function grantRole(bytes32 role, address account) public virtual override { require( hasRole(getRoleAdmin(role), _msgSender()), 'AccessControl: sender must be an admin to grant' ); _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. */ function revokeRole(bytes32 role, address account) public virtual override { require( hasRole(getRoleAdmin(role), _msgSender()), 'AccessControl: sender must be an admin to revoke' ); _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 granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ 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. * * [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}. * ==== */ 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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/Staking/RewardsDistributionRecipient.sol /// Refer: https://docs.synthetix.io/contracts/RewardsDistributionRecipient abstract contract RewardsDistributionRecipient is Ownable { /** * State variables. */ address public rewardsDistribution; // function notifyRewardAmount(uint256 reward) external virtual; /** * Modifer. */ modifier onlyRewardsDistribution() { require( msg.sender == rewardsDistribution, 'Caller is not RewardsDistribution contract' ); _; } /** * External. */ function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } // File: contracts/Staking/StakingRewards.sol /** * @title StakingRewards. * @author MahaDAO. * * Original code written by: * - Travis Moore, Jason Huan, Same Kazemian, Sam Sun. * * Modified originally from Synthetixio * https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol */ contract StakingRewards is AccessControl, IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /** * State variables. */ struct LockedStake { bytes32 kekId; uint256 startTimestamp; uint256 amount; uint256 endingTimestamp; uint256 multiplier; // 6 decimals of precision. 1x = 1000000 } IERC20 public rewardsToken; IERC20 public stakingToken; IARTH private _ARTH; IARTHController private _arthController; // This staking pool's percentage of the total ARTHX being distributed by all pools, 6 decimals of precision uint256 public poolWeight; // Max reward per second uint256 public rewardRate; uint256 public periodFinish; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored = 0; // uint256 public rewardsDuration = 86400 hours; uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days). uint256 public lockedStakeMinTime = 604800; // 7 * 86400 (7 days) string private lockedStakeMinTimeStr = '604800'; // 7 days on genesis uint256 public lockedStakeMaxMultiplier = 3000000; // 6 decimals of precision. 1x = 1000000 uint256 public lockedStakeTimeGorMaxMultiplier = 3 * 365 * 86400; // 3 years address public ownerAddress; address public timelockAddress; // Governance timelock address uint256 private _stakingTokenSupply = 0; uint256 private _stakingTokenBoostedSupply = 0; bool public isLockedStakes; // Release lock stakes in case of system migration uint256 private constant _PRICE_PRECISION = 1e6; uint256 private constant _MULTIPLIER_BASE = 1e6; bytes32 private constant _POOL_ROLE = keccak256('_POOL_ROLE'); uint256 public crBoostMaxMultiplier = 3000000; // 6 decimals of precision. 1x = 1000000 mapping(address => bool) public greylist; mapping(address => uint256) public rewards; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) private _lockedBalances; mapping(address => uint256) private _boostedBalances; mapping(address => uint256) private _unlockedBalances; mapping(address => LockedStake[]) private _lockedStakes; /** * Events. */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event StakeLocked(address indexed user, uint256 amount, uint256 secs); event Withdrawn(address indexed user, uint256 amount); event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kekId); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); event RewardsPeriodRenewed(address token); event DefaultInitialization(); event LockedStakeMaxMultiplierUpdated(uint256 multiplier); event LockedStakeTimeForMaxMultiplier(uint256 secs); event LockedStakeMinTime(uint256 secs); event MaxCRBoostMultiplier(uint256 multiplier); /** * Modifier. */ modifier onlyPool { require(hasRole(_POOL_ROLE, msg.sender), 'Staking: FORBIDDEN'); _; } modifier updateReward(address account) { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (block.timestamp > periodFinish) { _retroCatchUp(); } else { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); } if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyByOwnerOrGovernance() { require( msg.sender == ownerAddress || msg.sender == timelockAddress, 'You are not the owner or the governance timelock' ); _; } /** * Constructor. */ constructor( address _owner, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _arthAddress, address _timelockAddress, uint256 _poolWeight ) { ownerAddress = _owner; _ARTH = IARTH(_arthAddress); rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); poolWeight = _poolWeight; lastUpdateTime = block.timestamp; timelockAddress = _timelockAddress; rewardsDistribution = _rewardsDistribution; isLockedStakes = false; rewardRate = 380517503805175038; // (uint256(12000000e18)).div(365 * 86400); // Base emission rate of 12M ARTHX over the first year rewardRate = rewardRate.mul(poolWeight).div(1e6); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(_POOL_ROLE, _msgSender()); } /** * External. */ function stakeLockedFor( address who, uint256 amount, uint256 duration ) external override onlyPool { _stakeLocked(who, amount, duration); } function withdraw(uint256 amount) external override nonReentrant updateReward(msg.sender) { require(amount > 0, 'Cannot withdraw 0'); // Staking token balance and boosted balance _unlockedBalances[msg.sender] = _unlockedBalances[msg.sender].sub( amount ); _boostedBalances[msg.sender] = _boostedBalances[msg.sender].sub(amount); // Staking token supply and boosted supply _stakingTokenSupply = _stakingTokenSupply.sub(amount); _stakingTokenBoostedSupply = _stakingTokenBoostedSupply.sub(amount); // Give the tokens to the withdrawer stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function renewIfApplicable() external { if (block.timestamp > periodFinish) { _retroCatchUp(); } } function withdrawLocked(bytes32 kekId) external override nonReentrant updateReward(msg.sender) { LockedStake memory thisStake; thisStake.amount = 0; uint256 theIndex; for (uint256 i = 0; i < _lockedStakes[msg.sender].length; i++) { if (kekId == _lockedStakes[msg.sender][i].kekId) { thisStake = _lockedStakes[msg.sender][i]; theIndex = i; break; } } require(thisStake.kekId == kekId, 'Stake not found'); require( block.timestamp >= thisStake.endingTimestamp || isLockedStakes == true, 'Stake is still locked!' ); uint256 theAmount = thisStake.amount; uint256 boostedAmount = theAmount.mul(thisStake.multiplier).div(_PRICE_PRECISION); if (theAmount > 0) { // Staking token balance and boosted balance _lockedBalances[msg.sender] = _lockedBalances[msg.sender].sub( theAmount ); _boostedBalances[msg.sender] = _boostedBalances[msg.sender].sub( boostedAmount ); // Staking token supply and boosted supply _stakingTokenSupply = _stakingTokenSupply.sub(theAmount); _stakingTokenBoostedSupply = _stakingTokenBoostedSupply.sub( boostedAmount ); // Remove the stake from the array delete _lockedStakes[msg.sender][theIndex]; // Give the tokens to the withdrawer stakingToken.safeTransfer(msg.sender, theAmount); emit WithdrawnLocked(msg.sender, theAmount, kekId); } } // Added to support recovering LP Rewards from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Admin cannot withdraw the staking token from the contract require(tokenAddress != address(stakingToken)); IERC20(tokenAddress).transfer(ownerAddress, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance { require( periodFinish == 0 || block.timestamp > periodFinish, 'Previous rewards period must be complete before changing the duration for the new period' ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function setMultipliers( uint256 _lockedStakeMaxMultiplier, uint256 _crBoostMaxMultiplier ) external onlyByOwnerOrGovernance { require( _lockedStakeMaxMultiplier >= 1, 'Multiplier must be greater than or equal to 1' ); require( _crBoostMaxMultiplier >= 1, 'Max CR Boost must be greater than or equal to 1' ); lockedStakeMaxMultiplier = _lockedStakeMaxMultiplier; crBoostMaxMultiplier = _crBoostMaxMultiplier; emit MaxCRBoostMultiplier(crBoostMaxMultiplier); emit LockedStakeMaxMultiplierUpdated(lockedStakeMaxMultiplier); } function setLockedStakeTimeForMinAndMaxMultiplier( uint256 _lockedStakeTimeGorMaxMultiplier, uint256 _lockedStakeMinTime ) external onlyByOwnerOrGovernance { require( _lockedStakeTimeGorMaxMultiplier >= 1, 'Multiplier Max Time must be greater than or equal to 1' ); require( _lockedStakeMinTime >= 1, 'Multiplier Min Time must be greater than or equal to 1' ); lockedStakeTimeGorMaxMultiplier = _lockedStakeTimeGorMaxMultiplier; lockedStakeMinTime = _lockedStakeMinTime; lockedStakeMinTimeStr = StringHelpers.uint2str(_lockedStakeMinTime); emit LockedStakeTimeForMaxMultiplier(lockedStakeTimeGorMaxMultiplier); emit LockedStakeMinTime(_lockedStakeMinTime); } function initializeDefault() external onlyByOwnerOrGovernance { lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit DefaultInitialization(); } function greylistAddress(address _address) external onlyByOwnerOrGovernance { greylist[_address] = !(greylist[_address]); } function unlockStakes() external onlyByOwnerOrGovernance { isLockedStakes = !isLockedStakes; } function setRewardRate(uint256 _newRate) external onlyByOwnerOrGovernance { rewardRate = _newRate; } function setOwnerAndTimelock(address _newOwner, address _newTimelock) external onlyByOwnerOrGovernance { ownerAddress = _newOwner; timelockAddress = _newTimelock; } function stakeFor(address who, uint256 amount) external override onlyPool { _stake(who, amount); } function stake(uint256 amount) external override { _stake(msg.sender, amount); } function stakeLocked(uint256 amount, uint256 secs) external override { _stakeLocked(msg.sender, amount, secs); } function totalSupply() external view override returns (uint256) { return _stakingTokenSupply; } function totalBoostedSupply() external view returns (uint256) { return _stakingTokenBoostedSupply; } // Total unlocked and locked liquidity tokens function balanceOf(address account) external view override returns (uint256) { return (_unlockedBalances[account]).add(_lockedBalances[account]); } // Total unlocked liquidity tokens function unlockedBalanceOf(address account) external view returns (uint256) { return _unlockedBalances[account]; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier function boostedBalanceOf(address account) external view returns (uint256) { return _boostedBalances[account]; } function _lockedStakesOf(address account) external view returns (LockedStake[] memory) { return _lockedStakes[account]; } function stakingDecimals() external view returns (uint256) { return stakingToken.decimals(); } function rewardsFor(address account) external view returns (uint256) { // You may have use earned() instead, because of the order in which the contract executes return rewards[account]; } function getRewardForDuration() external view override returns (uint256) { return rewardRate.mul(rewardsDuration).mul(crBoostMultiplier()).div( _PRICE_PRECISION ); } /** * Public */ function stakingMultiplier(uint256 secs) public view returns (uint256) { uint256 multiplier = uint256(_MULTIPLIER_BASE).add( secs.mul(lockedStakeMaxMultiplier.sub(_MULTIPLIER_BASE)).div( lockedStakeTimeGorMaxMultiplier ) ); if (multiplier > lockedStakeMaxMultiplier) multiplier = lockedStakeMaxMultiplier; return multiplier; } function crBoostMultiplier() public view returns (uint256) { uint256 multiplier = uint256(_MULTIPLIER_BASE).add( ( uint256(_MULTIPLIER_BASE).sub( _arthController.getGlobalCollateralRatio() ) ) .mul(crBoostMaxMultiplier.sub(_MULTIPLIER_BASE)) .div(_MULTIPLIER_BASE) ); return multiplier; } // Total locked liquidity tokens function lockedBalanceOf(address account) public view returns (uint256) { return _lockedBalances[account]; } function lastTimeRewardApplicable() public view override returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override returns (uint256) { if (_stakingTokenSupply == 0) { return rewardPerTokenStored; } else { return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(crBoostMultiplier()) .mul(1e18) .div(_PRICE_PRECISION) .div(_stakingTokenBoostedSupply) ); } } function getReward() public override nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.transfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function earned(address account) public view override returns (uint256) { return _boostedBalances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } /** * Internal. */ function _stake(address who, uint256 amount) internal nonReentrant notPaused updateReward(who) { require(amount > 0, 'Cannot stake 0'); require(greylist[who] == false, 'address has been greylisted'); // Pull the tokens from the staker TransferHelper.safeTransferFrom( address(stakingToken), msg.sender, address(this), amount ); // Staking token supply and boosted supply _stakingTokenSupply = _stakingTokenSupply.add(amount); _stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add(amount); // Staking token balance and boosted balance _unlockedBalances[who] = _unlockedBalances[who].add(amount); _boostedBalances[who] = _boostedBalances[who].add(amount); emit Staked(who, amount); } function _stakeLocked( address who, uint256 amount, uint256 secs ) internal nonReentrant notPaused updateReward(who) { require(amount > 0, 'Cannot stake 0'); require(secs > 0, 'Cannot wait for a negative number'); require(greylist[who] == false, 'address has been greylisted'); require( secs >= lockedStakeMinTime, StringHelpers.strConcat( 'Minimum stake time not met (', lockedStakeMinTimeStr, ')' ) ); require( secs <= lockedStakeTimeGorMaxMultiplier, 'You are trying to stake for too long' ); uint256 multiplier = stakingMultiplier(secs); uint256 boostedAmount = amount.mul(multiplier).div(_PRICE_PRECISION); _lockedStakes[who].push( LockedStake( keccak256(abi.encodePacked(who, block.timestamp, amount)), block.timestamp, amount, block.timestamp.add(secs), multiplier ) ); // Pull the tokens from the staker or the operator TransferHelper.safeTransferFrom( address(stakingToken), msg.sender, address(this), amount ); // Staking token supply and boosted supply _stakingTokenSupply = _stakingTokenSupply.add(amount); _stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add( boostedAmount ); // Staking token balance and boosted balance _lockedBalances[who] = _lockedBalances[who].add(amount); _boostedBalances[who] = _boostedBalances[who].add(boostedAmount); emit StakeLocked(who, amount, secs); } // If the period expired, renew it function _retroCatchUp() internal { // Failsafe check require(block.timestamp > periodFinish, 'Period has not expired yet!'); // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 numPeriodsElapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period uint256 balance = rewardsToken.balanceOf(address(this)); require( rewardRate .mul(rewardsDuration) .mul(crBoostMultiplier()) .mul(numPeriodsElapsed + 1) .div(_PRICE_PRECISION) <= balance, 'Not enough ARTHX available for rewards!' ); // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish.add( (numPeriodsElapsed.add(1)).mul(rewardsDuration) ); rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); emit RewardsPeriodRenewed(address(stakingToken)); } /* // This notifies people that the reward is being changed function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) { // Needed to make compiler happy // if (block.timestamp >= periodFinish) { // rewardRate = reward.mul(crBoostMultiplier()).div(rewardsDuration).div(_PRICE_PRECISION); // } else { // uint256 remaining = periodFinish.sub(block.timestamp); // uint256 leftover = remaining.mul(rewardRate); // rewardRate = reward.mul(crBoostMultiplier()).add(leftover).div(rewardsDuration).div(_PRICE_PRECISION); // } // // Ensure the provided reward amount is not more than the balance in the contract. // // This keeps the reward rate in the right range, preventing overflows due to // // very high values of rewardRate in the earned and rewardsPerToken functions; // // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. // uint balance = rewardsToken.balanceOf(address(this)); // require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); // lastUpdateTime = block.timestamp; // periodFinish = block.timestamp.add(rewardsDuration); // emit RewardAdded(reward); } */ }
Returns the remainder of dividing two unsigned integers, with a division by zero flag. _Available since v3.4._/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); }
12,593,409
pragma solidity ^0.5.8; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() public { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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 make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /// @title Main contract for WrappedNFT. This contract converts any NFT between the ERC721 standard and the /// ERC20 standard by locking NFT's into the contract and minting 1:1 backed ERC20 tokens, that /// can then be redeemed for NFTs's when desired. /// @notice When wrapping an NFT, you get a generic WNFT token. Since the WNFT token is generic, it has no /// no information about which specific NFT you submitted besides the originating NFT's contract address, so /// you will most likely not receive the same NFT back when redeeming the token unless you specify that NFT's /// ID, although you are guaranteed that it will be from the same NFT contract address. The token only entitles /// you to receive *an* NFT from that NFT contract in return, not necessarily the *same* NFT in return. A /// different user can submit their own WNFT tokens to the contract and withdraw the NFT that you originally /// deposited. WNFT tokens have no information about which NFT was originally deposited to mint WNFT besides /// which NFT contract it originated from - this is due to the very nature of the ERC20 standard being fungible, /// and the ERC721 standard being nonfungible. contract WrappedNFT is IERC20, ReentrancyGuard { // OpenZeppelin's SafeMath library is used for all arithmetic operations to avoid overflows/underflows. using SafeMath for uint256; /* ****** */ /* EVENTS */ /* ****** */ /// @dev This event is fired when a user deposits an NFT into the contract in exchange /// for an equal number of WNFT ERC20 tokens. /// @param nftId The NFT id of the NFT that was deposited into the contract. event DepositNFTAndMintToken( uint256 nftId ); /// @dev This event is fired when a user deposits WNFT ERC20 tokens into the contract in exchange /// for an equal number of locked NFTs. /// @param nftId The NF id of the NFT that was withdrawn from the contract. event BurnTokenAndWithdrawNFT( uint256 nftId ); /* ******* */ /* STORAGE */ /* ******* */ /// @dev An Array containing all of the NFTs that are locked in the contract, backing /// WNFT ERC20 tokens 1:1 /// @notice Some of the NFTs in this array were indeed deposited to the contract, but they /// are no longer held by the contract. This is because burnTokensAndWithdrawNfts() allows a /// user to withdraw an NFT "out of order". Since it would be prohibitively expensive to /// shift the entire array once we've withdrawn a single element, we instead maintain the /// mapping nftIsDepositedInContract to determine whether an element is still contained in /// the contract or not. uint256[] private depositedNftsArray; /// @dev A mapping keeping track of which nftIDs are currently contained within the contract. /// @notice We cannot rely on depositedNftsArray as the source of truth as to which NFTs are /// deposited in the contract. This is because burnTokensAndWithdrawNfts() allows a user to /// withdraw an NFT "out of order" of the order that they are stored in the array. Since it /// would be prohibitively expensive to shift the entire array once we've withdrawn a single /// element, we instead maintain this mapping to determine whether an element is still contained /// in the contract or not. mapping (uint256 => bool) public nftIsDepositedInContract; /* ********* */ /* CONSTANTS */ /* ********* */ /// @dev The metadata details about the "Wrapped NFT" WNFT ERC20 token. uint8 constant public decimals = 18; string public name = 'Wrapped NFT'; string public symbol = 'WNFT'; /// @dev The address of official NFT contract that stores the metadata about each NFT. /// @notice The contract creator is not capable of changing the address of the NFTCore contract /// once the contract has been deployed. address public nftCoreAddress; NFTCoreContract nftCore; /// @dev Addresses that begin as whitelisted in all WNFT contracts that are created /// by this factory. The WNFT contracts begin with an allowance of UINT256_MAX for /// these addresses for all users, but any user can subsequently override that /// allowance if they wish. address public wyvernTokenTransferProxyAddress; address public wrappedNFTLiquidationProxyAddress; address public uniswapFactoryAddress; /* ********* */ /* FUNCTIONS */ /* ********* */ /// @notice Allows a user to lock NFTs in the contract in exchange for an equal number /// of WCK ERC20 tokens. /// @param _nftIds The ids of the NFTs that will be locked into the contract. /// @notice If the NFT contract does not implement onERC721Received() or approveAll(), then the /// user must first call approve() in the NFT's Core contract on each NFT that they wish to /// deposit before calling depositNftsAndMintTokens(). If the contract implements approveAll() but /// not onERC721Received, then the user simply needs to call approveAll() once for this contract. function depositNftsAndMintTokens(uint256[] calldata _nftIds) external nonReentrant { require(_nftIds.length > 0, 'you must submit an array with at least one element'); for(uint i = 0; i < _nftIds.length; i++){ uint256 nftToDeposit = _nftIds[i]; require(msg.sender == nftCore.ownerOf(nftToDeposit), 'you do not own this NFT'); nftCore.transferFrom(msg.sender, address(this), nftToDeposit); _pushNft(nftToDeposit); emit DepositNFTAndMintToken(nftToDeposit); } _mint(msg.sender, (_nftIds.length).mul(10**18)); } /// @notice Allows a user to burn WNFT ERC20 tokens in exchange for an equal number of locked /// NFTs. /// @param _nftIds The IDs of the NFTs that the user wishes to withdraw. If the user submits 0 /// as the ID for any NFT, the contract uses the last NFT in the array for that NFT. /// @param _destinationAddresses The addresses that the withdrawn NFTs will be sent to (this allows /// anyone to "airdrop" NFTs to addresses that they do not own in a single transaction). function burnTokensAndWithdrawNfts(uint256[] calldata _nftIds, address[] calldata _destinationAddresses) external nonReentrant { require(_nftIds.length == _destinationAddresses.length, 'you did not provide a destination address for each of the NFTs you wish to withdraw'); require(_nftIds.length > 0, 'you must submit an array with at least one element'); uint256 numTokensToBurn = _nftIds.length; uint256 numTokensToBurnInWei = numTokensToBurn.mul(10**18); require(balanceOf(msg.sender) >= numTokensToBurnInWei, 'you do not own enough ERC20 tokens to withdraw this many NFTs'); _burn(msg.sender, numTokensToBurnInWei); for(uint i = 0; i < numTokensToBurn; i++){ uint256 nftToWithdraw = _nftIds[i]; if(nftToWithdraw == 0){ nftToWithdraw = _popNft(); } else { require(nftIsDepositedInContract[nftToWithdraw] == true, 'this NFT has already been withdrawn'); require(address(this) == nftCore.ownerOf(nftToWithdraw), 'the contract does not own this NFT'); nftIsDepositedInContract[nftToWithdraw] = false; } nftCore.transferFrom(address(this), _destinationAddresses[i], nftToWithdraw); emit BurnTokenAndWithdrawNFT(nftToWithdraw); } } /// @notice Adds a locked NFT to the end of the array /// @param _nftId The id of the NFT that will be locked into the contract. function _pushNft(uint256 _nftId) internal { depositedNftsArray.push(_nftId); nftIsDepositedInContract[_nftId] = true; } /// @notice Removes an unlocked NFT from the end of the array /// @notice The reason that this function must check if the nftIsDepositedInContract /// is that the burnTokensAndWithdrawNfts() function allows a user to withdraw an NFT /// from the array "out of order" of the order that they entered the array.. /// @return The id of the NFT that will be unlocked from the contract. function _popNft() internal returns(uint256){ require(depositedNftsArray.length > 0, 'there are no NFTs in the array'); uint256 nftId = depositedNftsArray[depositedNftsArray.length - 1]; depositedNftsArray.length--; while(nftIsDepositedInContract[nftId] == false){ nftId = depositedNftsArray[depositedNftsArray.length - 1]; depositedNftsArray.length--; } nftIsDepositedInContract[nftId] = false; return nftId; } /// @notice Removes any NFTs that exist in the array but are no longer held in the /// contract, which happens if the first few NFTs have previously been withdrawn /// out of order using the burnTokensAndWithdrawNfts() function. /// @notice This function exists to prevent a griefing attack where a malicious attacker /// could call burnTokensAndWithdrawNfts() on a large number of specific NFTs at the /// front of the array, causing the while-loop in _popNft to always run out of gas. /// @notice It is unclear whether this griefing attack is even possible, because when a /// user is forced to traverse the array, they delete an item at each step of walking the /// array, so the repeated gas refunds may be sufficient to cover the repeated walking of /// the array. /// @param _numSlotsToCheck The number of slots to check in the array. function batchRemoveWithdrawnNFTsFromStorage(uint256 _numSlotsToCheck) external { require(_numSlotsToCheck <= depositedNftsArray.length, 'you are trying to batch remove more slots than exist in the array'); uint256 arrayIndex = depositedNftsArray.length; for(uint i = 0; i < _numSlotsToCheck; i++){ arrayIndex = arrayIndex.sub(1); uint256 nftId = depositedNftsArray[arrayIndex]; if(nftIsDepositedInContract[nftId] == false){ depositedNftsArray.length--; } else { return; } } } /// @dev If a user sends an NFT from nftCoreContract directly to this contract using a /// transfer function that implements onERC721Received, then we can simply mint a token /// for them here rather than having them call approve() and then have them call /// depositNftsAndMintTokens(). /// @notice The contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` to indicate that /// this contract is written in such a way to be prepared to receive ERC721 tokens. function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4) { require(msg.sender == nftCoreAddress, 'you can only mint tokens if the ERC721 token originates from nftCoreContract'); _pushNft(_tokenId); _mint(_from, 10**18); emit DepositNFTAndMintToken(_tokenId); return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } /// @notice The contract creator is not capable of changing any of the hardcoded addresses /// once the contract is deployed. /// @notice This contract whitelists three addresses (wyvernTokenTransferProxyAddress, /// uniswapExchange, and wrappedNFTLiquidationProxyAddress) for easier UX for users using /// OpenSea for the WNFTs. It accomplishes this by starting every user's account with an /// allowance of UINT256_MAX for these three addresses. However, any user can subsequently /// override this allowance if they wish by either calling approve() or calling /// decreaseAllowance(). constructor(address _nftCoreAddress, address _uniswapFactoryAddress, address _wyvernTokenTransferProxyAddress, address _wrappedNFTLiquidationProxyAddress) public { nftCore = NFTCoreContract(_nftCoreAddress); nftCoreAddress = _nftCoreAddress; name = string(abi.encodePacked('Wrapped ', nftCore.name())); symbol = string(abi.encodePacked('W', nftCore.symbol())); // Modified _transfer() auto-adds max allowance to whitelisted addresses the first // time that someone receives WNFT tokens, but not again. Users can subsequently // revoke this approval by calling approve() or decreaseAllowance(). This is added // for easier UX for users using OpenSea for their WNFTs. wyvernTokenTransferProxyAddress = _wyvernTokenTransferProxyAddress; wrappedNFTLiquidationProxyAddress = _wrappedNFTLiquidationProxyAddress; uniswapFactoryAddress = _uniswapFactoryAddress; } /// @dev We revert on any payment to the fallback function, since any ether sent directly to /// this contract would be lost forever. function() external payable { revert("This contract does not accept direct payments"); } /* *********************************************** */ /* ERC20_With_Whitelisted_Addresses Implementation */ /* *********************************************** */ mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; mapping (address => bool) private _haveAddedAllowancesForWhitelistedAddresses; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * 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 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /// @notice The _trasfer() function is modified to set max allowance for whitelisted /// addresses the first time that a user receives any WNFT tokens. They can subsequently /// revoke this approval by calling approve() or decreaseAllowance(), and the contract /// will not auto-add the whitelisted contract's allowance again. This is added /// for easier UX for users using OpenSea for their WNFTs. /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); // Modified _transfer() auto-adds max allowance to whitelisted addresses the first // time that someone receives WNFT tokens, but not again. Users can subsequently // revoke this approval by calling approve() or decreaseAllowance(). This is added // for easier UX for users using OpenSea for their WNFTs. if(_haveAddedAllowancesForWhitelistedAddresses[to] == false){ if(uniswapFactoryAddress != address(0)){ address uniswapExchangeAddress = UniswapFactory(uniswapFactoryAddress).getExchange(address(this)); if(uniswapExchangeAddress != address(0)){ _allowed[to][uniswapExchangeAddress] = ~uint256(0); } } if(wyvernTokenTransferProxyAddress != address(0)){ _allowed[to][wyvernTokenTransferProxyAddress] = ~uint256(0); } if(wrappedNFTLiquidationProxyAddress != address(0)){ _allowed[to][wrappedNFTLiquidationProxyAddress] = ~uint256(0); } _haveAddedAllowancesForWhitelistedAddresses[to] = true; } _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } /// @title Interface for interacting with the NFT Core contract contract NFTCoreContract { function name() external pure returns (string memory _name); function symbol() external pure returns (string memory _symbol); function ownerOf(uint256 _tokenId) public view returns (address owner); function transferFrom(address _from, address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function approve(address _to, uint256 _tokenId) external; } /// @title Interface for interacting with the UniswapFactory contract contract UniswapFactory { function getExchange(address token) external view returns (address exchange); function getToken(address exchange) external view returns (address token); }
Adds a locked NFT to the end of the array _nftId The id of the NFT that will be locked into the contract.
function _pushNft(uint256 _nftId) internal { depositedNftsArray.push(_nftId); nftIsDepositedInContract[_nftId] = true; }
12,809,078
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /// @title Interface to interact with Bubbles contract. interface IBubbles { function mint(address recipient, uint256 amount) external; } /// @author The Axolittles Team /// @title Contract for staking axos to receive $BUBBLE contract AxolittlesStaking is Ownable { address public AXOLITTLES = 0xf36446105fF682999a442b003f2224BcB3D82067; address public TOKEN = 0x58f46F627C88a3b217abc80563B9a726abB873ba; bool public stakingPaused; bool public isPositiveSum = true; uint64 internal stakeTarget = 6000; // Amount of $BUBBLE generated each block, contains 18 decimals. uint256 public emissionPerBlock = 15000000000000000; uint256 internal totalStaked; /// @notice struct per owner address to store: /// a. previously calced rewards, b. number staked, and block since last reward calculation. struct staker { // number of axolittles currently staked uint256 numStaked; // block since calcedReward was last updated uint256 blockSinceLastCalc; // previously calculated rewards uint256 calcedReward; } mapping(address => staker) public stakers; mapping(uint256 => address) public stakedAxos; constructor() {} event Stake(address indexed owner, uint256[] tokenIds); event Unstake(address indexed owner, uint256[] tokenIds); event Claim(address indexed owner, uint256 totalReward); event SetStakingPaused(bool _stakingPaused); event SetPositiveSum(bool _isPositiveSum, uint64 stakeTarget); event AdminTransfer(uint256[] tokenIds); /// @notice Function to stake axos. Transfers axos from sender to this contract. function stake(uint256[] memory tokenIds) external { require(!stakingPaused, "Staking is paused"); require(tokenIds.length > 0, "Nothing to stake"); stakers[msg.sender].calcedReward = _checkRewardInternal(msg.sender); stakers[msg.sender].numStaked += tokenIds.length; stakers[msg.sender].blockSinceLastCalc = block.number; totalStaked += tokenIds.length; for (uint256 i = 0; i < tokenIds.length; i++) { IERC721(AXOLITTLES).transferFrom(msg.sender, address(this), tokenIds[i]); stakedAxos[tokenIds[i]] = msg.sender; } emit Stake(msg.sender, tokenIds); } /// @notice Function to unstake axos. Transfers axos from this contract back to sender address. function unstake(uint256[] memory tokenIds) external { require(tokenIds.length > 0, "Nothing to unstake"); require(tokenIds.length <= stakers[msg.sender].numStaked, "Not your axo!"); stakers[msg.sender].calcedReward = _checkRewardInternal(msg.sender); stakers[msg.sender].numStaked -= tokenIds.length; stakers[msg.sender].blockSinceLastCalc = block.number; totalStaked -= tokenIds.length; for (uint256 i = 0; i < tokenIds.length; i++) { require(msg.sender == stakedAxos[tokenIds[i]], "Not your axo!"); delete stakedAxos[tokenIds[i]]; IERC721(AXOLITTLES).transferFrom(address(this), msg.sender, tokenIds[i]); } emit Unstake(msg.sender, tokenIds); } /// @notice Function to claim $BUBBLE. function claim() external { //todo: ownership and other checks here uint256 totalReward = _checkRewardInternal(msg.sender); require(totalReward > 0, "Nothing to claim"); stakers[msg.sender].blockSinceLastCalc = block.number; stakers[msg.sender].calcedReward = 0; IBubbles(TOKEN).mint(msg.sender, totalReward); emit Claim(msg.sender, totalReward); } /// @notice Function to check rewards per staker address function checkReward(address _staker_address) external view returns (uint256) { return _checkRewardInternal(_staker_address); } /// @notice Internal function to check rewards per staker address function _checkRewardInternal(address _staker_address) internal view returns (uint256) { uint256 totalReward = stakers[_staker_address].calcedReward + stakers[_staker_address].numStaked * emissionPerBlock * (block.number - stakers[_staker_address].blockSinceLastCalc); if (isPositiveSum) { totalReward *= (1 + (totalStaked / stakeTarget)); } return totalReward; } //ADMIN FUNCTIONS /// @notice Function to change address of NFT function setAxolittlesAddress(address _axolittlesAddress) external onlyOwner { AXOLITTLES = _axolittlesAddress; } /// @notice Function to change address of reward token function setTokenAddress(address _tokenAddress) external onlyOwner { TOKEN = _tokenAddress; } /// @notice Function to change amount of $BUBBLE generated each block per axo function setEmissionPerBlock(uint256 _emissionPerBlock) external onlyOwner { emissionPerBlock = _emissionPerBlock; } /// @notice Function to prevent further staking function setStakingPaused(bool _isPaused) external onlyOwner { stakingPaused = _isPaused; emit SetStakingPaused(stakingPaused); } ///@notice Function to turn on positive sum staking function setPositiveSum(bool _isPositiveSum, uint64 _stakeTarget) external onlyOwner { isPositiveSum = _isPositiveSum; stakeTarget = _stakeTarget; emit SetPositiveSum(isPositiveSum, stakeTarget); } /// @notice Function for admin to transfer axos out of contract back to original owner function adminTransfer(uint256[] memory tokenIds) external onlyOwner { require(tokenIds.length > 0, "Nothing to unstake"); totalStaked -= tokenIds.length; for (uint256 i = 0; i < tokenIds.length; i++) { address owner = stakedAxos[tokenIds[i]]; require(owner != address(0), "Axo not found"); stakers[owner].numStaked--; delete stakedAxos[tokenIds[i]]; IERC721(AXOLITTLES).transferFrom(address(this), owner, tokenIds[i]); } emit AdminTransfer(tokenIds); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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 ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _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 v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // 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 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
Function to change address of reward token
function setTokenAddress(address _tokenAddress) external onlyOwner { TOKEN = _tokenAddress; }
1,545,608
/** * Copyright 2017–2018, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * 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 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract UnlimitedAllowanceToken is StandardToken { uint internal constant MAX_UINT = 2**256 - 1; /// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance, and to add revert reasons. /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transferFrom( address _from, address _to, uint256 _value) public returns (bool) { uint allowance = allowed[_from][msg.sender]; require(_value <= balances[_from], "insufficient balance"); require(_value <= allowance, "insufficient allowance"); require(_to != address(0), "token burn not allowed"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); if (allowance < MAX_UINT) { allowed[_from][msg.sender] = allowance.sub(_value); } emit Transfer(_from, _to, _value); return true; } /// @dev Transfer token for a specified address, modified to add revert reasons. /// @param _to The address to transfer to. /// @param _value The amount to be transferred. function transfer( address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "insufficient balance"); require(_to != address(0), "token burn not allowed"); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } } contract BZRxToken is UnlimitedAllowanceToken, DetailedERC20, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); event LockingFinished(); bool public mintingFinished = false; bool public lockingFinished = false; mapping (address => bool) public minters; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(minters[msg.sender]); _; } modifier isLocked() { require(!lockingFinished); _; } constructor() public DetailedERC20( "bZx Protocol Token", "BZRX", 18 ) { minters[msg.sender] = true; } /// @dev ERC20 transferFrom function /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transferFrom( address _from, address _to, uint256 _value) public returns (bool) { if (lockingFinished || minters[msg.sender]) { return super.transferFrom( _from, _to, _value ); } revert("this token is locked for transfers"); } /// @dev ERC20 transfer function /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transfer( address _to, uint256 _value) public returns (bool) { if (lockingFinished || minters[msg.sender]) { return super.transfer( _to, _value ); } revert("this token is locked for transfers"); } /// @dev Allows minter to initiate a transfer on behalf of another spender /// @param _spender Minter with permission to spend. /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function minterTransferFrom( address _spender, address _from, address _to, uint256 _value) public hasMintPermission canMint returns (bool) { require(canTransfer( _spender, _from, _value), "canTransfer is false"); require(_to != address(0), "token burn not allowed"); uint allowance = allowed[_from][_spender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); if (allowance < MAX_UINT) { allowed[_from][_spender] = allowance.sub(_value); } emit Transfer(_from, _to, _value); return true; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { require(_to != address(0), "token burn not allowed"); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint { mintingFinished = true; emit MintFinished(); } /** * @dev Function to stop locking token. * @return True if the operation was successful. */ function finishLocking() public onlyOwner isLocked { lockingFinished = true; emit LockingFinished(); } /** * @dev Function to add minter address. * @return True if the operation was successful. */ function addMinter( address _minter) public onlyOwner canMint { minters[_minter] = true; } /** * @dev Function to remove minter address. * @return True if the operation was successful. */ function removeMinter( address _minter) public onlyOwner canMint { minters[_minter] = false; } /** * @dev Function to check balance and allowance for a spender. * @return True transfer will succeed based on balance and allowance. */ function canTransfer( address _spender, address _from, uint256 _value) public view returns (bool) { return ( balances[_from] >= _value && (_spender == _from || allowed[_from][_spender] >= _value) ); } } interface WETHInterface { function deposit() external payable; function withdraw(uint wad) external; } interface PriceFeed { function read() external view returns (bytes32); } contract BZRxTokenSale is Ownable { using SafeMath for uint256; struct TokenPurchases { uint totalETH; uint totalTokens; uint totalTokenBonus; } event BonusChanged(uint oldBonus, uint newBonus); event TokenPurchase(address indexed buyer, uint ethAmount, uint ethRate, uint tokensReceived); event SaleOpened(uint bonusMultiplier); event SaleClosed(uint bonusMultiplier); bool public saleClosed = true; address public bZRxTokenContractAddress; // BZRX Token address public bZxVaultAddress; // bZx Vault address public wethContractAddress; // WETH Token address public priceContractAddress; // MakerDao Medianizer price feed // The current token bonus offered to purchasers (example: 110 == 10% bonus) uint public bonusMultiplier; uint public ethRaised; address[] public purchasers; mapping (address => TokenPurchases) public purchases; bool public whitelistEnforced = false; mapping (address => uint) public whitelist; modifier saleOpen() { require(!saleClosed, "sale is closed"); _; } modifier whitelisted(address user, uint value) { require(canPurchaseAmount(user, value), "not whitelisted"); _; } constructor( address _bZRxTokenContractAddress, address _bZxVaultAddress, address _wethContractAddress, address _priceContractAddress, uint _bonusMultiplier) public { require(_bonusMultiplier > 100); bZRxTokenContractAddress = _bZRxTokenContractAddress; bZxVaultAddress = _bZxVaultAddress; wethContractAddress = _wethContractAddress; priceContractAddress = _priceContractAddress; bonusMultiplier = _bonusMultiplier; } function() public payable { if (msg.sender != wethContractAddress) buyToken(); } function buyToken() public payable saleOpen whitelisted(msg.sender, msg.value) returns (bool) { require(msg.value > 0, "no ether sent"); uint ethRate = getEthRate(); ethRaised += msg.value; uint tokenAmount = msg.value // amount of ETH sent .mul(ethRate).div(10**18) // curent ETH/USD rate .mul(1000).div(73); // fixed price per token $0.073 uint tokenAmountAndBonus = tokenAmount .mul(bonusMultiplier).div(100); TokenPurchases storage purchase = purchases[msg.sender]; if (purchase.totalETH == 0) { purchasers.push(msg.sender); } purchase.totalETH += msg.value; purchase.totalTokens += tokenAmountAndBonus; purchase.totalTokenBonus += tokenAmountAndBonus.sub(tokenAmount); emit TokenPurchase(msg.sender, msg.value, ethRate, tokenAmountAndBonus); return BZRxToken(bZRxTokenContractAddress).mint( msg.sender, tokenAmountAndBonus ); } // conforms to ERC20 transferFrom function for BZRX token support function transferFrom( address _from, address _to, uint256 _value) public saleOpen returns (bool) { require(msg.sender == bZxVaultAddress, "only the bZx vault can call this function"); if (BZRxToken(bZRxTokenContractAddress).canTransfer(msg.sender, _from, _value)) { return BZRxToken(bZRxTokenContractAddress).minterTransferFrom( msg.sender, _from, _to, _value ); } else { uint ethRate = getEthRate(); uint wethValue = _value // amount of BZRX .mul(73).div(1000) // fixed price per token $0.073 .mul(10**18).div(ethRate); // curent ETH/USD rate require(canPurchaseAmount(_from, wethValue), "not whitelisted"); require(StandardToken(wethContractAddress).transferFrom( _from, this, wethValue ), "weth transfer failed"); ethRaised += wethValue; TokenPurchases storage purchase = purchases[_from]; if (purchase.totalETH == 0) { purchasers.push(_from); } purchase.totalETH += wethValue; purchase.totalTokens += _value; return BZRxToken(bZRxTokenContractAddress).mint( _to, _value ); } } function closeSale( bool _closed) public onlyOwner returns (bool) { saleClosed = _closed; if (_closed) emit SaleClosed(bonusMultiplier); else emit SaleOpened(bonusMultiplier); return true; } function changeBZRxTokenContract( address _bZRxTokenContractAddress) public onlyOwner returns (bool) { bZRxTokenContractAddress = _bZRxTokenContractAddress; return true; } function changeBZxVault( address _bZxVaultAddress) public onlyOwner returns (bool) { bZxVaultAddress = _bZxVaultAddress; return true; } function changeWethContract( address _wethContractAddress) public onlyOwner returns (bool) { wethContractAddress = _wethContractAddress; return true; } function changePriceContract( address _priceContractAddress) public onlyOwner returns (bool) { priceContractAddress = _priceContractAddress; return true; } function changeBonusMultiplier( uint _newBonusMultiplier) public onlyOwner returns (bool) { require(bonusMultiplier != _newBonusMultiplier && _newBonusMultiplier > 100); emit BonusChanged(bonusMultiplier, _newBonusMultiplier); bonusMultiplier = _newBonusMultiplier; return true; } function unwrapEth() public onlyOwner returns (bool) { uint balance = StandardToken(wethContractAddress).balanceOf.gas(4999)(this); if (balance == 0) return false; WETHInterface(wethContractAddress).withdraw(balance); return true; } function transferEther( address _to, uint _value) public onlyOwner returns (bool) { uint amount = _value; if (amount > address(this).balance) { amount = address(this).balance; } return (_to.send(amount)); } function transferToken( address _tokenAddress, address _to, uint _value) public onlyOwner returns (bool) { uint balance = StandardToken(_tokenAddress).balanceOf.gas(4999)(this); if (_value > balance) { return StandardToken(_tokenAddress).transfer( _to, balance ); } else { return StandardToken(_tokenAddress).transfer( _to, _value ); } } function enforceWhitelist( bool _isEnforced) public onlyOwner returns (bool) { whitelistEnforced = _isEnforced; return true; } function setWhitelist( address[] _users, uint[] _values) public onlyOwner returns (bool) { require(_users.length == _values.length, "users and values count mismatch"); for (uint i=0; i < _users.length; i++) { whitelist[_users[i]] = _values[i]; } return true; } function getEthRate() public view returns (uint) { return uint(PriceFeed(priceContractAddress).read()); } function canPurchaseAmount( address _user, uint _value) public view returns (bool) { if (!whitelistEnforced || (whitelist[_user] > 0 && purchases[_user].totalETH.add(_value) <= whitelist[_user])) { return true; } else { return false; } } }
Function to add minter address. return True if the operation was successful./
function addMinter( address _minter) public onlyOwner canMint { minters[_minter] = true; }
5,772,162
./full_match/1/0xc8f818729Bf05D6239a407bAa8370DeC8e0c01e9/sources/contracts/traits/traitregistry/ECRegistryV3c.sol
This will only emit event if there was actually a state change! Returns: wasSet - was there any state change Reason: this is being called many times from the various random trait dropper contracts
function _setTrait(uint16 traitID, uint16 tokenId, bool _value) internal returns(bool wasSet) { bool emitvalue = _value; (uint16 byteNum, uint8 bitPos) = getByteAndBit(tokenId); if(traits[traitID].traitType == 1 || traits[traitID].traitType == 2) { _value = !_value; } if(_value) { wasSet = uint8(tokenData[traitID][byteNum] & 2**bitPos) == 0; if (wasSet) { tokenData[traitID][byteNum] = uint8(tokenData[traitID][byteNum] | 2**bitPos); emit tokenTraitChangeEvent(traitID, tokenId, emitvalue); } wasSet = uint8(tokenData[traitID][byteNum] & 2**bitPos) != 0; if (wasSet) { tokenData[traitID][byteNum] = uint8(tokenData[traitID][byteNum] & ~(2**bitPos)); emit tokenTraitChangeEvent(traitID, tokenId, emitvalue); } } }
2,999,487
./full_match/5/0x136B8Bf430867E50A311ece548b3b0c40eB05b23/sources/contracts/Gateway.sol
Function to retrieve all items
function getItems() public view returns (Item[] memory) { return items; }
1,884,885
./full_match/5/0x19E242DE333fB9091Bb88A1EA5e51f832016e1eb/sources/_thirdweb-dev/contracts/base/ERC721Drop.sol
Generative NFT logic Create a hash value using id, block number, address save hash in mappings
function _mintGenerative(address _to, uint256 _startTokenId, uint256 _qty) internal virtual { for(uint256 i = 0; i < _qty; i += 1) { uint256 _id = _startTokenId + i; bytes32 mintHash = keccak256(abi.encodePacked(_id, blockhash(block.number - 1), _to)); tokenToHash[_id] = mintHash; hashToToken[mintHash] = _id; } }
1,933,559
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./ERC721Min.sol"; contract OwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract PBGBNFT is Ownable, ERC721Min, ReentrancyGuard { using Strings for uint256; using SafeERC20 for IERC20; address public immutable proxyRegistryAddress; // opensea proxy mapping(address => bool) proxyToApproved; // proxy allowance for interaction with future contract string private _contractURI; string private _tokenBaseURI = ""; // SET TO THE METADATA URI address private treasuryAddress = 0xE6f84d92B4aB5E585c6f33364Aba8A29597D83C6; bool useBaseUriOnly = true; mapping(uint256 => string) public TokenURIMap; // allows for assigning individual/unique metada per token struct NftType { uint16 purchaseCount; uint16 maxPerAddress; uint16 maxPerMint; uint16 maxPerAddressForFive; uint16 maxMint; uint16 maxMintForOne; uint16 maxMintForFive; bool saleActive; uint256 price; uint256 priceForFive; mapping(address => uint256) PurchasesByAddress; string uri; } struct FeeRecipient { address recipient; uint256 basisPoints; } mapping(uint256 => FeeRecipient) public FeeRecipients; uint256 public feeRecipientCount; uint256 totalFeeBasisPoints; mapping(uint256 => NftType) public NftTypes; uint256 public nftTypeCount; bool public transferEnabled; mapping(uint256 => uint256) public NftIdToNftType; constructor() ERC721Min("PUSH BUTTON GET BANANA", "PBGB") { proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; } function totalSupply() external view returns(uint256) { return _owners.length; } // ** - CORE - ** // function buyOne(uint256 nftTypeId) external payable { require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED"); require(NftTypes[nftTypeId].price == msg.value, "INCORRECT_ETH"); require(NftTypes[nftTypeId].maxMintForOne > NftTypes[nftTypeId].purchaseCount, "EXCEED_MAX_SALE_SUPPLY"); require(NftTypes[nftTypeId].maxPerAddress == 0 || NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] < NftTypes[nftTypeId].maxPerAddress, "EXCEED_MAX_PER_USER"); NftIdToNftType[_owners.length] = nftTypeId; _mintMin(); if (NftTypes[nftTypeId].maxPerAddress > 0) NftTypes[nftTypeId].PurchasesByAddress[_msgSender()]++; NftTypes[nftTypeId].purchaseCount++; } function buyFive(uint256 nftTypeId) external payable { require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED"); require(NftTypes[nftTypeId].priceForFive == msg.value, "INCORRECT_ETH"); require(NftTypes[nftTypeId].maxMintForFive > NftTypes[nftTypeId].purchaseCount, "EXCEED_MAX_SALE_SUPPLY"); require(NftTypes[nftTypeId].maxPerAddress == 0 || NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] < NftTypes[nftTypeId].maxPerAddressForFive, "EXCEED_MAX_PER_USER"); NftIdToNftType[_owners.length] = nftTypeId; _mintMin(); NftIdToNftType[_owners.length] = nftTypeId; _mintMin(); NftIdToNftType[_owners.length] = nftTypeId; _mintMin(); NftIdToNftType[_owners.length] = nftTypeId; _mintMin(); NftIdToNftType[_owners.length] = nftTypeId; _mintMin(); if (NftTypes[nftTypeId].maxPerAddress > 0) { NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] += 5; } NftTypes[nftTypeId].purchaseCount += 5; } function buy(uint256 nftTypeId, uint16 amount) external payable { require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED"); require(NftTypes[nftTypeId].price * amount == msg.value, "INCORRECT_ETH"); require(NftTypes[nftTypeId].maxMint > NftTypes[nftTypeId].purchaseCount + amount, "EXCEED_MAX_SALE_SUPPLY"); require(amount < NftTypes[nftTypeId].maxPerMint, "EXCEED_MAX_PER_MINT"); require(NftTypes[nftTypeId].maxPerAddress > 0 || NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] + amount - 1 < NftTypes[nftTypeId].maxPerAddress, "EXCEED_MAX_PER_USER"); for (uint256 i = 0; i < amount; i++) { NftIdToNftType[_owners.length] = nftTypeId; _mintMin(); } NftTypes[nftTypeId].purchaseCount += amount; } // ** - PROXY - ** // function mintOne(address receiver, uint256 nftTypeId) external onlyProxy { NftIdToNftType[_owners.length] = nftTypeId; _mintMin2(receiver); } function mintFive(address receiver, uint256 nftTypeId) external onlyProxy { NftIdToNftType[_owners.length] = nftTypeId; _mintMin2(receiver); NftIdToNftType[_owners.length] = nftTypeId; _mintMin2(receiver); NftIdToNftType[_owners.length] = nftTypeId; _mintMin2(receiver); NftIdToNftType[_owners.length] = nftTypeId; _mintMin2(receiver); NftIdToNftType[_owners.length] = nftTypeId; _mintMin2(receiver); } function mint(address receiver, uint256 nftTypeId, uint256 tokenQuantity) external onlyProxy { for (uint256 i = 0; i < tokenQuantity; i++) { NftIdToNftType[_owners.length] = nftTypeId; _mintMin2(receiver); } } function getNftTokenIdForUserForNftType(address user, uint nftType) external view returns(uint) { uint result; uint bal = balanceOf(user); for (uint x = 0; x < bal; x++) { uint id = tokenOfOwnerByIndex(user, x); if (NftIdToNftType[id] == nftType) { return id; } } return result; } function userHasNftType(address user, uint nftType) external view returns(bool) { uint bal = balanceOf(user); for (uint x = 0; x < bal; x++) { uint id = tokenOfOwnerByIndex(user, x); if (NftIdToNftType[id] == nftType) return true; } return false; } // ** - ADMIN - ** // function addFeeRecipient(address recipient, uint256 basisPoints) external onlyOwner { feeRecipientCount++; FeeRecipients[feeRecipientCount].recipient = recipient; FeeRecipients[feeRecipientCount].basisPoints = basisPoints; totalFeeBasisPoints += basisPoints; } function editFeeRecipient(uint256 id, address recipient, uint256 basisPoints) external onlyOwner { require(id <= feeRecipientCount, "INVALID_ID"); totalFeeBasisPoints = totalFeeBasisPoints - FeeRecipients[feeRecipientCount].basisPoints + basisPoints; FeeRecipients[feeRecipientCount].recipient = recipient; FeeRecipients[feeRecipientCount].basisPoints = basisPoints; } function distributeETH() external nonReentrant { require(treasuryAddress != address(0), "TREASURY_NOT_SET"); uint256 bal = address(this).balance; for(uint256 x = 1; x <= feeRecipientCount; x++) { uint256 amount = bal * FeeRecipients[x].basisPoints / totalFeeBasisPoints; amount = amount > address(this).balance ? address(this).balance : amount; (bool sent, ) = FeeRecipients[x].recipient.call{value: amount}(""); require(sent, "FAILED_SENDING_FUNDS"); } emit DistributeETH(_msgSender(), bal); } function withdrawETH() external nonReentrant { require(treasuryAddress != address(0), "TREASURY_NOT_SET"); uint256 bal = address(this).balance; (bool sent, ) = treasuryAddress.call{value: bal}(""); require(sent, "FAILED_SENDING_FUNDS"); emit WithdrawETH(_msgSender(), bal); } function withdraw(address _token) external nonReentrant { require(_msgSender() == owner() || _msgSender() == treasuryAddress, "NOT_ALLOWED"); require(treasuryAddress != address(0), "TREASURY_NOT_SET"); IERC20(_token).safeTransfer( treasuryAddress, IERC20(_token).balanceOf(address(this)) ); } function gift(uint256 nftTypeId, address[] calldata receivers, uint256[] memory amounts) external onlyOwner { for (uint256 x = 0; x < receivers.length; x++) { for (uint256 i = 0; i < amounts[x]; i++) { NftIdToNftType[_owners.length] = nftTypeId; _mintMin2(receivers[x]); } } } // ** - NFT Types - ** // function addNftType(uint16 _maxMint, uint16 _maxPerMint, uint256 _price, uint16 _maxPerAddress, bool _saleActive, string calldata _uri) external onlyOwner { nftTypeCount++; NftTypes[nftTypeCount].maxMint = _maxMint+1; NftTypes[nftTypeCount].maxMintForOne = _maxMint; NftTypes[nftTypeCount].maxMintForFive = _maxMint-1; NftTypes[nftTypeCount].maxPerMint = _maxPerMint; NftTypes[nftTypeCount].price = _price; NftTypes[nftTypeCount].priceForFive = _price * 5; NftTypes[nftTypeCount].maxPerAddress = _maxPerAddress > 0 ? _maxPerAddress : NftTypes[nftTypeCount].maxPerAddress; NftTypes[nftTypeCount].maxPerAddressForFive = _maxPerAddress > 4 ? _maxPerAddress - 4 : NftTypes[nftTypeCount].maxPerAddress; NftTypes[nftTypeCount].saleActive = _saleActive; NftTypes[nftTypeCount].uri = _uri; } function toggleSaleActive(uint256 nftTypeId) external onlyOwner { NftTypes[nftTypeId].saleActive = !NftTypes[nftTypeId].saleActive; } function setMaxPerMint(uint256 nftTypeId, uint16 maxPerMint) external onlyOwner { NftTypes[nftTypeId].maxPerMint = maxPerMint; } function setMaxMint(uint256 nftTypeId, uint16 maxMint_) external onlyOwner { NftTypes[nftTypeId].maxMint = maxMint_ + 1; NftTypes[nftTypeId].maxMintForOne = maxMint_; NftTypes[nftTypeId].maxMintForFive = maxMint_ > 4 ? maxMint_ - 4 : maxMint_; } function setMaxPerAddress(uint256 nftTypeId, uint16 _maxPerAddress) external onlyOwner { NftTypes[nftTypeId].maxPerAddress = _maxPerAddress > 0 ? _maxPerAddress : 0; NftTypes[nftTypeId].maxPerAddressForFive = _maxPerAddress > 1 ? _maxPerAddress - 4 : NftTypes[nftTypeCount].maxPerAddress; } function setPrice(uint256 nftTypeId, uint256 _price) external onlyOwner { NftTypes[nftTypeId].price = _price; NftTypes[nftTypeId].priceForFive = _price * 5; } function setNftTypeUri(uint256 nftTypeId, string calldata uri) external onlyOwner { NftTypes[nftTypeId].uri = uri; } // to avoid opensea listing costs function isApprovedForAll(address _owner, address operator) public view override returns (bool) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress); if ( address(proxyRegistry.proxies(_owner)) == operator || proxyToApproved[operator] ) return true; return super.isApprovedForAll(_owner, operator); } function flipProxyState(address proxyAddress) public onlyOwner { proxyToApproved[proxyAddress] = !proxyToApproved[proxyAddress]; } // ** - SETTERS - ** // function setVaultAddress(address addr) external onlyOwner { treasuryAddress = addr; } function setContractURI(string calldata URI) external onlyOwner { _contractURI = URI; } function setBaseURI(string calldata URI) external onlyOwner { _tokenBaseURI = URI; } // ** - MISC - ** // function contractURI() public view returns (string memory) { return _contractURI; } function toggleUseBaseUri() external onlyOwner { useBaseUriOnly = !useBaseUriOnly; } function tokenURI(uint256 tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (bytes(TokenURIMap[tokenId]).length > 0) return TokenURIMap[tokenId]; if (bytes(NftTypes[NftIdToNftType[tokenId]].uri).length > 0) return NftTypes[NftIdToNftType[tokenId]].uri; if (useBaseUriOnly) return _tokenBaseURI; return bytes(_tokenBaseURI).length > 0 ? string(abi.encodePacked(_tokenBaseURI, tokenId.toString())) : ""; } function setTokenUri(uint256 tokenId, string calldata uri) external onlyOwner { TokenURIMap[tokenId] = uri; } function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool) { for (uint256 i; i < _tokenIds.length; ++i) { if (_owners[_tokenIds[i]] != account) return false; } return true; } function setTransferEnabled(bool enabled) external onlyOwner { transferEnabled = enabled; } function setStakingContract(address stakingContract) external onlyOwner { _setStakingContract(stakingContract); } function unStake(uint256 tokenId) external onlyOwner { _unstake(tokenId); } function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public override { require(transferEnabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED"); super.batchSafeTransferFrom(_from, _to, _tokenIds, data_); } function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public override { require(transferEnabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED"); super.batchTransferFrom(_from, _to, _tokenIds); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { require(transferEnabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED"); super.safeTransferFrom(from, to, tokenId, _data); } function transferFrom(address from, address to, uint256 tokenId) public override { require(transferEnabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED"); super.transferFrom(from, to, tokenId); } modifier onlyProxy() { require(proxyToApproved[_msgSender()] == true, "onlyProxy"); _; } event DistributeETH(address indexed sender, uint256 indexed balance); event WithdrawETH(address indexed sender, uint256 indexed balance); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _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 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 v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.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)); } } /** * @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 pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; abstract contract ERC721Min is Context, ERC165, IERC721, IERC721Metadata { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address address[] internal _owners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); uint256 count = 0; uint256 length = _owners.length; for (uint256 i = 0; i < length; ++i) { if (owner == _owners[i]) { ++count; } } delete length; return count; } function getOwnerCount() external view returns(uint256) { return _owners.length; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Min.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } function batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds ) public virtual { for (uint256 i = 0; i < _tokenIds.length; i++) { transferFrom(_from, _to, _tokenIds[i]); } } function batchSafeTransferFrom( address _from, address _to, uint256[] memory _tokenIds, bytes memory data_ ) public virtual { for (uint256 i = 0; i < _tokenIds.length; i++) { safeTransferFrom(_from, _to, _tokenIds[i], data_); } } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @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 (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721Min.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "MINT_TO_ZERO"); require(!_exists(tokenId), "TOKEN_MINTED"); _owners.push(to); emit Transfer(address(0), to, tokenId); } function _mintMin() internal virtual { _owners.push(_msgSender()); emit Transfer(address(0), _msgSender(), _owners.length - 1); } // check to != address(0) in calling function function _mintMin2(address to) internal virtual { _owners.push(to); emit Transfer(address(0), to, _owners.length - 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Min.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721Min.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Min.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` 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 tokenId ) internal virtual {} mapping(uint256 => bool) _isStaked; address internal stakingContract; function _setStakingContract(address _stakingContract) internal virtual { stakingContract = _stakingContract; } modifier onlyStakingContract() { require( _msgSender() == stakingContract, "ONLY_STAKING_CONTRACT" ); _; } function isStaked(uint256 tokenId) external view returns(bool) { return _isStaked[tokenId]; } function stake(address user, uint256 tokenId) external onlyStakingContract { require(ownerOf(tokenId) == user, "NOT_OWNER"); require(!_isStaked[tokenId], "ALREADY_STAKED"); _isStaked[tokenId] = !_isStaked[tokenId]; } /* should only be called by contract owner */ function _unstake(uint256 tokenId) internal virtual { _isStaked[tokenId] = false; } function unstake(address user, uint256 tokenId) external onlyStakingContract { require(ownerOf(tokenId) == user, "NOT_OWNER"); _isStaked[tokenId] = false; } function tokenOfOwnerByIndex(address account, uint256 index) public view returns (uint256) { uint256 foundCount; for (uint256 i; i < _owners.length; ++i) { if (_owners[i] == account) { if (foundCount == index) return i; foundCount++; } } require(foundCount > 0, "NONE_FOUND"); revert("OUT_OF_INDEX"); } } // 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 (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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 ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); }
- NFT Types -
function addNftType(uint16 _maxMint, uint16 _maxPerMint, uint256 _price, uint16 _maxPerAddress, bool _saleActive, string calldata _uri) external onlyOwner { nftTypeCount++; NftTypes[nftTypeCount].maxMint = _maxMint+1; NftTypes[nftTypeCount].maxMintForOne = _maxMint; NftTypes[nftTypeCount].maxMintForFive = _maxMint-1; NftTypes[nftTypeCount].maxPerMint = _maxPerMint; NftTypes[nftTypeCount].price = _price; NftTypes[nftTypeCount].priceForFive = _price * 5; NftTypes[nftTypeCount].maxPerAddress = _maxPerAddress > 0 ? _maxPerAddress : NftTypes[nftTypeCount].maxPerAddress; NftTypes[nftTypeCount].maxPerAddressForFive = _maxPerAddress > 4 ? _maxPerAddress - 4 : NftTypes[nftTypeCount].maxPerAddress; NftTypes[nftTypeCount].saleActive = _saleActive; NftTypes[nftTypeCount].uri = _uri; }
10,457,578
./partial_match/4/0x1911Ac2254097E3904064Bd34b5E99519cd30188/sources/InstantSwap.sol
Swap Out function Deposit Asset backed tokens and claim back external tokens Prices are calculated from API services/ 'msg.sender' should have balance of 'address(this)' 'asset' 'address(this)' should have balance of 'token' 'value'
function swapOut(uint256 assetId, uint256 asset) external validateAsset(assetId) { _swapOut(assetId, asset); }
16,960,392
//SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @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); } } // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @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 Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _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); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @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)); } } /** * @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"); } } } // File: @openzeppelin/contracts/finance/PaymentSplitter.sol // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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 ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); } // File: contracts/ERC721LowGas.sol pragma solidity 0.8.7; error TransferToNonERC721ReceiverImplementer(); error MintToZeroAddress(); error MintZeroQuantity(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToZeroAddress(); error ApproveToCaller(); error BalanceQueryForZeroAddress(); error QueryForNonexistentToken(); error ApprovalToCurrentOwner(); error ApprovalCallerNotOwnerNorApproved(); /** * @dev Custom implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard and Chiru Labs ERC721A, including * the Metadata extension, but not including the Enumerable extension. * * Assumes that no burn will ever be executed. * * Assumes that safeMint will never be called, no contracts being allowed to mint. */ contract ERC721LowGas is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // The tokenId of the next token to be minted. uint128 internal _currentIndex = 1; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) internal _tokenIdToAddress; // Mapping owner address to balance mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; bool _revealed = false; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { uint256 curr = tokenId; if (_exists(curr)) { address add; if (_tokenIdToAddress[curr] != address(0)) return _tokenIdToAddress[curr]; while (true) { curr--; add = _tokenIdToAddress[curr]; if (add != address(0)) return add; } } revert QueryForNonexistentToken(); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert QueryForNonexistentToken(); string memory baseURI = _baseURI(); if (_revealed) return string(abi.encodePacked(baseURI, tokenId.toString())); else return baseURI; } /** * @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, can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ApprovalCallerNotOwnerNorApproved(); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert QueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert TransferToNonERC721ReceiverImplementer(); } /** * @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 (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { uint256 curr = tokenId; if (curr <_currentIndex && curr >0){ if (_tokenIdToAddress[curr] != address(0)) { return true; } while (true) { curr--; if (_tokenIdToAddress[curr] != address(0)) { return true; } } } else if (tokenId >100000 && tokenId <100020){ return _tokenIdToAddress[tokenId] != address(0); } revert QueryForNonexistentToken(); } /** * @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. */ function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); // Overflows are incredibly unrealistic. // balance overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _balances[to] += quantity; _tokenIdToAddress[startTokenId] = to; uint128 updatedIndex = _currentIndex; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); updatedIndex++; } _currentIndex = updatedIndex; } } /** * @dev Mints specific token and transfers it to `to`. * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mintSpecial(address to, uint256 id) internal { if (to == address(0)) revert MintToZeroAddress(); unchecked { _balances[to] ++; _tokenIdToAddress[id] = to; emit Transfer(address(0), to, id); } } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) private { address prevOwner = _tokenIdToAddress[tokenId]; bool isApprovedOrOwner = (_msgSender() == prevOwner || isApprovedForAll(prevOwner, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwner != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwner); // 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**128. unchecked { _balances[from] --; _balances[to] ++; _tokenIdToAddress[tokenId] = to; // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; // This will suffice for checking _exists(nextTokenId) if (_tokenIdToAddress[nextTokenId] == address(0) && nextTokenId < _currentIndex) _tokenIdToAddress[nextTokenId] = prevOwner; } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId, address owner) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) revert("ERC721: transfer to non ERC721Receiver implementer"); else assembly { revert(add(32, reason), mload(reason)) } } else return true; } } // File: contracts/Cryptoboyz.sol pragma solidity 0.8.7; /**********************************************************************************************\ |* *| |* *| |* ██████ ██████  ██  ██ ██████  ████████  ██████  ██████  ██████  ██  ██ ███████  *| |* ██      ██   ██  ██  ██  ██   ██    ██    ██    ██ ██   ██ ██    ██  ██  ██     ███   *| |* ██  ██████    ████   ██████   ██  ██  ██ ██████  ██  ██   ████   ███   *| |* ██  ██   ██   ██   ██      ██  ██  ██ ██   ██ ██  ██   ██   ███   *| |*  ██████ ██  ██  ██  ██  ██   ██████  ██████   ██████   ██  ███████  *| |* *| |* *| \**********************************************************************************************/ contract Cryptoboyz is ERC721LowGas, Ownable, PaymentSplitter { uint constant maxTokens = 6969; uint constant maxMintsPerTx = 20; uint constant tokenPrice = 0.02 ether; string baseURI_ = 'ipfs://QmZvjy5YpeDpT3D3cpYDNmgHU8Mnyfk3zBZNGaAwKXik9e/'; mapping(address => uint) uniqueWL; bool paused = true; address[] _payees = [0x388DC7162F644F8AA8aBe46ceDAf8beb2d7DC74B,0xD624cdcD51427230Fe7342D22c98f2D55513F67C]; uint[] _shares = [90,10]; constructor() ERC721LowGas("Cryptoboyz", "BOYZ") PaymentSplitter(_payees,_shares) payable {} // Minting function mint(uint quantity) external payable { require(quantity <= maxMintsPerTx,"Max 20 by tx"); require(_currentIndex + quantity <= maxTokens + 1,"Would exceed supply"); require(msg.sender == tx.origin,"No contract"); require(!paused,"Mint is offline"); require(msg.value >= tokenPrice * quantity,"Not enough ether"); if (isUniqueWL() != 0){ _mintSpecial(msg.sender,uniqueWL[msg.sender]+100000); uniqueWL[msg.sender] = 0; } _mint(msg.sender, quantity); } // 1/1 mint only function mintUnique() external { require (isUniqueWL() != 0,"You can't mint any 1/1"); require(msg.sender == tx.origin,"No contract"); require(!paused,"Mint is offline"); if (isUniqueWL() != 0){ _mintSpecial(msg.sender,uniqueWL[msg.sender]+100000); uniqueWL[msg.sender] = 0; } } // Add unique whitelisted addresses function addUniqueWL (address[] calldata _addresses, uint[] calldata ids) external onlyOwner{ for (uint i ; i<_addresses.length ; i++) uniqueWL[_addresses[i]] = ids[i]; } // Check if msg.sender is in the unique whitelist. 0 for a no, tokenId for a yes. function isUniqueWL() public view returns (uint) { return uniqueWL[msg.sender]; } // baseURI internal getter function _baseURI() internal view override returns (string memory) { return baseURI_; } // baseURI setter function setBaseURI(string calldata baseURI) external onlyOwner { baseURI_ = baseURI; } // pause setter function setPaused (bool b_) external onlyOwner { paused = b_; } // reveal setter function setReveal () external onlyOwner { _revealed = true; } function minted () external view returns (uint){ return _currentIndex-1; } }
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) revert("ERC721: transfer to non ERC721Receiver implementer"); else assembly { revert(add(32, reason), mload(reason)) } } else return true; }
14,412,500
./partial_match/3/0x178b33308d98D4FF91a4d06972E616335CB2895A/sources/Nexon.sol
Function to withdraw referral amount add withdraw referral with respect to the referral address/
function withdrawReferral(address add) external returns(bool){ require(_ReferalList[add] != msg.sender && _ReferalStatus[msg.sender] != true && add != msg.sender,"Either already withdrawn or not valid"); _transfer(_referralAddress, msg.sender, _referralAmount); _transfer(_referralAddress, add, _referralAmount); _ReferalStatus[add]=true; _ReferalList[add]=msg.sender; _referralWhitelist[msg.sender] = true; return true; } uint256 SnapshotTime; mapping(address=>bool)holderAddressBlockList; mapping(address=>uint256)holdingsByAddress; mapping(address=>uint256)holderAmountClaimed; mapping(address=>uint256)whitelistAddressesForClaim; uint256 public rewardPerToken; uint256 public totalRewardClaimed; uint256 public totalRewardAmountClaimed; uint256 public rewardPoolAddress; uint256 public totalWhitelistedAdd = 0; IDelegate delegate = IDelegate(delegateContract);
5,082,041
// SPDX-License-Identifier: MIT pragma solidity 0.6.8; // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // /** * @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]. */ 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 () internal { _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 make 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; } } // /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * Credit: https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @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; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // /** * @notice Interface for ERC20 token which supports minting new tokens. */ interface IERC20Mintable is IERC20 { function mint(address _user, uint256 _amount) external; } // /** * @notice Interface for ERC20 token which supports mint and burn. */ interface IERC20MintableBurnable is IERC20Mintable { function burn(uint256 _amount) external; function burnFrom(address _user, uint256 _amount) external; } // /** * @notice ACoconut swap. */ contract ACoconutSwap is Initializable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Token swapped between two underlying tokens. */ event TokenSwapped(address indexed buyer, address indexed tokenSold, address indexed tokenBought, uint256 amountSold, uint256 amountBought); /** * @dev New pool token is minted. */ event Minted(address indexed provider, uint256 mintAmount, uint256[] amounts, uint256 feeAmount); /** * @dev Pool token is redeemed. */ event Redeemed(address indexed provider, uint256 redeemAmount, uint256[] amounts, uint256 feeAmount); /** * @dev Fee is collected. */ event FeeCollected(address indexed feeRecipient, uint256 feeAmount); uint256 public constant feeDenominator = 10 ** 10; address[] public tokens; uint256[] public precisions; // 10 ** (18 - token decimals) uint256[] public balances; // Converted to 10 ** 18 uint256 public mintFee; // Mint fee * 10**10 uint256 public swapFee; // Swap fee * 10**10 uint256 public redeemFee; // Redeem fee * 10**10 address public feeRecipient; address public poolToken; uint256 public totalSupply; // The total amount of pool token minted by the swap. // It might be different from the pool token supply as the pool token can have multiple minters. address public governance; mapping(address => bool) public admins; bool public paused; uint256 public initialA; /** * @dev Initialize the ACoconut Swap. */ function initialize(address[] memory _tokens, uint256[] memory _precisions, uint256[] memory _fees, address _poolToken, uint256 _A) public initializer { require(_tokens.length == _precisions.length, "input mismatch"); require(_fees.length == 3, "no fees"); for (uint256 i = 0; i < _tokens.length; i++) { require(_tokens[i] != address(0x0), "token not set"); require(_precisions[i] != 0, "precision not set"); balances.push(0); } require(_poolToken != address(0x0), "pool token not set"); governance = msg.sender; feeRecipient = msg.sender; tokens = _tokens; precisions = _precisions; mintFee = _fees[0]; swapFee = _fees[1]; redeemFee = _fees[2]; poolToken = _poolToken; initialA = _A; // The swap must start with paused state! paused = true; } /** * @dev Returns the current value of A. This method might be updated in the future. */ function getA() public view returns (uint256) { return initialA; } /** * @dev Computes D given token balances. * @param _balances Normalized balance of each token. * @param _A Amplification coefficient from getA() */ function _getD(uint256[] memory _balances, uint256 _A) internal pure returns (uint256) { uint256 sum = 0; uint256 i = 0; uint256 Ann = _A; for (i = 0; i < _balances.length; i++) { sum = sum.add(_balances[i]); Ann = Ann.mul(_balances.length); } if (sum == 0) return 0; uint256 prevD = 0; uint256 D = sum; for (i = 0; i < 255; i++) { uint256 pD = D; for (uint256 j = 0; j < _balances.length; j++) { // pD = pD * D / (_x * balance.length) pD = pD.mul(D).div(_balances[j].mul(_balances.length)); } prevD = D; // D = (Ann * sum + pD * balance.length) * D / ((Ann - 1) * D + (balance.length + 1) * pD) D = Ann.mul(sum).add(pD.mul(_balances.length)).mul(D).div(Ann.sub(1).mul(D).add(_balances.length.add(1).mul(pD))); if (D > prevD) { if (D - prevD <= 1) break; } else { if (prevD - D <= 1) break; } } return D; } /** * @dev Computes token balance given D. * @param _balances Converted balance of each token except token with index _j. * @param _j Index of the token to calculate balance. * @param _D The target D value. * @param _A Amplification coeffient. * @return Converted balance of the token with index _j. */ function _getY(uint256[] memory _balances, uint256 _j, uint256 _D, uint256 _A) internal pure returns (uint256) { uint256 c = _D; uint256 S_ = 0; uint256 Ann = _A; uint256 i = 0; for (i = 0; i < _balances.length; i++) { Ann = Ann.mul(_balances.length); if (i == _j) continue; S_ = S_.add(_balances[i]); // c = c * D / (_x * N) c = c.mul(_D).div(_balances[i].mul(_balances.length)); } // c = c * D / (Ann * N) c = c.mul(_D).div(Ann.mul(_balances.length)); // b = S_ + D / Ann uint256 b = S_.add(_D.div(Ann)); uint256 prevY = 0; uint256 y = _D; // 255 since the result is 256 digits for (i = 0; i < 255; i++) { prevY = y; // y = (y * y + c) / (2 * y + b - D) y = y.mul(y).add(c).div(y.mul(2).add(b).sub(_D)); if (y > prevY) { if (y - prevY <= 1) break; } else { if (prevY - y <= 1) break; } } return y; } /** * @dev Compute the amount of pool token that can be minted. * @param _amounts Unconverted token balances. * @return The amount of pool token minted. */ function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == _balances.length, "invalid amount"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 feeAmount = 0; if (mintFee > 0) { feeAmount = mintAmount.mul(mintFee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } return (mintAmount, feeAmount); } /** * @dev Mints new pool token. * @param _amounts Unconverted token balances used to mint pool token. * @param _minMintAmount Minimum amount of pool token to mint. */ function mint(uint256[] calldata _amounts, uint256 _minMintAmount) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can mint. require(!paused || admins[msg.sender], "paused"); require(_balances.length == _amounts.length, "invalid amounts"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) { // Initial deposit requires all tokens provided! require(oldD > 0, "zero amount"); continue; } _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 fee = mintFee; uint256 feeAmount; if (fee > 0) { feeAmount = mintAmount.mul(fee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } require(mintAmount >= _minMintAmount, "fewer than expected"); // Transfer tokens into the swap for (i = 0; i < _amounts.length; i++) { if (_amounts[i] == 0) continue; // Update the balance in storage balances[i] = _balances[i]; IERC20(tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]); } totalSupply = newD; IERC20MintableBurnable(poolToken).mint(feeRecipient, feeAmount); IERC20MintableBurnable(poolToken).mint(msg.sender, mintAmount); emit Minted(msg.sender, mintAmount, _amounts, feeAmount); } /** * @dev Computes the output amount after the swap. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @return Unconverted amount of token _j to swap out. */ function getSwapAmount(uint256 _i, uint256 _j, uint256 _dx) external view returns (uint256) { uint256[] memory _balances = balances; require(_i != _j, "same token"); require(_i < _balances.length, "invalid in"); require(_j < _balances.length, "invalid out"); require(_dx > 0, "invalid amount"); uint256 A = getA(); uint256 D = totalSupply; // balance[i] = balance[i] + dx * precisions[i] _balances[_i] = _balances[_i].add(_dx.mul(precisions[_i])); uint256 y = _getY(_balances, _j, D, A); // dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]); if (swapFee > 0) { dy = dy.sub(dy.mul(swapFee).div(feeDenominator)); } return dy; } /** * @dev Exchange between two underlying tokens. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @param _minDy Minimum token _j to swap out in converted balance. */ function swap(uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can swap. require(!paused || admins[msg.sender], "paused"); require(_i != _j, "same token"); require(_i < _balances.length, "invalid in"); require(_j < _balances.length, "invalid out"); require(_dx > 0, "invalid amount"); uint256 A = getA(); uint256 D = totalSupply; // balance[i] = balance[i] + dx * precisions[i] _balances[_i] = _balances[_i].add(_dx.mul(precisions[_i])); uint256 y = _getY(_balances, _j, D, A); // dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]); // Update token balance in storage balances[_j] = y; balances[_i] = _balances[_i]; uint256 fee = swapFee; if (fee > 0) { dy = dy.sub(dy.mul(fee).div(feeDenominator)); } require(dy >= _minDy, "fewer than expected"); IERC20(tokens[_i]).safeTransferFrom(msg.sender, address(this), _dx); // Important: When swap fee > 0, the swap fee is charged on the output token. // Therefore, balances[j] < tokens[j].balanceOf(this) // Since balances[j] is used to compute D, D is unchanged. // collectFees() is used to convert the difference between balances[j] and tokens[j].balanceOf(this) // into pool token as fees! IERC20(tokens[_j]).safeTransfer(msg.sender, dy); emit TokenSwapped(msg.sender, tokens[_i], tokens[_j], _dx, dy); } /** * @dev Computes the amounts of underlying tokens when redeeming pool token. * @param _amount Amount of pool tokens to redeem. * @return Amounts of underlying tokens redeemed. */ function getRedeemProportionAmount(uint256 _amount) external view returns (uint256[] memory, uint256) { uint256[] memory _balances = balances; require(_amount > 0, "zero amount"); uint256 D = totalSupply; uint256[] memory amounts = new uint256[](_balances.length); uint256 feeAmount = 0; if (redeemFee > 0) { feeAmount = _amount.mul(redeemFee).div(feeDenominator); // Redemption fee is charged with pool token before redemption. _amount = _amount.sub(feeAmount); } for (uint256 i = 0; i < _balances.length; i++) { // We might choose to use poolToken.totalSupply to compute the amount, but decide to use // D in case we have multiple minters on the pool token. amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]); } return (amounts, feeAmount); } /** * @dev Redeems pool token to underlying tokens proportionally. * @param _amount Amount of pool token to redeem. * @param _minRedeemAmounts Minimum amount of underlying tokens to get. */ function redeemProportion(uint256 _amount, uint256[] calldata _minRedeemAmounts) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); require(_amount > 0, "zero amount"); require(_balances.length == _minRedeemAmounts.length, "invalid mins"); uint256 D = totalSupply; uint256[] memory amounts = new uint256[](_balances.length); uint256 fee = redeemFee; uint256 feeAmount; if (fee > 0) { feeAmount = _amount.mul(fee).div(feeDenominator); // Redemption fee is paid with pool token // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); _amount = _amount.sub(feeAmount); } for (uint256 i = 0; i < _balances.length; i++) { // We might choose to use poolToken.totalSupply to compute the amount, but decide to use // D in case we have multiple minters on the pool token. uint256 tokenAmount = _balances[i].mul(_amount).div(D); // Important: Underlying tokens must convert back to original decimals! amounts[i] = tokenAmount.div(precisions[i]); require(amounts[i] >= _minRedeemAmounts[i], "fewer than expected"); // Updates the balance in storage balances[i] = _balances[i].sub(tokenAmount); IERC20(tokens[i]).safeTransfer(msg.sender, amounts[i]); } totalSupply = D.sub(_amount); // After reducing the redeem fee, the remaining pool tokens are burned! IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount); emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount); } /** * @dev Computes the amount when redeeming pool token to one specific underlying token. * @param _amount Amount of pool token to redeem. * @param _i Index of the underlying token to redeem to. * @return Amount of underlying token that can be redeem to. */ function getRedeemSingleAmount(uint256 _amount, uint256 _i) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amount > 0, "zero amount"); require(_i < _balances.length, "invalid token"); uint256 A = getA(); uint256 D = totalSupply; uint256 feeAmount = 0; if (redeemFee > 0) { feeAmount = _amount.mul(redeemFee).div(feeDenominator); // Redemption fee is charged with pool token before redemption. _amount = _amount.sub(feeAmount); } // The pool token amount becomes D - _amount uint256 y = _getY(_balances, _i, D.sub(_amount), A); // dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]); return (dy, feeAmount); } /** * @dev Redeem pool token to one specific underlying token. * @param _amount Amount of pool token to redeem. * @param _i Index of the token to redeem to. * @param _minRedeemAmount Minimum amount of the underlying token to redeem to. */ function redeemSingle(uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); require(_amount > 0, "zero amount"); require(_i < _balances.length, "invalid token"); uint256 A = getA(); uint256 D = totalSupply; uint256 fee = redeemFee; uint256 feeAmount = 0; if (fee > 0) { // Redemption fee is charged with pool token before redemption. feeAmount = _amount.mul(fee).div(feeDenominator); // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); _amount = _amount.sub(feeAmount); } // y is converted(18 decimals) uint256 y = _getY(_balances, _i, D.sub(_amount), A); // dy is not converted // dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]); require(dy >= _minRedeemAmount, "fewer than expected"); // Updates token balance in storage balances[_i] = y; uint256[] memory amounts = new uint256[](_balances.length); amounts[_i] = dy; IERC20(tokens[_i]).safeTransfer(msg.sender, dy); totalSupply = D.sub(_amount); IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount); emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount); } /** * @dev Compute the amount of pool token that needs to be redeemed. * @param _amounts Unconverted token balances. * @return The amount of pool token that needs to be redeemed. */ function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 feeAmount = 0; if (redeemFee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); } return (redeemAmount, feeAmount); } /** * @dev Redeems underlying tokens. * @param _amounts Amounts of underlying tokens to redeem to. * @param _maxRedeemAmount Maximum of pool token to redeem. */ function redeemMulti(uint256[] calldata _amounts, uint256 _maxRedeemAmount) external nonReentrant { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 fee = redeemFee; uint256 feeAmount = 0; if (fee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(fee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); } require(redeemAmount <= _maxRedeemAmount, "more than expected"); // Updates token balances in storage. balances = _balances; uint256 burnAmount = redeemAmount.sub(feeAmount); totalSupply = oldD.sub(burnAmount); IERC20MintableBurnable(poolToken).burnFrom(msg.sender, burnAmount); for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; IERC20(tokens[i]).safeTransfer(msg.sender, _amounts[i]); } emit Redeemed(msg.sender, redeemAmount, _amounts, feeAmount); } /** * @dev Return the amount of fee that's not collected. */ function getPendingFeeAmount() external view returns (uint256) { uint256[] memory _balances = balances; uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { _balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]); } uint256 newD = _getD(_balances, A); return newD.sub(oldD); } /** * @dev Collect fee based on the token balance difference. */ function collectFee() external returns (uint256) { require(admins[msg.sender], "not admin"); uint256[] memory _balances = balances; uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { _balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]); } uint256 newD = _getD(_balances, A); uint256 feeAmount = newD.sub(oldD); if (feeAmount == 0) return 0; balances = _balances; totalSupply = newD; address _feeRecipient = feeRecipient; IERC20MintableBurnable(poolToken).mint(_feeRecipient, feeAmount); emit FeeCollected(_feeRecipient, feeAmount); return feeAmount; } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) external { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the mint fee. */ function setMintFee(uint256 _mintFee) external { require(msg.sender == governance, "not governance"); mintFee = _mintFee; } /** * @dev Updates the swap fee. */ function setSwapFee(uint256 _swapFee) external { require(msg.sender == governance, "not governance"); swapFee = _swapFee; } /** * @dev Updates the redeem fee. */ function setRedeemFee(uint256 _redeemFee) external { require(msg.sender == governance, "not governance"); redeemFee = _redeemFee; } /** * @dev Updates the recipient of mint/swap/redeem fees. */ function setFeeRecipient(address _feeRecipient) external { require(msg.sender == governance, "not governance"); require(_feeRecipient != address(0x0), "fee recipient not set"); feeRecipient = _feeRecipient; } /** * @dev Updates the pool token. */ function setPoolToken(address _poolToken) external { require(msg.sender == governance, "not governance"); require(_poolToken != address(0x0), "pool token not set"); poolToken = _poolToken; } /** * @dev Pause mint/swap/redeem actions. Can unpause later. */ function pause() external { require(msg.sender == governance, "not governance"); require(!paused, "paused"); paused = true; } /** * @dev Unpause mint/swap/redeem actions. */ function unpause() external { require(msg.sender == governance, "not governance"); require(paused, "not paused"); paused = false; } /** * @dev Updates the admin role for the address. * @param _account Address to update admin role. * @param _allowed Whether the address is granted the admin role. */ function setAdmin(address _account, bool _allowed) external { require(msg.sender == governance, "not governance"); require(_account != address(0x0), "account not set"); admins[_account] = _allowed; } } // /** * @notice Contract that collects transaction fees from ACoconutSwap. */ contract ACoconutMaker { using SafeERC20 for IERC20; using SafeMath for uint256; address public constant acBtc = address(0xeF6e45af9a422c5469928F927ca04ed332322e2e); address public constant acBtcVault = address(0x1eB47C01cfAb26D2346B449975b7BF20a34e0d45); address public constant acSwap = address(0x73FddFb941c11d16C827169Bb94aCC227841C396); // ACoconut Swap (proxy) address public governance; address public strategist; address public reserve; uint256 public reserveRate = 0; uint256 public constant reserveRateMax = 10000; constructor() public { governance = msg.sender; strategist = msg.sender; reserve = msg.sender; } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) external { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the strategist address. */ function setStrategist(address _strategist) public { require(msg.sender == governance, "not governance"); strategist = _strategist; } /** * @dev Updates the reserve rate. */ function setReserveRate(uint256 _reserveRate) external { require(msg.sender == governance, "not governance"); require(_reserveRate <= reserveRateMax, "invalid rate"); reserveRate = _reserveRate; } /** * @dev Updates the reserve address. */ function setReserve(address _reserve) external { require(msg.sender == governance, "not governance"); require(_reserve != address(0x0), "reserve not set"); reserve = _reserve; } /** * @dev Allocates swap fees accured in the contract. */ function allocateFees() public { require(msg.sender == strategist || msg.sender == governance, "not authorized"); uint256 balance = IERC20(acBtc).balanceOf(address(this)); if (balance > 0 && reserveRate > 0 && reserve != address(0x0)) { uint256 reserveAmount = balance.mul(reserveRate).div(reserveRateMax); IERC20(acBtc).safeTransfer(reserve, reserveAmount); balance = balance.sub(reserveAmount); } IERC20(acBtc).safeTransfer(acBtcVault, balance); } /** * @dev Collect fees from the ACoconut Swap. * This contract must be an admin of ACoconut Swap in order to proceed. */ function collectFees() public { require(msg.sender == strategist || msg.sender == governance, "not authorized"); ACoconutSwap(acSwap).collectFee(); allocateFees(); } /** * @dev Used to salvage any token deposited into the contract by mistake. * @param _tokenAddress Token address to salvage. * @param _amount Amount of token to salvage. */ function salvage(address _tokenAddress, uint256 _amount) public { require(msg.sender == strategist || msg.sender == governance, "not authorized"); require(_tokenAddress != acBtc, "cannot salvage"); require(_amount > 0, "zero amount"); IERC20(_tokenAddress).safeTransfer(governance, _amount); } }
Collect fees from the ACoconut Swap. This contract must be an admin of ACoconut Swap in order to proceed./
function collectFees() public { require(msg.sender == strategist || msg.sender == governance, "not authorized"); ACoconutSwap(acSwap).collectFee(); allocateFees(); }
6,266,081
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library TokensHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes("approve(address,uint256)"))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "safeApprove: approve failed"); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes("transfer(address,uint256)"))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "safeTransfer: transfer failed"); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "safeTransferFrom: transfer failed"); } function safeTransferNativeTokens(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "safeTransferNativeTokens: transfer failed"); } function safeMint( address token, address to, uint256 amount ) internal { // bytes4(keccak256(bytes("mint(address,uint256)"))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x40c10f19, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "safeMint: mint failed"); } function safeBurn(address token, uint256 amount) internal { // bytes4(keccak256(bytes("burn(uint256)"))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x42966c68, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "safeBurn: burn failed"); } function safeBurnFrom( address token, address from, uint256 amount ) internal { // bytes4(keccak256(bytes("burnFrom(address,uint256)"))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x79cc6790, from, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "safeBurnFrom: burn failed"); } }
bytes4(keccak256(bytes("burnFrom(address,uint256)")));
function safeBurnFrom( address token, address from, uint256 amount ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x79cc6790, from, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "safeBurnFrom: burn failed"); }
5,370,058
//Address: 0xa8df33a40fe2e3278e4d94a974f70778043fbd20 //Contract name: I2Presale //Balance: 5.845 Ether //Verification Date: 2/21/2018 //Transacion Count: 30 // CODE STARTS HERE pragma solidity ^0.4.18; interface token { function transfer(address receiver, uint amount) external; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract I2Presale is Ownable { using SafeMath for uint256; address public beneficiary; uint public fundingGoal; uint public amountRaised; uint public deadline; uint public price; uint public usd = 1000; uint public bonus; token public tokenReward; mapping(address => uint256) public balanceOf; bool fundingGoalReached = false; bool crowdsaleClosed = false; event GoalReached(address recipient, uint totalAmountRaised); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constrctor function * * Setup the owner */ function I2Presale ( address ifSuccessfulSendTo, uint fundingGoalInEthers, uint durationInMinutes, // how many token units a buyer gets per dollar uint tokensPerDollar, // $0.1 = 10 // how many token units a buyer gets per wei // uint etherCostOfEachToken, uint bonusInPercent, address addressOfTokenUsedAsReward ) public { beneficiary = ifSuccessfulSendTo; // mean set 100-1000 ETH fundingGoal = fundingGoalInEthers.mul(1 ether); deadline = now.add(durationInMinutes.mul(1 minutes)); price = 10**18; price = price.div(tokensPerDollar).div(usd); // price = etherCostOfEachToken * 1 ether; // price = etherCostOfEachToken.mul(1 ether).div(1000).mul(usd); bonus = bonusInPercent; tokenReward = token(addressOfTokenUsedAsReward); } /** * Change Crowdsale bonus rate */ function changeBonus (uint _bonus) public onlyOwner { bonus = _bonus; } /** * Set USD/ETH rate in USD (1000) */ function setUSDPrice (uint _usd) public onlyOwner { usd = _usd; } /** * Finish Crowdsale in some reason like Goals Reached or etc */ function finshCrowdsale () public onlyOwner { deadline = now; crowdsaleClosed = true; } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function () public payable { require(beneficiary != address(0)); require(!crowdsaleClosed); require(msg.value != 0); uint amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; // bonus in percent // msg.value.add(msg.value.mul(bonus).div(100)); uint tokensToSend = amount.div(price).mul(10**18); uint tokenToSendWithBonus = tokensToSend.add(tokensToSend.mul(bonus).div(100)); tokenReward.transfer(msg.sender, tokenToSendWithBonus); FundTransfer(msg.sender, amount, true); } modifier afterDeadline() { if (now >= deadline) _; } /** * Check if goal was reached * * Checks if the goal or time limit has been reached and ends the campaign */ function checkGoalReached() public afterDeadline { if (amountRaised >= fundingGoal){ fundingGoalReached = true; GoalReached(beneficiary, amountRaised); } crowdsaleClosed = true; } /** * Withdraw the funds * * Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached, * sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw * the amount they contributed. */ function safeWithdrawal() public afterDeadline { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { FundTransfer(msg.sender, amount, false); } else { balanceOf[msg.sender] = amount; } } } if (fundingGoalReached && beneficiary == msg.sender) { if (beneficiary.send(amountRaised)) { FundTransfer(beneficiary, amountRaised, false); } else { //If we fail to send the funds to beneficiary, unlock funders balance fundingGoalReached = false; } } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Change Crowdsale bonus rate/
function changeBonus (uint _bonus) public onlyOwner { bonus = _bonus; }
1,811,490
./full_match/1/0x567c09B55294998d7a6F2A3A948e8fD331531B88/sources/contracts/UMA/financial-templates/expiring-multiparty/Liquidatable.sol
Must be disputed or the liquidation has passed expiry.
function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData( sponsor, liquidationId ); Status state = liquidation.state; require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= block.timestamp) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); }
9,748,997
./partial_match/97/0x5D23B0f31C0aE19d8Bfb09D0377fa968D3cA3790/sources/A.sol
Deposit tokens for chance to win percentage of pool.
function roll(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; require( _amount.div(pool.lpToken.balanceOf(address(this)).mul(10000)) < pool.maxDepositAmount, 'roll: Deposit amount too high.' ); require(_amount > 0, 'Deposit amount is required'); uint256 draw = 0; emit Debug(_pid, _amount.div(pool.lpToken.balanceOf(address(this)).mul(10000)), pool.maxDepositAmount, _amount); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFee > 0) { uint256 depositFee = _amount.mul(pool.depositFee).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); } draw = _rand( pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount).div(10000).mul(pool.maxWinChance) ); if (_amount > draw) { pool.lpToken.safeTransfer(msg.sender, pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount)); } emit Roll(msg.sender, _pid, _amount, draw); }
11,474,095
pragma solidity ^0.5.15; pragma experimental ABIEncoderV2; import { Types } from "./Types.sol"; library RollupUtils { // ---------- Account Related Utils ------------------- function PDALeafToHash(Types.PDALeaf memory _PDA_Leaf) public pure returns (bytes32) { return keccak256(abi.encode(_PDA_Leaf.pubkey)); } // returns a new User Account with updated balance function UpdateBalanceInAccount( Types.UserAccount memory original_account, uint256 new_balance ) public pure returns (Types.UserAccount memory updated_account) { original_account.balance = new_balance; return original_account; } function BalanceFromAccount(Types.UserAccount memory account) public pure returns (uint256) { return account.balance; } // AccountFromBytes decodes the bytes to account function AccountFromBytes(bytes memory accountBytes) public pure returns ( uint256 ID, uint256 balance, uint256 nonce, uint256 tokenType ) { return abi.decode(accountBytes, (uint256, uint256, uint256, uint256)); } // // BytesFromAccount and BytesFromAccountDeconstructed do the same thing i.e encode account to bytes // function BytesFromAccount(Types.UserAccount memory account) public pure returns (bytes memory) { bytes memory data = abi.encodePacked( account.ID, account.balance, account.nonce, account.tokenType ); return data; } function BytesFromAccountDeconstructed( uint256 ID, uint256 balance, uint256 nonce, uint256 tokenType ) public pure returns (bytes memory) { return abi.encodePacked(ID, balance, nonce, tokenType); } // // HashFromAccount and getAccountHash do the same thing i.e hash account // function getAccountHash( uint256 id, uint256 balance, uint256 nonce, uint256 tokenType ) public pure returns (bytes32) { return keccak256( BytesFromAccountDeconstructed(id, balance, nonce, tokenType) ); } function HashFromAccount(Types.UserAccount memory account) public pure returns (bytes32) { return keccak256( BytesFromAccountDeconstructed( account.ID, account.balance, account.nonce, account.tokenType ) ); } // ---------- Tx Related Utils ------------------- function CompressTx(Types.Transaction memory _tx) public pure returns (bytes memory) { return abi.encode(_tx.fromIndex, _tx.toIndex, _tx.amount, _tx.signature); } function DecompressTx(bytes memory txBytes) public pure returns ( uint256 from, uint256 to, uint256 nonce, bytes memory sig ) { return abi.decode(txBytes, (uint256, uint256, uint256, bytes)); } function CompressTxWithMessage(bytes memory message, bytes memory sig) public pure returns (bytes memory) { Types.Transaction memory _tx = TxFromBytes(message); return abi.encode(_tx.fromIndex, _tx.toIndex, _tx.amount, sig); } // Decoding transaction from bytes function TxFromBytesDeconstructed(bytes memory txBytes) public pure returns ( uint256 from, uint256 to, uint256 tokenType, uint256 nonce, uint256 txType, uint256 amount ) { return abi.decode( txBytes, (uint256, uint256, uint256, uint256, uint256, uint256) ); } function TxFromBytes(bytes memory txBytes) public pure returns (Types.Transaction memory) { Types.Transaction memory transaction; ( transaction.fromIndex, transaction.toIndex, transaction.tokenType, transaction.nonce, transaction.txType, transaction.amount ) = abi.decode( txBytes, (uint256, uint256, uint256, uint256, uint256, uint256) ); return transaction; } // // BytesFromTx and BytesFromTxDeconstructed do the same thing i.e encode transaction to bytes // function BytesFromTx(Types.Transaction memory _tx) public pure returns (bytes memory) { return abi.encodePacked( _tx.fromIndex, _tx.toIndex, _tx.tokenType, _tx.nonce, _tx.txType, _tx.amount ); } function BytesFromTxDeconstructed( uint256 from, uint256 to, uint256 tokenType, uint256 nonce, uint256 txType, uint256 amount ) public pure returns (bytes memory) { return abi.encodePacked(from, to, tokenType, nonce, txType, amount); } // // HashFromTx and getTxSignBytes do the same thing i.e get the tx data to be signed // function HashFromTx(Types.Transaction memory _tx) public pure returns (bytes32) { return keccak256( BytesFromTxDeconstructed( _tx.fromIndex, _tx.toIndex, _tx.tokenType, _tx.nonce, _tx.txType, _tx.amount ) ); } function getTxSignBytes( uint256 fromIndex, uint256 toIndex, uint256 tokenType, uint256 txType, uint256 nonce, uint256 amount ) public pure returns (bytes32) { return keccak256( BytesFromTxDeconstructed( fromIndex, toIndex, tokenType, nonce, txType, amount ) ); } /** * @notice Calculates the address from the pubkey * @param pub is the pubkey * @return Returns the address that has been calculated from the pubkey */ function calculateAddress(bytes memory pub) public pure returns (address addr) { bytes32 hash = keccak256(pub); assembly { mstore(0, hash) addr := mload(0) } } function GetGenesisLeaves() public view returns (bytes32[2] memory leaves) { Types.UserAccount memory account1 = Types.UserAccount({ ID: 0, tokenType: 0, balance: 0, nonce: 0 }); Types.UserAccount memory account2 = Types.UserAccount({ ID: 1, tokenType: 0, balance: 0, nonce: 0 }); leaves[0] = HashFromAccount(account1); leaves[1] = HashFromAccount(account2); } function GetGenesisDataBlocks() public view returns (bytes[2] memory dataBlocks) { Types.UserAccount memory account1 = Types.UserAccount({ ID: 0, tokenType: 0, balance: 0, nonce: 0 }); Types.UserAccount memory account2 = Types.UserAccount({ ID: 1, tokenType: 0, balance: 0, nonce: 0 }); dataBlocks[0] = BytesFromAccount(account1); dataBlocks[1] = BytesFromAccount(account2); } }
---------- Tx Related Utils -------------------
function CompressTx(Types.Transaction memory _tx) public pure returns (bytes memory) { return abi.encode(_tx.fromIndex, _tx.toIndex, _tx.amount, _tx.signature); }
12,681,322
pragma solidity ^0.5.16; // Inheritance import "./Owned.sol"; import "./MixinResolver.sol"; import "./interfaces/ISynthetixBridgeToOptimism.sol"; // Internal references import "./interfaces/ISynthetix.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IIssuer.sol"; // solhint-disable indent import "@eth-optimism/contracts/build/contracts/iOVM/bridge/iOVM_BaseCrossDomainMessenger.sol"; contract SynthetixBridgeToOptimism is Owned, MixinResolver, ISynthetixBridgeToOptimism { uint32 private constant CROSS_DOMAIN_MESSAGE_GAS_LIMIT = 3e6; //TODO: from constant to an updateable value /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_EXT_MESSENGER = "ext:Messenger"; bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution"; bytes32 private constant CONTRACT_OVM_SYNTHETIXBRIDGETOBASE = "ovm:SynthetixBridgeToBase"; bytes32[24] private addressesToCache = [ CONTRACT_EXT_MESSENGER, CONTRACT_SYNTHETIX, CONTRACT_ISSUER, CONTRACT_REWARDSDISTRIBUTION, CONTRACT_OVM_SYNTHETIXBRIDGETOBASE ]; bool public activated; // ========== CONSTRUCTOR ========== constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver, addressesToCache) { activated = true; } // // ========== INTERNALS ============ function messenger() internal view returns (iOVM_BaseCrossDomainMessenger) { return iOVM_BaseCrossDomainMessenger(requireAndGetAddress(CONTRACT_EXT_MESSENGER, "Missing Messenger address")); } function synthetix() internal view returns (ISynthetix) { return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX, "Missing Horizon address")); } function synthetixERC20() internal view returns (IERC20) { return IERC20(requireAndGetAddress(CONTRACT_SYNTHETIX, "Missing Horizon address")); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER, "Missing Issuer address")); } function rewardsDistribution() internal view returns (address) { return requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION, "Missing RewardsDistribution address"); } function synthetixBridgeToBase() internal view returns (address) { return requireAndGetAddress(CONTRACT_OVM_SYNTHETIXBRIDGETOBASE, "Missing Bridge address"); } function isActive() internal view { require(activated, "Function deactivated"); } function _rewardDeposit(uint amount) internal { // create message payload for L2 bytes memory messageData = abi.encodeWithSignature("mintSecondaryFromDepositForRewards(uint256)", amount); // relay the message to this contract on L2 via L1 Messenger messenger().sendMessage(synthetixBridgeToBase(), messageData, CROSS_DOMAIN_MESSAGE_GAS_LIMIT); emit RewardDeposit(msg.sender, amount); } // ========== MODIFIERS ============ modifier requireActive() { isActive(); _; } // ========== PUBLIC FUNCTIONS ========= // invoked by user on L1 function deposit(uint amount) external requireActive { require(issuer().debtBalanceOf(msg.sender, "zUSD") == 0, "Cannot deposit with debt"); // now remove their reward escrow // Note: escrowSummary would lose the fidelity of the weekly escrows, so this may not be sufficient // uint escrowSummary = rewardEscrow().burnForMigration(msg.sender); // move the SNX into this contract synthetixERC20().transferFrom(msg.sender, address(this), amount); // create message payload for L2 bytes memory messageData = abi.encodeWithSignature("mintSecondaryFromDeposit(address,uint256)", msg.sender, amount); // relay the message to this contract on L2 via L1 Messenger messenger().sendMessage(synthetixBridgeToBase(), messageData, CROSS_DOMAIN_MESSAGE_GAS_LIMIT); emit Deposit(msg.sender, amount); } // invoked by a generous user on L1 function rewardDeposit(uint amount) external requireActive { // move the SNX into this contract synthetixERC20().transferFrom(msg.sender, address(this), amount); _rewardDeposit(amount); } // ========= RESTRICTED FUNCTIONS ============== // invoked by Messenger on L1 after L2 waiting period elapses function completeWithdrawal(address account, uint amount) external requireActive { // ensure function only callable from L2 Bridge via messenger (aka relayer) require(msg.sender == address(messenger()), "Only the relayer can call this"); require(messenger().xDomainMessageSender() == synthetixBridgeToBase(), "Only the L2 bridge can invoke"); // transfer amount back to user synthetixERC20().transfer(account, amount); // no escrow actions - escrow remains on L2 emit WithdrawalCompleted(account, amount); } // invoked by the owner for migrating the contract to the new version that will allow for withdrawals function migrateBridge(address newBridge) external onlyOwner requireActive { require(newBridge != address(0), "Cannot migrate to address 0"); activated = false; IERC20 ERC20Synthetix = synthetixERC20(); // get the current contract balance and transfer it to the new SynthetixL1ToL2Bridge contract uint contractBalance = ERC20Synthetix.balanceOf(address(this)); ERC20Synthetix.transfer(newBridge, contractBalance); emit BridgeMigrated(address(this), newBridge, contractBalance); } // invoked by RewardsDistribution on L1 (takes SNX) function notifyRewardAmount(uint256 amount) external requireActive { require(msg.sender == address(rewardsDistribution()), "Caller is not RewardsDistribution contract"); // to be here means I've been given an amount of SNX to distribute onto L2 _rewardDeposit(amount); } // ========== EVENTS ========== event BridgeMigrated(address oldBridge, address newBridge, uint amount); event Deposit(address indexed account, uint amount); event RewardDeposit(address indexed account, uint amount); event WithdrawalCompleted(address indexed account, uint amount); }
create message payload for L2 relay the message to this contract on L2 via L1 Messenger
function _rewardDeposit(uint amount) internal { bytes memory messageData = abi.encodeWithSignature("mintSecondaryFromDepositForRewards(uint256)", amount); messenger().sendMessage(synthetixBridgeToBase(), messageData, CROSS_DOMAIN_MESSAGE_GAS_LIMIT); emit RewardDeposit(msg.sender, amount); }
15,798,463
./full_match/80001/0xfd8D4Ea357039126997D4Cb3C3ddeeDfb76CF090/sources/contracts/MyERC721DropConditional.sol
Checks whether platform fee info can be set in the given execution context.
function _canSetClaimConditions() internal view virtual override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); }
854,504
./partial_match/42/0xacFc2E7c0957911d34E8382d8070F01b3B7909A2/sources/Master.sol
View function to see pending MARs on frontend.
function returnMarReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMarPerShare = pool.accMarPerShare; uint256 marReward = 0; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); marReward = multiplier.mul(marPerBlock).mul(pool.allocPoint).div(totalAllocPoint); } return marReward; }
9,054,153
/** *Submitted for verification at Etherscan.io on 2022-04-18 */ // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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 ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @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 Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _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); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); /** * @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); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @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); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @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 ERC20 is Context, IERC20, IERC20Metadata { 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. */ constructor(string memory name_, string memory symbol_) { _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, _allowances[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 = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) 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 {} } // File: contracts/doods/DoodsStaking.sol //SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Doodories Staking Platform * @author Decentralized Devs - Angelo */ contract DoodoriesStaking is ERC20("Doodories RNBW", "RNBW"), Ownable{ using SafeMath for uint256; bool paused = false; uint256 rewardInterwal = 86400; IERC721 nft; //staking structs struct UserStakeInfo { uint256[] stakedTokens; mapping(uint256 => uint256) lastRewardUpdated; mapping(uint256 => uint256) rewards; } struct RewardProof { bytes32[] proof; } mapping(address => uint256) public rewards; mapping(address => bool) public staff; mapping(address => UserStakeInfo) private stakeUserInfo; mapping(uint256 => address) public tokenOwners; mapping(address => uint256) private _balances; //Staking root for offchain logic bytes32 private stakingRoot; modifier onlyAllowedContracts { require(staff[msg.sender] || msg.sender == owner()); _; } //events event Estake(address indexed _from, uint indexed _nftId); event EunStake(address indexed _from, uint indexed _nftId); constructor(address _nftAddress){ nft = IERC721(_nftAddress); //future liquidity Purposes _mint(msg.sender, 3650000 * 10 ** decimals()); } function mintForLiquidity(uint256 _amount) external onlyAllowedContracts{ _mint(msg.sender, _amount); } //staking function stake(uint256 _id, uint256 _reward, bytes32[] calldata _proof) public { _stake(msg.sender, _id, _reward, _proof); } //get staked NFT Ids function getStakedNftIds(address _account) public view returns(uint256[] memory) { UserStakeInfo storage user = stakeUserInfo[_account]; uint256[] memory stakedNfts = user.stakedTokens; return stakedNfts; } function getStakedAmount(address _account) public view returns(uint256) { UserStakeInfo storage user = stakeUserInfo[_account]; uint256[] memory stakedNfts = user.stakedTokens; return stakedNfts.length; } function getStakedLastRewardUpdated(address _account, uint256 _id) public view returns(uint256) { UserStakeInfo storage user = stakeUserInfo[_account]; return user.lastRewardUpdated[_id]; } function getStakedRewardInfo(address _account, uint256 _id) public view returns(uint256) { UserStakeInfo storage user = stakeUserInfo[_account]; return user.rewards[_id]; } function batchStake(uint256[] memory _ids, uint256[] memory _rewards, RewardProof[] calldata proofs ) public { uint256 len = _ids.length; for (uint256 i = 0; i < len; ++i) { _stake(msg.sender, _ids[i], _rewards[i], proofs[i].proof); } } function batchUnstake(address _user, uint256[] memory _ids) public { uint256 len = _ids.length; uint256 claimableRewards = getStakingRewards(_user); _balances[_user] += claimableRewards; _updateLastUpdated(_user); for (uint256 i = 0; i < len; ++i) { _unstake(_user, _ids[i]); } } function _stake( address _user, uint256 _id, uint256 _reward, bytes32[] calldata proof ) internal { //check if contract paused require(!paused, "Contract is paused"); //verify bonus from merkle require( _verify(_leaf(_id,_reward), proof), "Invalid proof" ); //end verify UserStakeInfo storage user = stakeUserInfo[_user]; nft.transferFrom( _user, address(this), _id ); user.lastRewardUpdated[_id] = block.timestamp; user.stakedTokens.push(_id); user.rewards[_id] = _reward; tokenOwners[_id] = _user; emit Estake(_user,_id); } function _unstake(address _user, uint256 _id) internal { UserStakeInfo storage user = stakeUserInfo[_user]; require( tokenOwners[_id] == _user, "Sender doesn't owns this token" ); _removeElement(user.stakedTokens, _id); delete tokenOwners[_id]; if (user.stakedTokens.length == 0) { delete stakeUserInfo[_user]; } nft.transferFrom( address(this), _user, _id ); emit EunStake(_user, _id); } function claimRewards() public { uint256 claimableRewards = getStakingRewards(msg.sender) + _balances[msg.sender]; _mint(msg.sender, claimableRewards); _updateLastUpdated(msg.sender); _balances[msg.sender] = 0; } function _updateLastUpdated(address _user) internal { UserStakeInfo storage user = stakeUserInfo[_user]; for (uint256 i; i < user.stakedTokens.length; i++) { uint256 _nftId = user.stakedTokens[i]; user.lastRewardUpdated[_nftId] = block.timestamp; } } function getCombinedRewards(address _user) public view returns (uint256) { uint256 reward = getStakingRewards(_user) + _balances[msg.sender]; return reward; } function getStakingRewards(address _user) public view returns (uint256) { uint256 time = block.timestamp; uint256 claimableRewards; UserStakeInfo storage user = stakeUserInfo[_user]; for(uint256 i =0; i < user.stakedTokens.length; i++){ uint256 _nftId = user.stakedTokens[i] ; //calculate rewards for the nft uint256 reward = user.rewards[_nftId] * 10 ** decimals(); //check if the rewards had been given or first time giving rewards for this nft id if (user.lastRewardUpdated[_nftId] == 0) { claimableRewards += 0; }else{ //calculate rewards from the last reward updated date uint256 rewardForNftStaked = reward .mul( time.sub(user.lastRewardUpdated[_nftId]) ) .div(rewardInterwal); claimableRewards += rewardForNftStaked; } } return claimableRewards; } function _removeElement(uint256[] storage _array, uint256 _element) internal { for (uint256 i; i < _array.length; i++) { if (_array[i] == _element) { _array[i] = _array[_array.length - 1]; _array.pop(); break; } } } function overideTranser(address _user, uint256 _id) public onlyOwner{ nft.transferFrom( address(this), _user, _id ); } function setRewardInterwal(uint256 _val) public onlyOwner{ rewardInterwal = _val; } function setStaffState(address _address, bool _state) public onlyOwner { staff[_address] = _state; } function togglePause() public onlyOwner { paused = !paused; } function burn(address _from, uint256 _amount) onlyAllowedContracts external { _burn(_from, _amount); } function _verify( bytes32 _leafNode, bytes32[] memory proof ) internal view returns (bool) { return MerkleProof.verify(proof, stakingRoot, _leafNode); } // Generate the leaf node (just the hash of tokenID concatenated with the account address) function _leaf(uint256 _nftId, uint256 _bonus ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_nftId,_bonus)); } function setStakingRoot(bytes32 _root) public onlyOwner { stakingRoot = _root; } }
Generate the leaf node (just the hash of tokenID concatenated with the account address)
function _leaf(uint256 _nftId, uint256 _bonus ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_nftId,_bonus)); }
6,788,770
// Ethereum Name Service contracts by Nick Johnson <[email protected]> // // To the extent possible under law, the person who associated CC0 with // ENS contracts has waived all copyright and related or neighboring rights // to ENS. // // You should have received a copy of the CC0 legalcode along with this // work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. /** * The ENS registry contract. */ contract ENS { struct Record { address owner; address resolver; } mapping(bytes32=>Record) records; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the owner of a node changes the resolver for that node. event NewResolver(bytes32 indexed node, address resolver); // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if(records[node].owner != msg.sender) throw; _ } /** * Constructs a new ENS registrar, with the provided address as the owner of the root node. */ function ENS(address owner) { records[0].owner = owner; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) constant returns (address) { return records[node].resolver; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode sha3(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) { var subnode = sha3(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) { NewResolver(node, resolver); records[node].resolver = resolver; } } /** * A registrar that allocates subdomains to the first person to claim them. It also deploys * a simple resolver contract and sets that as the default resolver on new names for * convenience. */ contract FIFSRegistrar { ENS ens; PublicResolver defaultResolver; bytes32 rootNode; /** * Constructor. * @param ensAddr The address of the ENS registry. * @param node The node that this registrar administers. */ function FIFSRegistrar(address ensAddr, bytes32 node) { ens = ENS(ensAddr); defaultResolver = new PublicResolver(ensAddr); rootNode = node; } /** * Register a name, or change the owner of an existing registration. * @param subnode The hash of the label to register. * @param owner The address of the new owner. */ function register(bytes32 subnode, address owner) { var node = sha3(rootNode, subnode); var currentOwner = ens.owner(node); if(currentOwner != 0 && currentOwner != msg.sender) throw; // Temporarily set ourselves as the owner ens.setSubnodeOwner(rootNode, subnode, this); // Set up the default resolver ens.setResolver(node, defaultResolver); // Set the owner to the real owner ens.setOwner(node, owner); } } contract Resolver { event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); function has(bytes32 node, bytes32 kind) returns (bool); function addr(bytes32 node) constant returns (address ret); function content(bytes32 node) constant returns (bytes32 ret); } /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver is Resolver { ENS ens; mapping(bytes32=>address) addresses; mapping(bytes32=>bytes32) contents; modifier only_owner(bytes32 node) { if(ens.owner(node) != msg.sender) throw; _ } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(address ensAddr) { ens = ENS(ensAddr); } /** * Fallback function. */ function() { throw; } /** * Returns true if the specified node has the specified record type. * @param node The ENS node to query. * @param kind The record type name, as specified in EIP137. * @return True if this resolver has a record of the provided type on the * provided node. */ function has(bytes32 node, bytes32 kind) returns (bool) { return (kind == "addr" && addresses[node] != 0) || (kind == "content" && contents[node] != 0); } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) constant returns (address ret) { ret = addresses[node]; if(ret == 0) throw; } /** * Returns the content hash associated with an ENS node. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) constant returns (bytes32 ret) { ret = contents[node]; if(ret == 0) throw; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) { addresses[node] = addr; AddrChanged(node, addr); } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The content hash to set. */ function setContent(bytes32 node, bytes32 hash) only_owner(node) { contents[node] = hash; ContentChanged(node, hash); } }
Sets the address associated with an ENS node. May only be called by the owner of that node in the ENS registry. node The node to update. addr The address to set./
function setAddr(bytes32 node, address addr) only_owner(node) { addresses[node] = addr; AddrChanged(node, addr); }
1,754,417
./partial_match/1/0xf4BC293A38bD1E3875Cfc141Ba81dd8E95F65f90/sources/StrategyConic.sol
Convert token route to encoded path uint24 type for fees so path is packed tightly
function routeToPath( address[] memory _route, uint24[] memory _fee ) internal pure returns (bytes memory path) { path = abi.encodePacked(_route[0]); uint256 feeLength = _fee.length; for (uint256 i = 0; i < feeLength; i++) { path = abi.encodePacked(path, _fee[i], _route[i+1]); } }
4,260,121
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "../client/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title A digital time capsule for images * @author John Park * @notice This smart contract's main purpose is to store the state for an image time capsule application. Along with basic inifo like unlock time, title, etc, private key used to encrypt the AES key and the encrypted AES key is stored for each entry */ contract TimeCapsule { using SafeMath for uint256; /// Custom type: Stores data about each encrypted image in IPFS struct Entry { uint256 id; uint256 unlockTime; address owner; string ipfs; string title; string ec_aes_key; string priv_key; bool isReleased; } /// State variables: mapping (uint256 => Entry) private entries; mapping(address => Entry[]) private ownerToEntries; bool public contractPaused = false; address payable public contractOwner; uint256 public counter; /// Events event EventEntry( uint256 id, string title, string ipfs, bool isReleased, uint256 unlockTime ); event EventRelease( uint256 id, address owner, string priv_key, string ec_aes_key, string ipfs, bool isReleased ); /// Modifiers modifier onlyContractOwner() { /// only the contract creator can call require(msg.sender == contractOwner); _; } modifier onlyOwner(uint256 _id) { /// only the creator of the entry/entries can call require(msg.sender == entries[_id].owner); _; } modifier checkIfPaused() { /// If the contract is paused, stop the modified function. Attach this modifier to all public functions require(contractPaused == false); _; } /** * @dev In order to avoid any complications that might arise from the fact that mining takes 10 to 20 seconds (such as frontrunning), the modifier has a wiggle room of 5 minutes. It's an extra precaution that might not be needed since you can only specify up to the day in the application UI */ modifier checkRelease(uint256 _id) { /// Note if the scale of your time-dependent event can vary by 15 seconds and maintain integrity, it is safe to use a block.timestamp / now require(now >= (entries[_id].unlockTime.sub(300))); _; } constructor() public { contractOwner = msg.sender; counter = 0; } /** * @author John Park * @notice Stores key pieces of information for an encrypted image * @param _unlockTime The time when an encrypted image is able to be decrypted (Unix timestamp in seconds) * @param _ipfs IPFS hash of the encrypted image * @param _title Title of the encrypted image * @param _ecAesKey Encrypted AES key -> AES key is used to encrypt the image. Public RSA key is used to encyrpt the AES key. Private RSA key is used to decrpt the encrypted AES key * @param _privKey Private RSA key -> AES key is used to encrypt the image. Public RSA key is used to encyrpt the AES key. Private RSA key is used to decrpt the encrypted AES key */ function appendEntry(uint256 _unlockTime, string memory _ipfs, string memory _title, string memory _ecAesKey, string memory _privKey) public checkIfPaused { /// Increment id counter for new entry counter = counter.add(1); /// Defining Entry Struct instance Entry memory entry = Entry( counter, _unlockTime, msg.sender, _ipfs, _title, _ecAesKey, _privKey, false ); entries[counter] = entry; ownerToEntries[msg.sender].push(entry); /// Trigger an event to communicate with the client that the entry has successfully been added to the blockchain emit EventEntry(counter, _title, _ipfs, false, _unlockTime); } /** * @author John Park * @notice Checks if it's time to decrypt an image by marking a boolean * @param _id The Entry id. Used to identify which image is to be marked as ready to be decrypted */ function release(uint256 _id) public checkRelease(_id) onlyOwner(_id) checkIfPaused { Entry storage entry = entries[_id]; /// Change isReleased value entry.isReleased = true; Entry[] storage senderEntries = ownerToEntries[msg.sender]; for (uint i=0; i<senderEntries.length; i++) { if (senderEntries[i].id == _id) { senderEntries[i].isReleased = true; } } /// Trigger an event to communicate with the client that the entry has been successfully designated as released emit EventRelease(_id, entry.owner, entry.priv_key, entry.ec_aes_key, entry.ipfs, true); } /** * @author John Park * @notice Fetches an Entry using _id as the unique identifier * @param _id The Entry id * @return An Entry struct */ function getEntry(uint256 _id) public view onlyOwner(_id) checkIfPaused returns(Entry memory) { return entries[_id]; } /** * @author John Park * @notice Fetches an array of all of the message sender's Entries * @return An array of Entries */ function getSenderEntries() public view checkIfPaused returns(Entry[] memory) { return ownerToEntries[msg.sender]; } /** * @author John Park * @notice Fetches the total number of Entries stored in the contract * @return Total number of Entries in the contract */ function getTotalEntries() public view checkIfPaused returns(uint256 x) { return counter; } /** * @author John Park * @notice Flips the value of contractPaused state variable so that the circuit breaker modifier kicks in */ function circuitBreaker() public onlyContractOwner { if (contractPaused == false) { contractPaused = true; } else { contractPaused = false; } } /** * @author John Park * @notice Kill the contract so that it's no longer accessible */ function close() public onlyContractOwner { selfdestruct(contractOwner); } }
John Park Checks if it's time to decrypt an image by marking a boolean _id The Entry id. Used to identify which image is to be marked as ready to be decrypted/
function release(uint256 _id) public checkRelease(_id) onlyOwner(_id) checkIfPaused { Entry storage entry = entries[_id]; entry.isReleased = true; Entry[] storage senderEntries = ownerToEntries[msg.sender]; } for (uint i=0; i<senderEntries.length; i++) { if (senderEntries[i].id == _id) { senderEntries[i].isReleased = true; } } for (uint i=0; i<senderEntries.length; i++) { if (senderEntries[i].id == _id) { senderEntries[i].isReleased = true; } } emit EventRelease(_id, entry.owner, entry.priv_key, entry.ec_aes_key, entry.ipfs, true); }
1,072,814
./partial_match/1/0xa1A7a95d7AD043b356D72b7c5fBE0eF053ba8c13/sources/contracts/Comptroller.sol
Calculate number of tokens of collateral asset to seize given an underlying amount Used in liquidation (called in slToken.liquidateBorrowFresh) slTokenBorrowed The address of the borrowed slToken slTokenCollateral The address of the collateral slToken actualRepayAmount The amount of slTokenBorrowed underlying to convert into slTokenCollateral tokens return (errorCode, number of slTokenCollateral tokens to be seized in a liquidation)/
function liquidateCalculateSeizeTokens(address slTokenBorrowed, address slTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { uint priceBorrowedMantissa = oracle.getUnderlyingPrice(SLToken(slTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(SLToken(slTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); uint seizeTokens; if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); }
11,022,824
/** *Submitted for verification at Etherscan.io on 2021-12-14 */ /** *Submitted for verification at Etherscan.io on 2021-10-07 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @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); } } pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } 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); } pragma solidity ^0.8.0; /** * @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; } } pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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 ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); } 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; } } pragma solidity ^0.8.0; /** * @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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ /** * @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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; string public _baseURI; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory base = baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; } /** * @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, can be overriden in child contracts. */ function baseURI() internal view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @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 (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` 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 tokenId ) internal virtual {} } pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } pragma solidity ^0.8.0; contract MysticAliens is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; uint public constant _TOTALSUPPLY =2022; uint public maxPerTx =5; uint256 public price = 0.15 ether; bool public isPaused = true; uint private tokenId=1; constructor(string memory baseURI) ERC721("MysticAliens", "MA") { setBaseURI(baseURI); } function setBaseURI(string memory baseURI) public onlyOwner { _baseURI = baseURI; } function setPrice(uint256 _newPrice) public onlyOwner() { price = _newPrice; } function setMaxxQtPerTx(uint256 _quantity) public onlyOwner { maxPerTx=_quantity; } modifier isSaleOpen{ require(totalSupply() < _TOTALSUPPLY, "Sale end"); _; } function flipPauseStatus() public onlyOwner { isPaused = !isPaused; } function getPrice(uint256 _quantity) public view returns (uint256) { return _quantity*price ; } function mint(uint chosenAmount) public payable isSaleOpen{ require(isPaused == false, "Sale is not active at the moment"); require(totalSupply()+chosenAmount<=_TOTALSUPPLY,"Quantity must be lesser then remaining NFTs"); require(chosenAmount > 0, "Number of NFTs can not be less than or equal to 0"); require(chosenAmount <= maxPerTx,"Chosen Amount exceeds MaxQuantity allowed per transaction"); require(chosenAmount+balanceOf(msg.sender)<=10, "Maximum of 10 NFTs can be owned by one person"); require(price.mul(chosenAmount) == msg.value,"Sent ether value is not correct"); for (uint i = 0; i < chosenAmount; i++) { _safeMint(msg.sender, totalsupply()); tokenId++; } } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory base = baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : ""; } function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 count = balanceOf(_owner); uint256[] memory result = new uint256[](count); for (uint256 index = 0; index < count; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function contractURI() public view returns (string memory) { string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Mystic Aliens", "description": "For decades, humans have researched and wondered about life beyond Earth. The search is finally over, 2022 Mystic Aliens have landed and they brought a spaceship full of otherworldly treasures - you too can reap the rewards of the Mystic Aliens one of a kind staking + DAO Protocol. APY that is out of this world, literally. Programmatically and randomly generated on the Ethereum Blockchain. Each Alien is unique, made from a combination of more than 50 attributes drawn by hand. A Mystic Alien is both a NFT collectible and a key to enter the spaceship and a lot more.", "seller_fee_basis_points": 1000, "fee_recipient": "0x2C0593Bbd2182C7818ab624FEC0d35EDad917C47"}')))); json = string(abi.encodePacked('data:application/json;base64,', json)); return json; } function totalsupply() private view returns (uint) { return tokenId; } } library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
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); }
1,274,337
./partial_match/1/0x52dAb11c6029862eBF1E65A4d5c30641f5FbD957/sources/AccountLogic.sol
called from 'enter'
function unfreeze(address payable _account) external allowSelfCallsOnly { require(accountStorage.getDelayDataHash(_account, UNFREEZE) == 0, "delay data already exists"); bytes32 hash = keccak256(abi.encodePacked('unfreeze', _account)); accountStorage.setDelayData(_account, UNFREEZE, hash, now + DELAY_UNFREEZE_KEY); }
16,014,817
./full_match/43113/0x015Cf48929c446E52CAbBc8fa2d83Ab6C1203Ab0/sources/Masterchef.sol
Update the max transfer amount rate. Can only be called by the current operator./
function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOperator { require(_maxTransferAmountRate <= 10000, "BUD::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate."); require(_maxTransferAmountRate >= 100, "BUD::updateMaxTransferAmountRate: Max transfer amount rate must exceed the minimum rate."); emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate); maxTransferAmountRate = _maxTransferAmountRate; }
7,144,800
// File: contracts/helpers/ERC20Like.sol // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; interface ERC20Like { function balanceOf(address) external view returns (uint); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function totalSupply() external view returns (uint256); } // File: contracts/helpers/ReentrancyGuard.sol pragma solidity ^0.7.1; /** * @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]. */ 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 () public { _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 make 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; } } // File: contracts/helpers/SafeMath.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: division by zero"); return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/VaultParameters.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title Auth * @author Unit Protocol: Artem Zakharov ([email protected]), Alexander Ponomorev (@bcngod) * @dev Manages USDP's system access **/ contract Auth { // address of the the contract with vault parameters VaultParameters public vaultParameters; constructor(address _parameters) public { vaultParameters = VaultParameters(_parameters); } // ensures tx's sender is a manager modifier onlyManager() { require(vaultParameters.isManager(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is able to modify the Vault modifier hasVaultAccess() { require(vaultParameters.canModifyVault(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is the Vault modifier onlyVault() { require(msg.sender == vaultParameters.vault(), "Unit Protocol: AUTH_FAILED"); _; } } /** * @title VaultParameters * @author Unit Protocol: Artem Zakharov ([email protected]), Alexander Ponomorev (@bcngod) **/ contract VaultParameters is Auth { // map token to stability fee percentage; 3 decimals mapping(address => uint) public stabilityFee; // map token to liquidation fee percentage, 0 decimals mapping(address => uint) public liquidationFee; // map token to USDP mint limit mapping(address => uint) public tokenDebtLimit; // permissions to modify the Vault mapping(address => bool) public canModifyVault; // managers mapping(address => bool) public isManager; // enabled oracle types mapping(uint => mapping (address => bool)) public isOracleTypeEnabled; // address of the Vault address payable public vault; // The foundation address address public foundation; /** * The address for an Ethereum contract is deterministically computed from the address of its creator (sender) * and how many transactions the creator has sent (nonce). The sender and nonce are RLP encoded and then * hashed with Keccak-256. * Therefore, the Vault address can be pre-computed and passed as an argument before deployment. **/ constructor(address payable _vault, address _foundation) public Auth(address(this)) { require(_vault != address(0), "Unit Protocol: ZERO_ADDRESS"); require(_foundation != address(0), "Unit Protocol: ZERO_ADDRESS"); isManager[msg.sender] = true; vault = _vault; foundation = _foundation; } /** * @notice Only manager is able to call this function * @dev Grants and revokes manager's status of any address * @param who The target address * @param permit The permission flag **/ function setManager(address who, bool permit) external onlyManager { isManager[who] = permit; } /** * @notice Only manager is able to call this function * @dev Sets the foundation address * @param newFoundation The new foundation address **/ function setFoundation(address newFoundation) external onlyManager { require(newFoundation != address(0), "Unit Protocol: ZERO_ADDRESS"); foundation = newFoundation; } /** * @notice Only manager is able to call this function * @dev Sets ability to use token as the main collateral * @param asset The address of the main collateral token * @param stabilityFeeValue The percentage of the year stability fee (3 decimals) * @param liquidationFeeValue The liquidation fee percentage (0 decimals) * @param usdpLimit The USDP token issue limit * @param oracles The enables oracle types **/ function setCollateral( address asset, uint stabilityFeeValue, uint liquidationFeeValue, uint usdpLimit, uint[] calldata oracles ) external onlyManager { setStabilityFee(asset, stabilityFeeValue); setLiquidationFee(asset, liquidationFeeValue); setTokenDebtLimit(asset, usdpLimit); for (uint i=0; i < oracles.length; i++) { setOracleType(oracles[i], asset, true); } } /** * @notice Only manager is able to call this function * @dev Sets a permission for an address to modify the Vault * @param who The target address * @param permit The permission flag **/ function setVaultAccess(address who, bool permit) external onlyManager { canModifyVault[who] = permit; } /** * @notice Only manager is able to call this function * @dev Sets the percentage of the year stability fee for a particular collateral * @param asset The address of the main collateral token * @param newValue The stability fee percentage (3 decimals) **/ function setStabilityFee(address asset, uint newValue) public onlyManager { stabilityFee[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the percentage of the liquidation fee for a particular collateral * @param asset The address of the main collateral token * @param newValue The liquidation fee percentage (0 decimals) **/ function setLiquidationFee(address asset, uint newValue) public onlyManager { require(newValue <= 100, "Unit Protocol: VALUE_OUT_OF_RANGE"); liquidationFee[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Enables/disables oracle types * @param _type The type of the oracle * @param asset The address of the main collateral token * @param enabled The control flag **/ function setOracleType(uint _type, address asset, bool enabled) public onlyManager { isOracleTypeEnabled[_type][asset] = enabled; } /** * @notice Only manager is able to call this function * @dev Sets USDP limit for a specific collateral * @param asset The address of the main collateral token * @param limit The limit number **/ function setTokenDebtLimit(address asset, uint limit) public onlyManager { tokenDebtLimit[asset] = limit; } } // File: contracts/helpers/TransferHelper.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts/USDP.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title USDP token implementation * @author Unit Protocol: Artem Zakharov ([email protected]), Alexander Ponomorev (@bcngod) * @dev ERC20 token **/ contract USDP is Auth { using SafeMath for uint; // name of the token string public constant name = "USDP Stablecoin"; // symbol of the token string public constant symbol = "USDP"; // version of the token string public constant version = "1"; // number of decimals the token uses uint8 public constant decimals = 18; // total token supply uint public totalSupply; // balance information map mapping(address => uint) public balanceOf; // token allowance mapping mapping(address => mapping(address => uint)) public allowance; /** * @dev Trigger on any successful call to approve(address spender, uint amount) **/ event Approval(address indexed owner, address indexed spender, uint value); /** * @dev Trigger when tokens are transferred, including zero value transfers **/ event Transfer(address indexed from, address indexed to, uint value); /** * @param _parameters The address of system parameters contract **/ constructor(address _parameters) public Auth(_parameters) {} /** * @notice Only Vault can mint USDP * @dev Mints 'amount' of tokens to address 'to', and MUST fire the * Transfer event * @param to The address of the recipient * @param amount The amount of token to be minted **/ function mint(address to, uint amount) external onlyVault { require(to != address(0), "Unit Protocol: ZERO_ADDRESS"); balanceOf[to] = balanceOf[to].add(amount); totalSupply = totalSupply.add(amount); emit Transfer(address(0), to, amount); } /** * @notice Only manager can burn tokens from manager's balance * @dev Burns 'amount' of tokens, and MUST fire the Transfer event * @param amount The amount of token to be burned **/ function burn(uint amount) external onlyManager { _burn(msg.sender, amount); } /** * @notice Only Vault can burn tokens from any balance * @dev Burns 'amount' of tokens from 'from' address, and MUST fire the Transfer event * @param from The address of the balance owner * @param amount The amount of token to be burned **/ function burn(address from, uint amount) external onlyVault { _burn(from, amount); } /** * @dev Transfers 'amount' of tokens to address 'to', and MUST fire the Transfer event. The * function SHOULD throw if the _from account balance does not have enough tokens to spend. * @param to The address of the recipient * @param amount The amount of token to be transferred **/ function transfer(address to, uint amount) external returns (bool) { return transferFrom(msg.sender, to, amount); } /** * @dev Transfers 'amount' of tokens from address 'from' to address 'to', and MUST fire the * Transfer event * @param from The address of the sender * @param to The address of the recipient * @param amount The amount of token to be transferred **/ function transferFrom(address from, address to, uint amount) public returns (bool) { require(to != address(0), "Unit Protocol: ZERO_ADDRESS"); require(balanceOf[from] >= amount, "Unit Protocol: INSUFFICIENT_BALANCE"); if (from != msg.sender) { require(allowance[from][msg.sender] >= amount, "Unit Protocol: INSUFFICIENT_ALLOWANCE"); _approve(from, msg.sender, allowance[from][msg.sender].sub(amount)); } balanceOf[from] = balanceOf[from].sub(amount); balanceOf[to] = balanceOf[to].add(amount); emit Transfer(from, to, amount); return true; } /** * @dev Allows 'spender' to withdraw from your account multiple times, up to the 'amount' amount. If * this function is called again it overwrites the current allowance with 'amount'. * @param spender The address of the account able to transfer the tokens * @param amount The amount of tokens to be approved for transfer **/ function approve(address spender, uint amount) external returns (bool) { _approve(msg.sender, spender, 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, uint addedValue) public virtual returns (bool) { _approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, allowance[msg.sender][spender].sub(subtractedValue)); return true; } function _approve(address owner, address spender, uint amount) internal virtual { require(owner != address(0), "Unit Protocol: approve from the zero address"); require(spender != address(0), "Unit Protocol: approve to the zero address"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burn(address from, uint amount) internal virtual { balanceOf[from] = balanceOf[from].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(from, address(0), amount); } } // File: contracts/helpers/IWETH.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: contracts/Vault.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title Vault * @author Unit Protocol: Artem Zakharov ([email protected]), Alexander Ponomorev (@bcngod) * @notice Vault is the core of Unit Protocol USDP Stablecoin system * @notice Vault stores and manages collateral funds of all positions and counts debts * @notice Only Vault can manage supply of USDP token * @notice Vault will not be changed/upgraded after initial deployment for the current stablecoin version **/ contract Vault is Auth { using SafeMath for uint; // COL token address address public immutable col; // WETH token address address payable public immutable weth; uint public constant DENOMINATOR_1E5 = 1e5; uint public constant DENOMINATOR_1E2 = 1e2; // USDP token address address public immutable usdp; // collaterals whitelist mapping(address => mapping(address => uint)) public collaterals; // COL token collaterals mapping(address => mapping(address => uint)) public colToken; // user debts mapping(address => mapping(address => uint)) public debts; // block number of liquidation trigger mapping(address => mapping(address => uint)) public liquidationBlock; // initial price of collateral mapping(address => mapping(address => uint)) public liquidationPrice; // debts of tokens mapping(address => uint) public tokenDebts; // stability fee pinned to each position mapping(address => mapping(address => uint)) public stabilityFee; // liquidation fee pinned to each position, 0 decimals mapping(address => mapping(address => uint)) public liquidationFee; // type of using oracle pinned for each position mapping(address => mapping(address => uint)) public oracleType; // timestamp of the last update mapping(address => mapping(address => uint)) public lastUpdate; modifier notLiquidating(address asset, address user) { require(liquidationBlock[asset][user] == 0, "Unit Protocol: LIQUIDATING_POSITION"); _; } /** * @param _parameters The address of the system parameters * @param _col COL token address * @param _usdp USDP token address **/ constructor(address _parameters, address _col, address _usdp, address payable _weth) public Auth(_parameters) { col = _col; usdp = _usdp; weth = _weth; } // only accept ETH via fallback from the WETH contract receive() external payable { require(msg.sender == weth, "Unit Protocol: RESTRICTED"); } /** * @dev Updates parameters of the position to the current ones * @param asset The address of the main collateral token * @param user The owner of a position **/ function update(address asset, address user) public hasVaultAccess notLiquidating(asset, user) { // calculate fee using stored stability fee uint debtWithFee = getTotalDebt(asset, user); tokenDebts[asset] = tokenDebts[asset].sub(debts[asset][user]).add(debtWithFee); debts[asset][user] = debtWithFee; stabilityFee[asset][user] = vaultParameters.stabilityFee(asset); liquidationFee[asset][user] = vaultParameters.liquidationFee(asset); lastUpdate[asset][user] = block.timestamp; } /** * @dev Creates new position for user * @param asset The address of the main collateral token * @param user The address of a position's owner * @param _oracleType The type of an oracle **/ function spawn(address asset, address user, uint _oracleType) external hasVaultAccess notLiquidating(asset, user) { oracleType[asset][user] = _oracleType; delete liquidationBlock[asset][user]; } /** * @dev Clears unused storage variables * @param asset The address of the main collateral token * @param user The address of a position's owner **/ function destroy(address asset, address user) public hasVaultAccess notLiquidating(asset, user) { delete stabilityFee[asset][user]; delete oracleType[asset][user]; delete lastUpdate[asset][user]; delete liquidationFee[asset][user]; } /** * @notice Tokens must be pre-approved * @dev Adds main collateral to a position * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of tokens to deposit **/ function depositMain(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { collaterals[asset][user] = collaterals[asset][user].add(amount); TransferHelper.safeTransferFrom(asset, user, address(this), amount); } /** * @dev Converts ETH to WETH and adds main collateral to a position * @param user The address of a position's owner **/ function depositEth(address user) external payable notLiquidating(weth, user) { IWETH(weth).deposit{value: msg.value}(); collaterals[weth][user] = collaterals[weth][user].add(msg.value); } /** * @dev Withdraws main collateral from a position * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of tokens to withdraw **/ function withdrawMain(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { collaterals[asset][user] = collaterals[asset][user].sub(amount); TransferHelper.safeTransfer(asset, user, amount); } /** * @dev Withdraws WETH collateral from a position converting WETH to ETH * @param user The address of a position's owner * @param amount The amount of ETH to withdraw **/ function withdrawEth(address payable user, uint amount) external hasVaultAccess notLiquidating(weth, user) { collaterals[weth][user] = collaterals[weth][user].sub(amount); IWETH(weth).withdraw(amount); TransferHelper.safeTransferETH(user, amount); } /** * @notice Tokens must be pre-approved * @dev Adds COL token to a position * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of tokens to deposit **/ function depositCol(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { colToken[asset][user] = colToken[asset][user].add(amount); TransferHelper.safeTransferFrom(col, user, address(this), amount); } /** * @dev Withdraws COL token from a position * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of tokens to withdraw **/ function withdrawCol(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { colToken[asset][user] = colToken[asset][user].sub(amount); TransferHelper.safeTransfer(col, user, amount); } /** * @dev Increases position's debt and mints USDP token * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of USDP to borrow **/ function borrow( address asset, address user, uint amount ) external hasVaultAccess notLiquidating(asset, user) returns(uint) { require(vaultParameters.isOracleTypeEnabled(oracleType[asset][user], asset), "Unit Protocol: WRONG_ORACLE_TYPE"); update(asset, user); debts[asset][user] = debts[asset][user].add(amount); tokenDebts[asset] = tokenDebts[asset].add(amount); // check USDP limit for token require(tokenDebts[asset] <= vaultParameters.tokenDebtLimit(asset), "Unit Protocol: ASSET_DEBT_LIMIT"); USDP(usdp).mint(user, amount); return debts[asset][user]; } /** * @dev Decreases position's debt and burns USDP token * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of USDP to repay * @return updated debt of a position **/ function repay( address asset, address user, uint amount ) external hasVaultAccess notLiquidating(asset, user) returns(uint) { uint debt = debts[asset][user]; debts[asset][user] = debt.sub(amount); tokenDebts[asset] = tokenDebts[asset].sub(amount); USDP(usdp).burn(user, amount); return debts[asset][user]; } /** * @dev Transfers fee to foundation * @param asset The address of the fee asset * @param user The address to transfer funds from * @param amount The amount of asset to transfer **/ function chargeFee(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { if (amount != 0) { TransferHelper.safeTransferFrom(asset, user, vaultParameters.foundation(), amount); } } /** * @dev Deletes position and transfers collateral to liquidation system * @param asset The address of the main collateral token * @param positionOwner The address of a position's owner * @param initialPrice The starting price of collateral in USDP **/ function triggerLiquidation( address asset, address positionOwner, uint initialPrice ) external hasVaultAccess notLiquidating(asset, positionOwner) { // reverts if oracle type is disabled require(vaultParameters.isOracleTypeEnabled(oracleType[asset][positionOwner], asset), "Unit Protocol: WRONG_ORACLE_TYPE"); // fix the debt debts[asset][positionOwner] = getTotalDebt(asset, positionOwner); liquidationBlock[asset][positionOwner] = block.number; liquidationPrice[asset][positionOwner] = initialPrice; } /** * @dev Internal liquidation process * @param asset The address of the main collateral token * @param positionOwner The address of a position's owner * @param mainAssetToLiquidator The amount of main asset to send to a liquidator * @param colToLiquidator The amount of COL to send to a liquidator * @param mainAssetToPositionOwner The amount of main asset to send to a position owner * @param colToPositionOwner The amount of COL to send to a position owner * @param repayment The repayment in USDP * @param penalty The liquidation penalty in USDP * @param liquidator The address of a liquidator **/ function liquidate( address asset, address positionOwner, uint mainAssetToLiquidator, uint colToLiquidator, uint mainAssetToPositionOwner, uint colToPositionOwner, uint repayment, uint penalty, address liquidator ) external hasVaultAccess { require(liquidationBlock[asset][positionOwner] != 0, "Unit Protocol: NOT_TRIGGERED_LIQUIDATION"); uint mainAssetInPosition = collaterals[asset][positionOwner]; uint mainAssetToFoundation = mainAssetInPosition.sub(mainAssetToLiquidator).sub(mainAssetToPositionOwner); uint colInPosition = colToken[asset][positionOwner]; uint colToFoundation = colInPosition.sub(colToLiquidator).sub(colToPositionOwner); delete liquidationPrice[asset][positionOwner]; delete liquidationBlock[asset][positionOwner]; delete debts[asset][positionOwner]; delete collaterals[asset][positionOwner]; delete colToken[asset][positionOwner]; destroy(asset, positionOwner); // charge liquidation fee and burn USDP if (repayment > penalty) { if (penalty != 0) { TransferHelper.safeTransferFrom(usdp, liquidator, vaultParameters.foundation(), penalty); } USDP(usdp).burn(liquidator, repayment.sub(penalty)); } else { if (repayment != 0) { TransferHelper.safeTransferFrom(usdp, liquidator, vaultParameters.foundation(), repayment); } } // send the part of collateral to a liquidator if (mainAssetToLiquidator != 0) { TransferHelper.safeTransfer(asset, liquidator, mainAssetToLiquidator); } if (colToLiquidator != 0) { TransferHelper.safeTransfer(col, liquidator, colToLiquidator); } // send the rest of collateral to a position owner if (mainAssetToPositionOwner != 0) { TransferHelper.safeTransfer(asset, positionOwner, mainAssetToPositionOwner); } if (colToPositionOwner != 0) { TransferHelper.safeTransfer(col, positionOwner, colToPositionOwner); } if (mainAssetToFoundation != 0) { TransferHelper.safeTransfer(asset, vaultParameters.foundation(), mainAssetToFoundation); } if (colToFoundation != 0) { TransferHelper.safeTransfer(col, vaultParameters.foundation(), colToFoundation); } } /** * @notice Only manager can call this function * @dev Changes broken oracle type to the correct one * @param asset The address of the main collateral token * @param user The address of a position's owner * @param newOracleType The new type of an oracle **/ function changeOracleType(address asset, address user, uint newOracleType) external onlyManager { oracleType[asset][user] = newOracleType; } /** * @dev Calculates the total amount of position's debt based on elapsed time * @param asset The address of the main collateral token * @param user The address of a position's owner * @return user debt of a position plus accumulated fee **/ function getTotalDebt(address asset, address user) public view returns (uint) { uint debt = debts[asset][user]; if (liquidationBlock[asset][user] != 0) return debt; uint fee = calculateFee(asset, user, debt); return debt.add(fee); } /** * @dev Calculates the amount of fee based on elapsed time and repayment amount * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The repayment amount * @return fee amount **/ function calculateFee(address asset, address user, uint amount) public view returns (uint) { uint sFeePercent = stabilityFee[asset][user]; uint timePast = block.timestamp.sub(lastUpdate[asset][user]); return amount.mul(sFeePercent).mul(timePast).div(365 days).div(DENOMINATOR_1E5); } } // File: contracts/vault-managers/VaultManagerParameters.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title VaultManagerParameters **/ contract VaultManagerParameters is Auth { // determines the minimum percentage of COL token part in collateral, 0 decimals mapping(address => uint) public minColPercent; // determines the maximum percentage of COL token part in collateral, 0 decimals mapping(address => uint) public maxColPercent; // map token to initial collateralization ratio; 0 decimals mapping(address => uint) public initialCollateralRatio; // map token to liquidation ratio; 0 decimals mapping(address => uint) public liquidationRatio; // map token to liquidation discount; 3 decimals mapping(address => uint) public liquidationDiscount; // map token to devaluation period in blocks mapping(address => uint) public devaluationPeriod; constructor(address _vaultParameters) public Auth(_vaultParameters) {} /** * @notice Only manager is able to call this function * @dev Sets ability to use token as the main collateral * @param asset The address of the main collateral token * @param stabilityFeeValue The percentage of the year stability fee (3 decimals) * @param liquidationFeeValue The liquidation fee percentage (0 decimals) * @param initialCollateralRatioValue The initial collateralization ratio * @param liquidationRatioValue The liquidation ratio * @param liquidationDiscountValue The liquidation discount (3 decimals) * @param devaluationPeriodValue The devaluation period in blocks * @param usdpLimit The USDP token issue limit * @param oracles The enabled oracles type IDs * @param minColP The min percentage of COL value in position (0 decimals) * @param maxColP The max percentage of COL value in position (0 decimals) **/ function setCollateral( address asset, uint stabilityFeeValue, uint liquidationFeeValue, uint initialCollateralRatioValue, uint liquidationRatioValue, uint liquidationDiscountValue, uint devaluationPeriodValue, uint usdpLimit, uint[] calldata oracles, uint minColP, uint maxColP ) external onlyManager { vaultParameters.setCollateral(asset, stabilityFeeValue, liquidationFeeValue, usdpLimit, oracles); setInitialCollateralRatio(asset, initialCollateralRatioValue); setLiquidationRatio(asset, liquidationRatioValue); setDevaluationPeriod(asset, devaluationPeriodValue); setLiquidationDiscount(asset, liquidationDiscountValue); setColPartRange(asset, minColP, maxColP); } /** * @notice Only manager is able to call this function * @dev Sets the initial collateral ratio * @param asset The address of the main collateral token * @param newValue The collateralization ratio (0 decimals) **/ function setInitialCollateralRatio(address asset, uint newValue) public onlyManager { require(newValue != 0 && newValue <= 100, "Unit Protocol: INCORRECT_COLLATERALIZATION_VALUE"); initialCollateralRatio[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the liquidation ratio * @param asset The address of the main collateral token * @param newValue The liquidation ratio (0 decimals) **/ function setLiquidationRatio(address asset, uint newValue) public onlyManager { require(newValue != 0 && newValue >= initialCollateralRatio[asset], "Unit Protocol: INCORRECT_COLLATERALIZATION_VALUE"); liquidationRatio[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the liquidation discount * @param asset The address of the main collateral token * @param newValue The liquidation discount (3 decimals) **/ function setLiquidationDiscount(address asset, uint newValue) public onlyManager { require(newValue < 1e5, "Unit Protocol: INCORRECT_DISCOUNT_VALUE"); liquidationDiscount[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the devaluation period of collateral after liquidation * @param asset The address of the main collateral token * @param newValue The devaluation period in blocks **/ function setDevaluationPeriod(address asset, uint newValue) public onlyManager { require(newValue != 0, "Unit Protocol: INCORRECT_DEVALUATION_VALUE"); devaluationPeriod[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the percentage range of the COL token part for specific collateral token * @param asset The address of the main collateral token * @param min The min percentage (0 decimals) * @param max The max percentage (0 decimals) **/ function setColPartRange(address asset, uint min, uint max) public onlyManager { require(max <= 100 && min <= max, "Unit Protocol: WRONG_RANGE"); minColPercent[asset] = min; maxColPercent[asset] = max; } } // File: contracts/liquidators/LiquidationTriggerBase.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title LiquidationTriggerSimple * @dev Manages triggering of liquidation process **/ abstract contract LiquidationTriggerBase { using SafeMath for uint; uint public constant DENOMINATOR_1E5 = 1e5; uint public constant DENOMINATOR_1E2 = 1e2; // vault manager parameters contract VaultManagerParameters public immutable vaultManagerParameters; uint public immutable oracleType; // Vault contract Vault public immutable vault; /** * @dev Trigger when liquidations are initiated **/ event LiquidationTriggered(address indexed token, address indexed user); /** * @param _vaultManagerParameters The address of the contract with vault manager parameters * @param _oracleType The id of the oracle type **/ constructor(address _vaultManagerParameters, uint _oracleType) internal { vaultManagerParameters = VaultManagerParameters(_vaultManagerParameters); vault = Vault(VaultManagerParameters(_vaultManagerParameters).vaultParameters().vault()); oracleType = _oracleType; } /** * @dev Triggers liquidation of a position * @param asset The address of the main collateral token of a position * @param user The owner of a position **/ function triggerLiquidation(address asset, address user) external virtual {} /** * @dev Determines whether a position is liquidatable * @param asset The address of the main collateral token of a position * @param user The owner of a position * @param collateralUsdValue USD value of the collateral * @return boolean value, whether a position is liquidatable **/ function isLiquidatablePosition( address asset, address user, uint collateralUsdValue ) public virtual view returns (bool); /** * @dev Calculates position's utilization ratio * @param collateralUsdValue USD value of collateral * @param debt USDP borrowed * @return utilization ratio of a position **/ function UR(uint collateralUsdValue, uint debt) public virtual pure returns (uint); } // File: contracts/oracles/OracleSimple.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title OracleSimple **/ abstract contract OracleSimple { function assetToUsd(address asset, uint amount) public virtual view returns (uint); } /** * @title OracleSimplePoolToken **/ abstract contract OracleSimplePoolToken is OracleSimple { ChainlinkedOracleSimple public oracleMainAsset; } /** * @title ChainlinkedOracleSimple **/ abstract contract ChainlinkedOracleSimple is OracleSimple { address public WETH; function ethToUsd(uint ethAmount) public virtual view returns (uint); function assetToEth(address asset, uint amount) public virtual view returns (uint); } // File: contracts/liquidators/LiquidationTriggerSimple.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; /** * @title LiquidationTriggerSimple * @dev Manages liquidation triggering **/ contract LiquidationTriggerSimple is LiquidationTriggerBase, ReentrancyGuard { using SafeMath for uint; OracleSimple public immutable oracle; uint public constant Q112 = 2**112; /** * @param _vaultManagerParameters The address of the contract with vault manager parameters * @param _oracle The address of simple oracle * @param _oracleType The id of the oracle type **/ constructor( address _vaultManagerParameters, address _oracle, uint _oracleType ) public LiquidationTriggerBase(_vaultManagerParameters, _oracleType) { oracle = OracleSimple(_oracle); } /** * @dev Determines whether a position is liquidatable * @param asset The address of the main collateral token of a position * @param user The owner of a position * @param mainUsdValue_q112 Q112-encoded USD value of the main collateral * @return boolean value, whether a position is liquidatable **/ function isLiquidatablePosition( address asset, address user, uint mainUsdValue_q112 ) public override view returns (bool){ uint debt = vault.getTotalDebt(asset, user); // position is collateralized if there is no debt if (debt == 0) return false; require(vault.oracleType(asset, user) == oracleType, "Unit Protocol: INCORRECT_ORACLE_TYPE"); return UR(mainUsdValue_q112, debt) >= vaultManagerParameters.liquidationRatio(asset); } /** * @dev Triggers liquidation of a position * @param asset The address of the main collateral token of a position * @param user The owner of a position **/ function triggerLiquidation(address asset, address user) public override nonReentrant { // USD value of the main collateral uint mainUsdValue_q112 = oracle.assetToUsd(asset, vault.collaterals(asset, user)); // reverts if a position is not liquidatable require(isLiquidatablePosition(asset, user, mainUsdValue_q112), "Unit Protocol: SAFE_POSITION"); uint liquidationDiscount_q112 = mainUsdValue_q112.mul( vaultManagerParameters.liquidationDiscount(asset) ).div(DENOMINATOR_1E5); uint initialLiquidationPrice = mainUsdValue_q112.sub(liquidationDiscount_q112).div(Q112); // sends liquidation command to the Vault vault.triggerLiquidation(asset, user, initialLiquidationPrice); // fire an liquidation event emit LiquidationTriggered(asset, user); } /** * @dev Calculates position's utilization ratio * @param mainUsdValue USD value of main collateral, q112 format * @param debt USDP borrowed * @return utilization ratio of a position **/ function UR(uint mainUsdValue, uint debt) public override pure returns (uint) { return debt.mul(100).mul(Q112).div(mainUsdValue); } }
Transfers 'amount' of tokens from address 'from' to address 'to', and MUST fire the Transfer event from The address of the sender to The address of the recipient amount The amount of token to be transferred/
function transferFrom(address from, address to, uint amount) public returns (bool) { require(to != address(0), "Unit Protocol: ZERO_ADDRESS"); require(balanceOf[from] >= amount, "Unit Protocol: INSUFFICIENT_BALANCE"); if (from != msg.sender) { require(allowance[from][msg.sender] >= amount, "Unit Protocol: INSUFFICIENT_ALLOWANCE"); _approve(from, msg.sender, allowance[from][msg.sender].sub(amount)); } balanceOf[from] = balanceOf[from].sub(amount); balanceOf[to] = balanceOf[to].add(amount); emit Transfer(from, to, amount); return true; }
276,395
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; // Part: IBasicRewards interface IBasicRewards { function stakeFor(address, uint256) external returns (bool); function balanceOf(address) external view returns (uint256); function earned(address) external view returns (uint256); function withdrawAll(bool) external returns (bool); function withdraw(uint256, bool) external returns (bool); function getReward() external returns (bool); function stake(uint256) external returns (bool); } // Part: ICurveFactoryPool interface ICurveFactoryPool { function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_balances() external view returns (uint256[2] memory); function add_liquidity( uint256[2] memory _amounts, uint256 _min_mint_amount, address _receiver ) external returns (uint256); function exchange( int128 i, int128 j, uint256 _dx, uint256 _min_dy, address _receiver ) external returns (uint256); } // Part: ICurveV2Pool interface ICurveV2Pool { function get_dy( uint256 i, uint256 j, uint256 dx ) external view returns (uint256); function exchange_underlying( uint256 i, uint256 j, uint256 dx, uint256 min_dy ) external payable returns (uint256); } // Part: ICvxCrvDeposit interface ICvxCrvDeposit { function deposit(uint256, bool) external; } // Part: IMerkleDistributorV2 interface IMerkleDistributorV2 { enum Option { Claim, ClaimAsETH, ClaimAsCRV, ClaimAsCVX, ClaimAndStake } function vault() external view returns (address); function merkleRoot() external view returns (bytes32); function week() external view returns (uint32); function frozen() external view returns (bool); function isClaimed(uint256 index) external view returns (bool); function setApprovals() external; function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, Option option ) external; function freeze() external; function unfreeze() external; function stake() external; function updateMerkleRoot(bytes32 newMerkleRoot, bool unfreeze) external; event Claimed( uint256 index, uint256 amount, address indexed account, uint256 indexed week, Option option ); event MerkleRootUpdated(bytes32 indexed merkleRoot, uint32 indexed week); } // Part: IMultiMerkleStash interface IMultiMerkleStash { struct claimParam { address token; uint256 index; uint256 amount; bytes32[] merkleProof; } function isClaimed(address token, uint256 index) external view returns (bool); function claim( address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; function claimMulti(address account, claimParam[] calldata claims) external; function updateMerkleRoot(address token, bytes32 _merkleRoot) external; event Claimed( address indexed token, uint256 index, uint256 amount, address indexed account, uint256 indexed update ); event MerkleRootUpdated( address indexed token, bytes32 indexed merkleRoot, uint256 indexed update ); } // Part: IUniV2Router interface IUniV2Router { function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: IUniV3Router interface IUniV3Router { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } function exactInputSingle(ExactInputSingleParams calldata params) external returns (uint256 amountOut); } // Part: IVotiumRegistry interface IVotiumRegistry { struct Registry { uint256 start; address to; uint256 expiration; } function registry(address _from) external view returns (Registry memory registry); function setRegistry(address _to) external; } // Part: IWETH interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // Part: OpenZeppelin/[email protected]/Address /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Ownable /** * @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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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' // solhint-disable-next-line max-line-length 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)); } } /** * @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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: UnionBase // Common variables and functions contract UnionBase { address public constant CVXCRV_STAKING_CONTRACT = 0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e; address public constant CURVE_CRV_ETH_POOL = 0x8301AE4fc9c624d1D396cbDAa1ed877821D7C511; address public constant CURVE_CVX_ETH_POOL = 0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4; address public constant CURVE_CVXCRV_CRV_POOL = 0x9D0464996170c6B9e75eED71c68B99dDEDf279e8; address public constant CRV_TOKEN = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant CVXCRV_TOKEN = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7; address public constant CVX_TOKEN = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; uint256 public constant CRVETH_ETH_INDEX = 0; uint256 public constant CRVETH_CRV_INDEX = 1; int128 public constant CVXCRV_CRV_INDEX = 0; int128 public constant CVXCRV_CVXCRV_INDEX = 1; uint256 public constant CVXETH_ETH_INDEX = 0; uint256 public constant CVXETH_CVX_INDEX = 1; IBasicRewards cvxCrvStaking = IBasicRewards(CVXCRV_STAKING_CONTRACT); ICurveV2Pool cvxEthSwap = ICurveV2Pool(CURVE_CVX_ETH_POOL); ICurveV2Pool crvEthSwap = ICurveV2Pool(CURVE_CRV_ETH_POOL); ICurveFactoryPool crvCvxCrvSwap = ICurveFactoryPool(CURVE_CVXCRV_CRV_POOL); /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @return amount of CRV obtained after the swap function _swapCrvToCvxCrv(uint256 amount, address recipient) internal returns (uint256) { return _crvToCvxCrv(amount, recipient, 0); } /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapCrvToCvxCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return _crvToCvxCrv(amount, recipient, minAmountOut); } /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _crvToCvxCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return crvCvxCrvSwap.exchange( CVXCRV_CRV_INDEX, CVXCRV_CVXCRV_INDEX, amount, minAmountOut, recipient ); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @return amount of CRV obtained after the swap function _swapCvxCrvToCrv(uint256 amount, address recipient) internal returns (uint256) { return _cvxCrvToCrv(amount, recipient, 0); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapCvxCrvToCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return _cvxCrvToCrv(amount, recipient, minAmountOut); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _cvxCrvToCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return crvCvxCrvSwap.exchange( CVXCRV_CVXCRV_INDEX, CVXCRV_CRV_INDEX, amount, minAmountOut, recipient ); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @return amount of ETH obtained after the swap function _swapCrvToEth(uint256 amount) internal returns (uint256) { return _crvToEth(amount, 0); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of ETH obtained after the swap function _swapCrvToEth(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _crvToEth(amount, minAmountOut); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of ETH obtained after the swap function _crvToEth(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return crvEthSwap.exchange_underlying{value: 0}( CRVETH_CRV_INDEX, CRVETH_ETH_INDEX, amount, minAmountOut ); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @return amount of CRV obtained after the swap function _swapEthToCrv(uint256 amount) internal returns (uint256) { return _ethToCrv(amount, 0); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapEthToCrv(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _ethToCrv(amount, minAmountOut); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _ethToCrv(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return crvEthSwap.exchange_underlying{value: amount}( CRVETH_ETH_INDEX, CRVETH_CRV_INDEX, amount, minAmountOut ); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @return amount of CRV obtained after the swap function _swapEthToCvx(uint256 amount) internal returns (uint256) { return _ethToCvx(amount, 0); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapEthToCvx(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _ethToCvx(amount, minAmountOut); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _ethToCvx(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return cvxEthSwap.exchange_underlying{value: amount}( CVXETH_ETH_INDEX, CVXETH_CVX_INDEX, amount, minAmountOut ); } } // File: UnionZap.sol contract UnionZap is Ownable, UnionBase { using SafeERC20 for IERC20; address public votiumDistributor = 0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A; address public unionDistributor; address private constant SUSHI_ROUTER = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address private constant UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private constant CVXCRV_DEPOSIT = 0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae; address public constant VOTIUM_REGISTRY = 0x92e6E43f99809dF84ed2D533e1FD8017eb966ee2; uint256 private constant BASE_TX_GAS = 21000; uint256 private constant FINAL_TRANSFER_GAS = 50000; uint256 public unionDues = 200; uint256 public constant FEE_DENOMINATOR = 10000; uint256 public constant MAX_DUES = 400; mapping(uint256 => address) private routers; mapping(uint256 => uint24) private fees; struct claimParam { address token; uint256 index; uint256 amount; bytes32[] merkleProof; } event Received(address sender, uint256 amount); event Distributed(uint256 amount, uint256 fees, bool locked); event DistributorUpdated(address distributor); event VotiumDistributorUpdated(address distributor); event DuesUpdated(uint256 dues); event FundsRetrieved(address token, address to, uint256 amount); constructor(address distributor_) { unionDistributor = distributor_; routers[0] = SUSHI_ROUTER; routers[1] = UNISWAP_ROUTER; fees[0] = 3000; fees[1] = 10000; } /// @notice Update union fees /// @param dues - Fees taken from the collected bribes in bips function setUnionDues(uint256 dues) external onlyOwner { require(dues <= MAX_DUES, "Dues too high"); unionDues = dues; emit DuesUpdated(dues); } /// @notice Update the contract used to distribute funds /// @param distributor_ - Address of the new contract function updateDistributor(address distributor_) external onlyOwner { require(distributor_ != address(0)); unionDistributor = distributor_; emit DistributorUpdated(distributor_); } /// @notice Change forwarding address in Votium registry /// @param _to - address that will be forwarded to /// @dev To be used in case of migration, rewards can be forwarded to /// new contracts function setForwarding(address _to) external onlyOwner { IVotiumRegistry(VOTIUM_REGISTRY).setRegistry(_to); } /// @notice Update the votium contract address to claim for /// @param distributor_ - Address of the new contract function updateVotiumDistributor(address distributor_) external onlyOwner { require(distributor_ != address(0)); votiumDistributor = distributor_; emit VotiumDistributorUpdated(distributor_); } /// @notice Withdraws specified ERC20 tokens to the multisig /// @param tokens - the tokens to retrieve /// @param to - address to send the tokens to /// @dev This is needed to handle tokens that don't have ETH pairs on sushi /// or need to be swapped on other chains (NBST, WormholeLUNA...) function retrieveTokens(address[] calldata tokens, address to) external onlyOwner { require(to != address(0)); for (uint256 i; i < tokens.length; ++i) { address token = tokens[i]; uint256 tokenBalance = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransfer(to, tokenBalance); emit FundsRetrieved(token, to, tokenBalance); } } /// @notice Execute calls on behalf of contract in case of emergency function execute( address _to, uint256 _value, bytes calldata _data ) external onlyOwner returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value: _value}(_data); return (success, result); } /// @notice Set approvals for the tokens used when swapping function setApprovals() external onlyOwner { IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 0); IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 2**256 - 1); IERC20(CRV_TOKEN).safeApprove(CVXCRV_DEPOSIT, 0); IERC20(CRV_TOKEN).safeApprove(CVXCRV_DEPOSIT, 2**256 - 1); IERC20(CVXCRV_TOKEN).safeApprove(CVXCRV_STAKING_CONTRACT, 0); IERC20(CVXCRV_TOKEN).safeApprove(CVXCRV_STAKING_CONTRACT, 2**256 - 1); } /// @notice Swap a token for ETH /// @param token - address of the token to swap /// @param amount - amount of the token to swap /// @dev Swaps are executed via Sushi or UniV2 router, will revert if pair /// does not exist. Tokens must have a WETH pair. function _swapToETH( address token, uint256 amount, address router ) internal { require(router != address(0)); address[] memory _path = new address[](2); _path[0] = token; _path[1] = WETH; IERC20(token).safeApprove(router, 0); IERC20(token).safeApprove(router, amount); IUniV2Router(router).swapExactTokensForETH( amount, 0, _path, address(this), block.timestamp + 1 ); } /// @notice Swap a token for ETH on UniSwap V3 /// @param token - address of the token to swap /// @param amount - amount of the token to swap /// @param fee - the pool's fee function _swapToETHUniV3( address token, uint256 amount, uint24 fee ) internal { IERC20(token).safeApprove(UNIV3_ROUTER, 0); IERC20(token).safeApprove(UNIV3_ROUTER, amount); IUniV3Router.ExactInputSingleParams memory _params = IUniV3Router .ExactInputSingleParams( token, WETH, fee, address(this), block.timestamp + 1, amount, 1, 0 ); uint256 _wethReceived = IUniV3Router(UNIV3_ROUTER).exactInputSingle( _params ); IWETH(WETH).withdraw(_wethReceived); } /// @notice Claims all specified rewards from Votium /// @param claimParams - an array containing the info necessary to claim for /// each available token /// @dev Used to retrieve tokens that need to be transferred function claim(IMultiMerkleStash.claimParam[] calldata claimParams) public onlyOwner { require(claimParams.length > 0, "No claims"); // claim all from votium IMultiMerkleStash(votiumDistributor).claimMulti( address(this), claimParams ); } /// @notice Claims all specified rewards and swaps them to ETH /// @param claimParams - an array containing the info necessary to claim /// @param routerChoices - the router to use for the swap /// @param claimBeforeSwap - whether to claim on Votium or not /// @param lock - whether to lock or swap crv to cvxcrv /// @param stake - whether to stake cvxcrv (if distributor is vault) /// @dev routerChoices is a 2-bit bitmap such that /// 0b00 (0) - Sushi /// 0b01 (1) - UniV2 /// 0b10 (2) - UniV3 0.3% /// 0b11 (3) - UniV3 1% /// Ex: 6 = 00 01 10 will swap token 1 on UniV3, 2 on UniV3, last on Sushi /// Passing 0 will execute all swaps on sushi /// @dev claimBeforeSwap is used in case 3rd party already claimed on Votium function _distribute( IMultiMerkleStash.claimParam[] calldata claimParams, uint256 routerChoices, bool claimBeforeSwap, bool lock, bool stake ) internal { // initialize gas counting uint256 _startGas = gasleft(); bool _locked = false; // claim if (claimBeforeSwap) { claim(claimParams); } // swap all claims to ETH for (uint256 i; i < claimParams.length; ++i) { address _token = claimParams[i].token; uint256 _balance = IERC20(_token).balanceOf(address(this)); // avoid wasting gas / reverting if no balance if (_balance <= 1) { continue; } else { // leave one gwei to lower future claim gas costs // https://twitter.com/libevm/status/1474870670429360129?s=21 _balance -= 1; } // unwrap WETH if (_token == WETH) { IWETH(WETH).withdraw(_balance); } // no need to swap bribes paid out in cvxCRV or CRV else if ((_token == CRV_TOKEN) || (_token == CVXCRV_TOKEN)) { continue; } else { uint256 _choice = routerChoices & 3; if (_choice >= 2) { _swapToETHUniV3(_token, _balance, fees[_choice - 2]); } else { _swapToETH(_token, _balance, routers[_choice]); } } routerChoices = routerChoices >> 2; } uint256 _ethBalance = address(this).balance; // swap from ETH to CRV uint256 _swappedCrv = _swapEthToCrv(_ethBalance); uint256 _crvBalance = IERC20(CRV_TOKEN).balanceOf(address(this)); // swap on Curve if there is a premium for doing so if (!lock) { _swapCrvToCvxCrv(_crvBalance, address(this)); } // otherwise deposit & lock else { ICvxCrvDeposit(CVXCRV_DEPOSIT).deposit(_crvBalance, true); _locked = true; } uint256 _cvxCrvBalance = IERC20(CVXCRV_TOKEN).balanceOf(address(this)); // freeze distributor before transferring funds IMerkleDistributorV2(unionDistributor).freeze(); // estimate gas cost uint256 _gasUsed = _startGas - gasleft() + BASE_TX_GAS + 16 * msg.data.length + FINAL_TRANSFER_GAS; // compute the ETH/CRV exchange rate based on previous curve swap uint256 _gasCostInCrv = (_gasUsed * tx.gasprice * _swappedCrv) / _ethBalance; uint256 _fees = (_cvxCrvBalance * unionDues) / FEE_DENOMINATOR; uint256 _netDeposit = _cvxCrvBalance - _fees - _gasCostInCrv; // transfer funds IERC20(CVXCRV_TOKEN).safeTransfer(unionDistributor, _netDeposit); if (stake) { IMerkleDistributorV2(unionDistributor).stake(); } emit Distributed(_netDeposit, _cvxCrvBalance - _netDeposit, _locked); } /// @notice External wrapper around _distribute /// @param claimParams - an array containing the info necessary to claim /// @param routerChoices - the router to use for the swap /// @param claimBeforeSwap - whether to claim on Votium or not /// @param lock - whether to lock or swap crv to cvxcrv function distribute( IMultiMerkleStash.claimParam[] calldata claimParams, uint256 routerChoices, bool claimBeforeSwap, bool lock ) external onlyOwner { _distribute(claimParams, routerChoices, claimBeforeSwap, lock, true); } /// @notice External wrapper around _distribute /// @param claimParams - an array containing the info necessary to claim /// @param routerChoices - the router to use for the swap /// @param claimBeforeSwap - whether to claim on Votium or not /// @param lock - whether to lock or swap crv to cvxcrv /// @param stake - whether to stake cvxcrv (if distributor is vault) /// @dev Overloads distribute above to allow specifying a stake param to /// switch between regular distributor and vault distributor (v2) function distribute( IMultiMerkleStash.claimParam[] calldata claimParams, uint256 routerChoices, bool claimBeforeSwap, bool lock, bool stake ) external onlyOwner { _distribute(claimParams, routerChoices, claimBeforeSwap, lock, stake); } // @notice Stakes the accumulated cvxCrv for the owner function stakeAccumulated() external onlyOwner { cvxCrvStaking.stakeFor( owner(), IERC20(CVXCRV_TOKEN).balanceOf(address(this)) - 1 ); } receive() external payable { emit Received(msg.sender, msg.value); } }
Claims all specified rewards and swaps them to ETH claimParams - an array containing the info necessary to claim routerChoices - the router to use for the swap claimBeforeSwap - whether to claim on Votium or not lock - whether to lock or swap crv to cvxcrv stake - whether to stake cvxcrv (if distributor is vault) routerChoices is a 2-bit bitmap such that 0b00 (0) - Sushi 0b01 (1) - UniV2 0b10 (2) - UniV3 0.3% 0b11 (3) - UniV3 1% Ex: 6 = 00 01 10 will swap token 1 on UniV3, 2 on UniV3, last on Sushi Passing 0 will execute all swaps on sushi claimBeforeSwap is used in case 3rd party already claimed on Votium initialize gas counting claim swap all claims to ETH avoid wasting gas / reverting if no balance leave one gwei to lower future claim gas costs https:twitter.com/libevm/status/1474870670429360129?s=21 unwrap WETH no need to swap bribes paid out in cvxCRV or CRV swap on Curve if there is a premium for doing so otherwise deposit & lock
function _distribute( IMultiMerkleStash.claimParam[] calldata claimParams, uint256 routerChoices, bool claimBeforeSwap, bool lock, bool stake ) internal { uint256 _startGas = gasleft(); bool _locked = false; if (claimBeforeSwap) { claim(claimParams); } for (uint256 i; i < claimParams.length; ++i) { address _token = claimParams[i].token; uint256 _balance = IERC20(_token).balanceOf(address(this)); if (_balance <= 1) { continue; _balance -= 1; } if (_token == WETH) { IWETH(WETH).withdraw(_balance); } else if ((_token == CRV_TOKEN) || (_token == CVXCRV_TOKEN)) { continue; uint256 _choice = routerChoices & 3; if (_choice >= 2) { _swapToETHUniV3(_token, _balance, fees[_choice - 2]); _swapToETH(_token, _balance, routers[_choice]); } } routerChoices = routerChoices >> 2; } uint256 _ethBalance = address(this).balance; uint256 _crvBalance = IERC20(CRV_TOKEN).balanceOf(address(this)); if (!lock) { _swapCrvToCvxCrv(_crvBalance, address(this)); } else { ICvxCrvDeposit(CVXCRV_DEPOSIT).deposit(_crvBalance, true); _locked = true; } uint256 _cvxCrvBalance = IERC20(CVXCRV_TOKEN).balanceOf(address(this)); gasleft() + BASE_TX_GAS + 16 * msg.data.length + FINAL_TRANSFER_GAS; _ethBalance; uint256 _fees = (_cvxCrvBalance * unionDues) / FEE_DENOMINATOR; uint256 _netDeposit = _cvxCrvBalance - _fees - _gasCostInCrv; if (stake) { IMerkleDistributorV2(unionDistributor).stake(); } emit Distributed(_netDeposit, _cvxCrvBalance - _netDeposit, _locked); }
14,572,682
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../interface/RocketStorageInterface.sol"; /// @title Base settings / modifiers for each contract in Rocket Pool /// @author David Rugendyke abstract contract RocketBase { // Calculate using this as the base uint256 constant calcBase = 1 ether; // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained RocketStorageInterface rocketStorage = RocketStorageInterface(0); /*** Modifiers **********************************************************/ /** * @dev Throws if called by any sender that doesn't match a Rocket Pool network contract */ modifier onlyLatestNetworkContract() { require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract"); _; } /** * @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract */ modifier onlyLatestContract(string memory _contractName, address _contractAddress) { require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract"); _; } /** * @dev Throws if called by any sender that isn't a registered node */ modifier onlyRegisteredNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node"); _; } /** * @dev Throws if called by any sender that isn't a trusted node DAO member */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered minipool */ modifier onlyRegisteredMinipool(address _minipoolAddress) { require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool"); _; } /** * @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled) */ modifier onlyGuardian() { require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian"); _; } /*** Methods **********************************************************/ /// @dev Set the main Rocket Storage address constructor(RocketStorageInterface _rocketStorageAddress) { // Update the contract address rocketStorage = RocketStorageInterface(_rocketStorageAddress); } /// @dev Get the address of a network contract by name function getContractAddress(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Check it require(contractAddress != address(0x0), "Contract not found"); // Return return contractAddress; } /// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist) function getContractAddressUnsafe(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Return return contractAddress; } /// @dev Get the name of a network contract by address function getContractName(address _contractAddress) internal view returns (string memory) { // Get the contract name string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress))); // Check it require(bytes(contractName).length > 0, "Contract not found"); // Return return contractName; } /// @dev Get revert error message from a .call method function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /*** Rocket Storage Methods ****************************************/ // Note: Unused helpers have been removed to keep contract sizes down /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); } function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); } /// @dev Storage arithmetic methods function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); } function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../RocketBase.sol"; import "../../interface/token/RocketTokenRPLInterface.sol"; import "../../interface/rewards/RocketRewardsPoolInterface.sol"; import "../../interface/dao/protocol/settings/RocketDAOProtocolSettingsRewardsInterface.sol"; import "../../interface/RocketVaultInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // Holds RPL generated by the network for claiming from stakers (node operators etc) contract RocketRewardsPool is RocketBase, RocketRewardsPoolInterface { // Libs using SafeMath for uint; // Events event RPLTokensClaimed(address indexed claimingContract, address indexed claimingAddress, uint256 amount, uint256 time); // Modifiers /** * @dev Throws if called by any sender that doesn't match a Rocket Pool claim contract */ modifier onlyClaimContract() { require(getClaimingContractExists(getContractName(msg.sender)), "Not a valid rewards claiming contact"); _; } /** * @dev Throws if called by any sender that doesn't match an enabled Rocket Pool claim contract */ modifier onlyEnabledClaimContract() { require(getClaimingContractEnabled(getContractName(msg.sender)), "Not a valid rewards claiming contact or it has been disabled"); _; } // Construct constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) { // Version version = 1; // Set the claim interval start time as the current time setUint(keccak256("rewards.pool.claim.interval.time.start"), block.timestamp); } /** * Get how much RPL the Rewards Pool contract currently has assigned to it as a whole * @return uint256 Returns rpl balance of rocket rewards contract */ function getRPLBalance() override external view returns(uint256) { // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Check per contract return rocketVault.balanceOfToken("rocketRewardsPool", IERC20(getContractAddress("rocketTokenRPL"))); } /** * Get the last set interval start time * @return uint256 Last set start timestamp for a claim interval */ function getClaimIntervalTimeStart() override public view returns(uint256) { return getUint(keccak256("rewards.pool.claim.interval.time.start")); } /** * Compute the current start time before a claim is made, takes into account intervals that may have passed * @return uint256 Computed starting timestamp for next possible claim */ function getClaimIntervalTimeStartComputed() override public view returns(uint256) { // If intervals have passed, a new start timestamp will be used for the next claim, if it's the same interval then return that uint256 claimIntervalTimeStart = getClaimIntervalTimeStart(); uint256 claimIntervalTime = getClaimIntervalTime(); return _getClaimIntervalTimeStartComputed(claimIntervalTimeStart, claimIntervalTime); } function _getClaimIntervalTimeStartComputed(uint256 _claimIntervalTimeStart, uint256 _claimIntervalTime) private view returns (uint256) { uint256 claimIntervalsPassed = _getClaimIntervalsPassed(_claimIntervalTimeStart, _claimIntervalTime); return claimIntervalsPassed == 0 ? _claimIntervalTimeStart : _claimIntervalTimeStart.add(_claimIntervalTime.mul(claimIntervalsPassed)); } /** * Compute intervals since last claim period * @return uint256 Time intervals since last update */ function getClaimIntervalsPassed() override public view returns(uint256) { // Calculate now if inflation has begun return _getClaimIntervalsPassed(getClaimIntervalTimeStart(), getClaimIntervalTime()); } function _getClaimIntervalsPassed(uint256 _claimIntervalTimeStart, uint256 _claimIntervalTime) private view returns (uint256) { return block.timestamp.sub(_claimIntervalTimeStart).div(_claimIntervalTime); } /** * Get how many seconds in a claim interval * @return uint256 Number of seconds in a claim interval */ function getClaimIntervalTime() override public view returns(uint256) { // Get from the DAO settings RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); return daoSettingsRewards.getRewardsClaimIntervalTime(); } /** * Get the last time a claim was made * @return uint256 Last time a claim was made */ function getClaimTimeLastMade() override external view returns(uint256) { return getUint(keccak256("rewards.pool.claim.interval.time.last")); } // Check whether a claiming contract exists function getClaimingContractExists(string memory _contractName) override public view returns (bool) { RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); return (daoSettingsRewards.getRewardsClaimerPercTimeUpdated(_contractName) > 0); } // If the claiming contact has a % allocated to it higher than 0, it can claim function getClaimingContractEnabled(string memory _contractName) override public view returns (bool) { // Load contract RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); // Now verify this contract can claim by having a claim perc > 0 return daoSettingsRewards.getRewardsClaimerPerc(_contractName) > 0 ? true : false; } /** * The current claim amount total for this interval per claiming contract * @return uint256 The current claim amount for this interval for the claiming contract */ function getClaimingContractTotalClaimed(string memory _claimingContract) override external view returns(uint256) { return _getClaimingContractTotalClaimed(_claimingContract, getClaimIntervalTimeStartComputed()); } function _getClaimingContractTotalClaimed(string memory _claimingContract, uint256 _claimIntervalTimeStartComputed) private view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", _claimIntervalTimeStartComputed, _claimingContract))); } /** * Have they claimed already during this interval? * @return bool Returns true if they can claim during this interval */ function getClaimingContractUserHasClaimed(uint256 _claimIntervalStartTime, string memory _claimingContract, address _claimerAddress) override public view returns(bool) { // Check per contract return getBool(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimer.address", _claimIntervalStartTime, _claimingContract, _claimerAddress))); } /** * Get the time this account registered as a claimer at * @return uint256 Returns the time the account was registered at */ function getClaimingContractUserRegisteredTime(string memory _claimingContract, address _claimerAddress) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", _claimingContract, _claimerAddress))); } /** * Get whether this address can currently make a claim * @return bool Returns true if the _claimerAddress can make a claim */ function getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress) override public view returns(bool) { return _getClaimingContractUserCanClaim(_claimingContract, _claimerAddress, getClaimIntervalTime()); } function _getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress, uint256 _claimIntervalTime) private view returns(bool) { // Get the time they registered at uint256 registeredTime = getClaimingContractUserRegisteredTime(_claimingContract, _claimerAddress); // If it's 0 or hasn't passed one interval yet, they can't claim return registeredTime > 0 && registeredTime.add(_claimIntervalTime) <= block.timestamp && getClaimingContractPerc(_claimingContract) > 0 ? true : false; } /** * Get the number of claimers for the current interval per claiming contract * @return uint256 Returns number of claimers for the current interval per claiming contract */ function getClaimingContractUserTotalCurrent(string memory _claimingContract) override external view returns(uint256) { // Return the current interval amount if in that interval, if we are moving to the next one upon next claim, use that return getClaimIntervalsPassed() == 0 ? getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.current", _claimingContract))) : getClaimingContractUserTotalNext(_claimingContract); } /** * Get the number of claimers that will be added/removed on the next interval * @return uint256 Returns the number of claimers that will be added/removed on the next interval */ function getClaimingContractUserTotalNext(string memory _claimingContract) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", _claimingContract))); } /** * Get contract claiming percentage last recorded * @return uint256 Returns the contract claiming percentage last recorded */ function getClaimingContractPercLast(string memory _claimingContract) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", _claimingContract))); } /** * Get the approx amount of rewards available for this claim interval * @return uint256 Rewards amount for current claim interval */ function getClaimIntervalRewardsTotal() override public view returns(uint256) { // Get the RPL contract instance RocketTokenRPLInterface rplContract = RocketTokenRPLInterface(getContractAddress("rocketTokenRPL")); // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Rewards amount uint256 rewardsTotal = 0; // Is this the first claim of this interval? If so, calculate expected inflation RPL + any RPL already in the pool if(getClaimIntervalsPassed() > 0) { // Get the balance of tokens that will be transferred to the vault for this contract when the first claim is made // Also account for any RPL tokens already in the vault for the rewards pool rewardsTotal = rplContract.inflationCalculate().add(rocketVault.balanceOfToken("rocketRewardsPool", IERC20(getContractAddress("rocketTokenRPL")))); }else{ // Claims have already been made, lets retrieve rewards total stored on first claim of this interval rewardsTotal = getUint(keccak256("rewards.pool.claim.interval.total")); } // Done return rewardsTotal; } /** * Get the percentage this contract can claim in this interval * @return uint256 Rewards percentage this contract can claim in this interval */ function getClaimingContractPerc(string memory _claimingContract) override public view returns(uint256) { // Load contract RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); // Get the % amount allocated to this claim contract uint256 claimContractPerc = daoSettingsRewards.getRewardsClaimerPerc(_claimingContract); // Get the time the % was changed at, it will only use this % on the next interval if(daoSettingsRewards.getRewardsClaimerPercTimeUpdated(_claimingContract) > getClaimIntervalTimeStartComputed()) { // Ok so this percentage was set during this interval, we must use the current % assigned to the last claim and the new one will kick in the next interval // If this is 0, the contract hasn't made a claim yet and can only do so on the next interval claimContractPerc = getClaimingContractPercLast(_claimingContract); } // Done return claimContractPerc; } /** * Get the approx amount of rewards available for this claim interval per claiming contract * @return uint256 Rewards amount for current claim interval per claiming contract */ function getClaimingContractAllowance(string memory _claimingContract) override public view returns(uint256) { // Get the % amount this claim contract will get uint256 claimContractPerc = getClaimingContractPerc(_claimingContract); // How much rewards are available for this claim interval? uint256 claimIntervalRewardsTotal = getClaimIntervalRewardsTotal(); // How much this claiming contract is entitled to in perc uint256 contractClaimTotal = 0; // Check now if(claimContractPerc > 0 && claimIntervalRewardsTotal > 0) { // Calculate how much rewards this claimer will receive based on their claiming perc contractClaimTotal = claimContractPerc.mul(claimIntervalRewardsTotal).div(calcBase); } // Done return contractClaimTotal; } // How much this claimer is entitled to claim, checks parameters that claim() will check function getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc) override external view returns (uint256) { if (!getClaimingContractUserCanClaim(_claimingContract, _claimerAddress)) { return 0; } uint256 claimIntervalTimeStartComptued = getClaimIntervalTimeStartComputed(); uint256 claimingContractTotalClaimed = _getClaimingContractTotalClaimed(_claimingContract, claimIntervalTimeStartComptued); return _getClaimAmount(_claimingContract, _claimerAddress, _claimerAmountPerc, claimIntervalTimeStartComptued, claimingContractTotalClaimed); } function _getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc, uint256 _claimIntervalTimeStartComputed, uint256 _claimingContractTotalClaimed) private view returns (uint256) { // Get the total rewards available for this claiming contract uint256 contractClaimTotal = getClaimingContractAllowance(_claimingContract); // How much of the above that this claimer will receive uint256 claimerTotal = 0; // Are we good to proceed? if( contractClaimTotal > 0 && _claimerAmountPerc > 0 && _claimerAmountPerc <= 1 ether && _claimerAddress != address(0x0) && getClaimingContractEnabled(_claimingContract) && !getClaimingContractUserHasClaimed(_claimIntervalTimeStartComputed, _claimingContract, _claimerAddress)) { // Now calculate how much this claimer would receive claimerTotal = _claimerAmountPerc.mul(contractClaimTotal).div(calcBase); // Is it more than currently available + the amount claimed already for this claim interval? claimerTotal = claimerTotal.add(_claimingContractTotalClaimed) <= contractClaimTotal ? claimerTotal : 0; } // Done return claimerTotal; } // An account must be registered to claim from the rewards pool. They must wait one claim interval before they can collect. // Also keeps track of total function registerClaimer(address _claimerAddress, bool _enabled) override external onlyClaimContract { // The name of the claiming contract string memory contractName = getContractName(msg.sender); // Record the time they are registering at uint256 registeredTime = 0; // How many users are to be included in next interval uint256 claimersIntervalTotalUpdate = getClaimingContractUserTotalNext(contractName); // Ok register if(_enabled) { // Make sure they are not already registered require(getClaimingContractUserRegisteredTime(contractName, _claimerAddress) == 0, "Claimer is already registered"); // Update time registeredTime = block.timestamp; // Update the total registered claimers for next interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.add(1)); }else{ // Make sure they are already registered require(getClaimingContractUserRegisteredTime(contractName, _claimerAddress) != 0, "Claimer is not registered"); // Update the total registered claimers for next interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.sub(1)); } // Save the registered time setUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", contractName, _claimerAddress)), registeredTime); } // A claiming contract claiming for a user and the percentage of the rewards they are allowed to receive function claim(address _claimerAddress, address _toAddress, uint256 _claimerAmountPerc) override external onlyEnabledClaimContract { // The name of the claiming contract string memory contractName = getContractName(msg.sender); // Check to see if this registered claimer has waited one interval before collecting uint256 claimIntervalTime = getClaimIntervalTime(); require(_getClaimingContractUserCanClaim(contractName, _claimerAddress, claimIntervalTime), "Registered claimer is not registered to claim or has not waited one claim interval"); // RPL contract address address rplContractAddress = getContractAddress("rocketTokenRPL"); // RPL contract instance RocketTokenRPLInterface rplContract = RocketTokenRPLInterface(rplContractAddress); // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Get the start of the last claim interval as this may have just changed for a new interval beginning uint256 claimIntervalTimeStart = getClaimIntervalTimeStart(); uint256 claimIntervalTimeStartComputed = _getClaimIntervalTimeStartComputed(claimIntervalTimeStart, claimIntervalTime); uint256 claimIntervalsPassed = _getClaimIntervalsPassed(claimIntervalTimeStart, claimIntervalTime); // Is this the first claim of this interval? If so, set the rewards total for this interval if (claimIntervalsPassed > 0) { // Mint any new tokens from the RPL inflation rplContract.inflationMintTokens(); // Get how many tokens are in the reward pool to be available for this claim period setUint(keccak256("rewards.pool.claim.interval.total"), rocketVault.balanceOfToken("rocketRewardsPool", rplContract)); // Set this as the start of the new claim interval setUint(keccak256("rewards.pool.claim.interval.time.start"), claimIntervalTimeStartComputed); // Soon as we mint new tokens, send the DAO's share to it's claiming contract, then attempt to transfer them to the dao if possible uint256 daoClaimContractAllowance = getClaimingContractAllowance("rocketClaimDAO"); // Are we sending any? if (daoClaimContractAllowance > 0) { // Get the DAO claim contract address address daoClaimContractAddress = getContractAddress("rocketClaimDAO"); // Transfers the DAO's tokens to it's claiming contract from the rewards pool rocketVault.transferToken("rocketClaimDAO", rplContract, daoClaimContractAllowance); // Set the current claim percentage this contract is entitled to for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", "rocketClaimDAO")), getClaimingContractPerc("rocketClaimDAO")); // Store the total RPL rewards claim for this claiming contract in this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", claimIntervalTimeStartComputed, "rocketClaimDAO")), _getClaimingContractTotalClaimed("rocketClaimDAO", claimIntervalTimeStartComputed).add(daoClaimContractAllowance)); // Log it emit RPLTokensClaimed(daoClaimContractAddress, daoClaimContractAddress, daoClaimContractAllowance, block.timestamp); } } // Has anyone claimed from this contract so far in this interval? If not then set the interval settings for the contract if (_getClaimingContractTotalClaimed(contractName, claimIntervalTimeStartComputed) == 0) { // Get the amount allocated to this claim contract uint256 claimContractAllowance = getClaimingContractAllowance(contractName); // Make sure this is ok require(claimContractAllowance > 0, "Claiming contract must have an allowance of more than 0"); // Set the current claim percentage this contract is entitled too for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", contractName)), getClaimingContractPerc(contractName)); // Set the current claim allowance amount for this contract for this claim interval (if the claim amount is changed, it will kick in on the next interval) setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.allowance", contractName)), claimContractAllowance); // Set the current amount of claimers for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.current", contractName)), getClaimingContractUserTotalNext(contractName)); } // Check if they have a valid claim amount uint256 claimingContractTotalClaimed = _getClaimingContractTotalClaimed(contractName, claimIntervalTimeStartComputed); uint256 claimAmount = _getClaimAmount(contractName, _claimerAddress, _claimerAmountPerc, claimIntervalTimeStartComputed, claimingContractTotalClaimed); // First initial checks require(claimAmount > 0, "Claimer is not entitled to tokens, they have already claimed in this interval or they are claiming more rewards than available to this claiming contract."); // Send tokens now rocketVault.withdrawToken(_toAddress, rplContract, claimAmount); // Store the claiming record for this interval and claiming contract setBool(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimer.address", claimIntervalTimeStartComputed, contractName, _claimerAddress)), true); // Store the total RPL rewards claim for this claiming contract in this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", claimIntervalTimeStartComputed, contractName)), claimingContractTotalClaimed.add(claimAmount)); // Store the last time a claim was made setUint(keccak256("rewards.pool.claim.interval.time.last"), block.timestamp); // Log it emit RPLTokensClaimed(getContractAddress(contractName), _claimerAddress, claimAmount, block.timestamp); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketStorageInterface { // Deploy status function getDeployedStatus() external view returns (bool); // Guardian function getGuardian() external view returns(address); function setGuardian(address _newAddress) external; function confirmGuardian() external; // Getters function getAddress(bytes32 _key) external view returns (address); function getUint(bytes32 _key) external view returns (uint); function getString(bytes32 _key) external view returns (string memory); function getBytes(bytes32 _key) external view returns (bytes memory); function getBool(bytes32 _key) external view returns (bool); function getInt(bytes32 _key) external view returns (int); function getBytes32(bytes32 _key) external view returns (bytes32); // Setters function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string calldata _value) external; function setBytes(bytes32 _key, bytes calldata _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // Deleters function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; // Arithmetic function addUint(bytes32 _key, uint256 _amount) external; function subUint(bytes32 _key, uint256 _amount) external; // Protected storage function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address); function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address); function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external; function confirmWithdrawalAddress(address _nodeAddress) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; interface RocketVaultInterface { function balanceOf(string memory _networkContractName) external view returns (uint256); function depositEther() external payable; function withdrawEther(uint256 _amount) external; function depositToken(string memory _networkContractName, IERC20 _tokenAddress, uint256 _amount) external; function withdrawToken(address _withdrawalAddress, IERC20 _tokenAddress, uint256 _amount) external; function balanceOfToken(string memory _networkContractName, IERC20 _tokenAddress) external view returns (uint256); function transferToken(string memory _networkContractName, IERC20 _tokenAddress, uint256 _amount) external; function burnToken(ERC20Burnable _tokenAddress, uint256 _amount) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAOProtocolSettingsRewardsInterface { function setSettingRewardsClaimer(string memory _contractName, uint256 _perc) external; function getRewardsClaimerPerc(string memory _contractName) external view returns (uint256); function getRewardsClaimerPercTimeUpdated(string memory _contractName) external view returns (uint256); function getRewardsClaimersPercTotal() external view returns (uint256); function getRewardsClaimIntervalTime() external view returns (uint256); } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketRewardsPoolInterface { function getRPLBalance() external view returns(uint256); function getClaimIntervalTimeStart() external view returns(uint256); function getClaimIntervalTimeStartComputed() external view returns(uint256); function getClaimIntervalsPassed() external view returns(uint256); function getClaimIntervalTime() external view returns(uint256); function getClaimTimeLastMade() external view returns(uint256); function getClaimIntervalRewardsTotal() external view returns(uint256); function getClaimingContractTotalClaimed(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserTotalNext(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserTotalCurrent(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserHasClaimed(uint256 _claimIntervalStartTime, string memory _claimingContract, address _claimerAddress) external view returns(bool); function getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress) external view returns(bool); function getClaimingContractUserRegisteredTime(string memory _claimingContract, address _claimerAddress) external view returns(uint256); function getClaimingContractAllowance(string memory _claimingContract) external view returns(uint256); function getClaimingContractPerc(string memory _claimingContract) external view returns(uint256); function getClaimingContractPercLast(string memory _claimingContract) external view returns(uint256); function getClaimingContractExists(string memory _contractName) external view returns (bool); function getClaimingContractEnabled(string memory _contractName) external view returns (bool); function getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc) external view returns (uint256); function registerClaimer(address _claimerAddress, bool _enabled) external; function claim(address _claimerAddress, address _toAddress, uint256 _claimerAmount) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface RocketTokenRPLInterface is IERC20 { function getInflationCalcTime() external view returns(uint256); function getInflationIntervalTime() external view returns(uint256); function getInflationIntervalRate() external view returns(uint256); function getInflationIntervalsPassed() external view returns(uint256); function getInflationIntervalStartTime() external view returns(uint256); function getInflationRewardsContractAddress() external view returns(address); function inflationCalculate() external view returns (uint256); function inflationMintTokens() external returns (uint256); function swapTokens(uint256 _amount) external; }
Get the percentage this contract can claim in this interval return uint256 Rewards percentage this contract can claim in this interval/ Load contract Get the % amount allocated to this claim contract Get the time the % was changed at, it will only use this % on the next interval Ok so this percentage was set during this interval, we must use the current % assigned to the last claim and the new one will kick in the next interval If this is 0, the contract hasn't made a claim yet and can only do so on the next interval
function getClaimingContractPerc(string memory _claimingContract) override public view returns(uint256) { RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); uint256 claimContractPerc = daoSettingsRewards.getRewardsClaimerPerc(_claimingContract); if(daoSettingsRewards.getRewardsClaimerPercTimeUpdated(_claimingContract) > getClaimIntervalTimeStartComputed()) { claimContractPerc = getClaimingContractPercLast(_claimingContract); } }
12,064,638
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; interface IAstraMetadata { function tokenURI(uint256 tokenId, uint256 meta, bool isLocking, string memory genesisImageUrl) external view returns (string memory); function generate(uint256 seed) external view returns (uint256, uint256); } contract AstraArmy is ERC721, Ownable { using SafeMath for uint256; uint256 constant MAX_ALPHA_SUPPLY = 8869; // Maximum limit of tokens for sale by ETH uint256 constant MAX_TOTAL_SUPPLY = 696969; // Maximum limit of tokens in the collection uint256 constant MAX_GIVEAWAY_REVERSE = 69; // Maximum limit of tokens for giving away purposes uint256 constant BATCH_PRESALE_LIMIT = 2; // Maximum limit of tokens per pre-sale transaction uint256 constant BATCH_BORN_LIMIT = 3; // Maximum limit of tokens per mint by token transaction uint256 constant PRESALE_PRICE = 0.050 ether; // Price for pre-sale uint256 constant PUBLICSALE_PRICE = 0.069 ether; // Price for minting uint256 constant CLAIM_TIMEOUT = 14*24*3600; // Claim expiration time after reserve uint256 constant STATS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000000000; // Mask for separate props and stats uint256 public MaxSalePerAddress = 10; // Maximum limit of tokens per address for minting uint256 public LockingTime = 2*24*3600; // Lock metadata after mint in seconds uint256 public TotalSupply; // Current total supply uint256 public GiveAwaySupply; // Total supply for giving away purposes uint256 public ResevedSupply; // Current total supply for sale by ETH bytes32 public PresaleMerkleRoot; // Merkle root hash to verify pre-sale address address public PaymentAddress; // The address where payment will be received address public MetadataAddress; // The address of metadata's contract address public BattleAddress; // The address of game's contract bool public PreSaleActived; // Pre-sale is activated bool public PublicSaleActived; // Public sale is activated bool public BornActived; // Mint by token is activated mapping (uint256 => uint256) MintTimestampMapping; // Mapping minting time mapping (uint256 => uint256) MetadataMapping; // Mapping token's metadata mapping (uint256 => bool) MetadataExisting; // Mapping metadata's existence mapping (address => bool) PresaleClaimedMapping; // Mapping pre-sale claimed rewards mapping (address => uint256) ReserveSaleMapping; // Mapping reservations for public sale mapping (address => uint256) ReserveTimestampMapping;// Mapping minting time mapping (address => uint256) ClaimedSaleMapping; // Mapping claims for public sale // Initialization function will initialize the initial values constructor(address metadataAddress, address paymentAddress) ERC721("Astra Chipmunks Army", "ACA") { PaymentAddress = paymentAddress; MetadataAddress = metadataAddress; // Generate first tokens for Alvxns & teams saveMetadata(1, 0x00000a000e001c001b0011001700000000000000000000000000000000000000); super._safeMint(paymentAddress, 1); TotalSupply++; } // Randomize metadata util it's unique function generateMetadata(uint256 tokenId, uint256 seed) internal returns (uint256) { (uint256 random, uint256 meta) = IAstraMetadata(MetadataAddress).generate(seed); if(MetadataExisting[meta]) return generateMetadata(tokenId, random); else return meta; } // Get the tokenURI onchain function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { return IAstraMetadata(MetadataAddress).tokenURI(tokenId, MetadataMapping[tokenId], MintTimestampMapping[tokenId] + LockingTime > block.timestamp, ""); } // The function that reassigns a global variable named MetadataAddress (owner only) function setMetadataAddress(address metadataAddress) external onlyOwner { MetadataAddress = metadataAddress; } // The function that reassigns a global variable named BattleAddress (owner only) function setBattleAddress(address battleAddress) external onlyOwner { BattleAddress = battleAddress; } // The function that reassigns a global variable named PaymentAddress (owner only) function setPaymentAddress(address paymentAddress) external onlyOwner { PaymentAddress = paymentAddress; } // The function that reassigns a global variable named PresaleMerkleRoot (owner only) function setPresaleMerkleRoot(bytes32 presaleMerkleRoot) external onlyOwner { PresaleMerkleRoot = presaleMerkleRoot; } // The function that reassigns a global variable named PreSaleActived (owner only) function setPresaleActived(bool preSaleActived) external onlyOwner { PreSaleActived = preSaleActived; } // The function that reassigns a global variable named BornActived (owner only) function setBornActived(bool bornActived) external onlyOwner { BornActived = bornActived; } // The function that reassigns a global variable named PublicSaleActived (owner only) function setPublicSaleActived(bool publicSaleActived) external onlyOwner { PublicSaleActived = publicSaleActived; } // The function that reassigns a global variable named LockingTime (owner only) function setLockingTime(uint256 lockingTime) external onlyOwner { LockingTime = lockingTime; } // The function that reassigns a global variable named MaxSalePerAddress (owner only) function setMaxSalePerAddress(uint256 maxSalePerAddress) external onlyOwner { MaxSalePerAddress = maxSalePerAddress; } // Pre-sale whitelist check function function checkPresaleProof(address buyer, bool hasFreeMint, bytes32[] memory merkleProof) public view returns (bool) { // Calculate the hash of leaf bytes32 leafHash = keccak256(abi.encode(buyer, hasFreeMint)); // Verify leaf using openzeppelin library return MerkleProof.verify(merkleProof, PresaleMerkleRoot, leafHash); } // Give away minting function (owner only) function mintGiveAway(uint256 numberOfTokens, address toAddress) external onlyOwner { // Calculate current index for minting uint256 i = TotalSupply + 1; TotalSupply += numberOfTokens; GiveAwaySupply += numberOfTokens; // Exceeded the maximum total give away supply require(0 < numberOfTokens && GiveAwaySupply <= MAX_GIVEAWAY_REVERSE && TotalSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!'); for (;i <= TotalSupply; i++) { // To the sun _safeMint(toAddress, i); } } // Presale minting function function mintPreSale(uint256 numberOfTokens, bool hasFreeMint, bytes32[] memory merkleProof) external payable { // Calculate current index for minting uint256 i = TotalSupply + 1; TotalSupply += numberOfTokens.add(hasFreeMint ? 1 : 0); // The sender must be a wallet require(msg.sender == tx.origin, 'Not a wallet!'); // Pre-sale is not open yet require(PreSaleActived, 'Not open yet!'); // Exceeded the maximum total supply require(TotalSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!'); // Exceeded the limit for each pre-sale require(0 < numberOfTokens && numberOfTokens <= BATCH_PRESALE_LIMIT, 'Exceed limitation!'); // You are not on the pre-sale whitelist require(this.checkPresaleProof(msg.sender, hasFreeMint, merkleProof), 'Not on the whitelist!'); // Your promotion has been used require(!PresaleClaimedMapping[msg.sender], 'Promotion is over!'); // Your ETH amount is insufficient require(PRESALE_PRICE.mul(numberOfTokens) <= msg.value, 'Insufficient funds!'); // Mark the address that has used the promotion PresaleClaimedMapping[msg.sender] = true; // Make the payment to diffrence wallet payable(PaymentAddress).transfer(msg.value); for (; i <= TotalSupply; i++) { // To the moon _safeMint(msg.sender, i); } } // Getting the reserve status function reserveStatus(address addressOf) external view returns (uint256, uint256) { uint256 claimable = ReserveSaleMapping[addressOf] - ClaimedSaleMapping[addressOf]; uint256 reservable = MaxSalePerAddress > ReserveSaleMapping[addressOf] ? MaxSalePerAddress - ReserveSaleMapping[addressOf] : 0; return (claimable, reservable); } // Public sale by ETH minting function function reserve(uint256 numberOfTokens) external payable { // Register for a ticket ReserveSaleMapping[msg.sender] = ReserveSaleMapping[msg.sender].add(numberOfTokens); ResevedSupply = ResevedSupply.add(numberOfTokens); ReserveTimestampMapping[msg.sender] = block.timestamp; // The sender must be a wallet require(msg.sender == tx.origin, 'Not a wallet!'); // Public sale is not open yet require(PublicSaleActived, 'Not open yet!'); // Exceeded the maximum total supply require(TotalSupply + ResevedSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!'); // Your ETH amount is insufficient require(0 < numberOfTokens && PUBLICSALE_PRICE.mul(numberOfTokens) <= msg.value, 'Insufficient funds!'); // Exceeded the limit per address require(numberOfTokens <= MaxSalePerAddress && ReserveSaleMapping[msg.sender] <= MaxSalePerAddress, 'Exceed address limitation!'); // Make the payment to diffrence wallet payable(PaymentAddress).transfer(msg.value); } // Public sale by ETH minting function function claim() external payable { // The sender must be a wallet require(msg.sender == tx.origin, 'Not a wallet!'); // Reservetions must come first require(ReserveSaleMapping[msg.sender] > ClaimedSaleMapping[msg.sender], 'Already claimed!'); // Expired claims require(ReserveTimestampMapping[msg.sender] + CLAIM_TIMEOUT > block.timestamp, 'Expired claims!'); // Calculate current index for minting uint256 i = TotalSupply + 1; uint256 numberOfTokens = ReserveSaleMapping[msg.sender] - ClaimedSaleMapping[msg.sender]; ResevedSupply -= numberOfTokens; TotalSupply += numberOfTokens; // Reassign used tickets ClaimedSaleMapping[msg.sender] = ReserveSaleMapping[msg.sender]; delete(ReserveTimestampMapping[msg.sender]); for (; i <= TotalSupply; i++) { // To the moon _safeMint(msg.sender, i); } } // Public sale by token minting function function born(address toAddress, uint256 numberOfTokens) external { // Calculate current index for minting uint256 i = TotalSupply + 1; TotalSupply = TotalSupply.add(numberOfTokens); // Born is not open yet require(BornActived, 'Not open yet!'); // Exceeded the limit for each mint egg require(0 < numberOfTokens && numberOfTokens <= BATCH_BORN_LIMIT, 'Exceed batch limitation!'); // Exceeded the maximum total supply require(TotalSupply <= MAX_TOTAL_SUPPLY, 'Exceed total supply!'); // The sender must be game contract require(msg.sender == BattleAddress, 'Not authorized!'); for (; i <= TotalSupply; i++) { // To the moon _safeMint(toAddress, i); } } // Setting the stats of the token function setStats(uint256 tokenId, uint256 meta) external { // The sender must be game contract require(msg.sender == BattleAddress, 'Not authorized!'); // Put on a mask to make sure nothing can change the art, just stats MetadataMapping[tokenId] = (MetadataMapping[tokenId] & ~STATS_MASK) | (meta & STATS_MASK); } // Save the metadata information function saveMetadata(uint256 tokenId, uint256 meta) internal { MintTimestampMapping[tokenId] = block.timestamp; MetadataMapping[tokenId] = meta; MetadataExisting[meta] = true; } // Customize safeMint function function _safeMint(address to, uint256 tokenId) internal virtual override { // Generate and save metadata saveMetadata(tokenId, generateMetadata(tokenId, tokenId)); // Call the function super super._safeMint(to, tokenId); } // Customize beforeTokenTransfer function function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { // Call the function super super._beforeTokenTransfer(from, to, tokenId); // Lock the tranfer of LockingTime seconds, except for the alpha generation require(tokenId <= MAX_ALPHA_SUPPLY || MintTimestampMapping[tokenId] + LockingTime < block.timestamp, 'Not transferable!'); } // Customize totalSupply function function totalSupply() external virtual returns (uint256) { return TotalSupply; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @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, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @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 (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` 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 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT 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() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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 ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT 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 pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @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); } } // SPDX-License-Identifier: MIT 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 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); }
Public sale by ETH minting function Register for a ticket The sender must be a wallet Public sale is not open yet Exceeded the maximum total supply Your ETH amount is insufficient Exceeded the limit per address Make the payment to diffrence wallet
function reserve(uint256 numberOfTokens) external payable { ReserveSaleMapping[msg.sender] = ReserveSaleMapping[msg.sender].add(numberOfTokens); ResevedSupply = ResevedSupply.add(numberOfTokens); ReserveTimestampMapping[msg.sender] = block.timestamp; require(msg.sender == tx.origin, 'Not a wallet!'); require(PublicSaleActived, 'Not open yet!'); require(TotalSupply + ResevedSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!'); require(0 < numberOfTokens && PUBLICSALE_PRICE.mul(numberOfTokens) <= msg.value, 'Insufficient funds!'); require(numberOfTokens <= MaxSalePerAddress && ReserveSaleMapping[msg.sender] <= MaxSalePerAddress, 'Exceed address limitation!'); payable(PaymentAddress).transfer(msg.value); }
10,306,675
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @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 a proxied contract can't have 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. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.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 pragma solidity ^0.8.0; import "../IERC20Upgradeable.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' // solhint-disable-next-line max-line-length 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)); } } /** * @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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./ModuleMapConsumer.sol"; import "../interfaces/IKernel.sol"; abstract contract Controlled is Initializable, ModuleMapConsumer { // controller address => is a controller mapping(address => bool) internal _controllers; address[] public controllers; function __Controlled_init(address[] memory controllers_, address moduleMap_) public initializer { for (uint256 i; i < controllers_.length; i++) { _controllers[controllers_[i]] = true; } controllers = controllers_; __ModuleMapConsumer_init(moduleMap_); } function addController(address controller) external onlyOwner { _controllers[controller] = true; bool added; for (uint256 i; i < controllers.length; i++) { if (controller == controllers[i]) { added = true; } } if (!added) { controllers.push(controller); } } modifier onlyOwner() { require( IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isOwner(msg.sender), "Controlled::onlyOwner: Caller is not owner" ); _; } modifier onlyManager() { require( IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isManager(msg.sender), "Controlled::onlyManager: Caller is not manager" ); _; } modifier onlyController() { require( _controllers[msg.sender], "Controlled::onlyController: Caller is not controller" ); _; } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IModuleMap.sol"; abstract contract ModuleMapConsumer is Initializable { IModuleMap public moduleMap; function __ModuleMapConsumer_init(address moduleMap_) internal initializer { moduleMap = IModuleMap(moduleMap_); } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../interfaces/IIntegrationMap.sol"; import "../interfaces/IIntegration.sol"; import "../interfaces/IEtherRewards.sol"; import "../interfaces/IYieldManager.sol"; import "../interfaces/IUniswapTrader.sol"; import "../interfaces/ISushiSwapTrader.sol"; import "../interfaces/IUserPositions.sol"; import "../interfaces/IWeth9.sol"; import "../interfaces/IStrategyMap.sol"; import "./Controlled.sol"; import "./ModuleMapConsumer.sol"; /// @title Yield Manager /// @notice Manages yield deployments, harvesting, processing, and distribution contract YieldManager is Initializable, ModuleMapConsumer, Controlled, IYieldManager { using SafeERC20Upgradeable for IERC20MetadataUpgradeable; uint256 private gasAccountTargetEthBalance; uint32 private biosBuyBackEthWeight; uint32 private treasuryEthWeight; uint32 private protocolFeeEthWeight; uint32 private rewardsEthWeight; uint256 private lastEthRewardsAmount; address payable private gasAccount; address payable private treasuryAccount; mapping(address => uint256) private processedWethByToken; receive() external payable {} /// @param controllers_ The addresses of the controlling contracts /// @param moduleMap_ Address of the Module Map /// @param gasAccountTargetEthBalance_ The target ETH balance of the gas account /// @param biosBuyBackEthWeight_ The relative weight of ETH to send to BIOS buy back /// @param treasuryEthWeight_ The relative weight of ETH to send to the treasury /// @param protocolFeeEthWeight_ The relative weight of ETH to send to protocol fee accrual /// @param rewardsEthWeight_ The relative weight of ETH to send to user rewards /// @param gasAccount_ The address of the account to send ETH to gas for executing bulk system functions /// @param treasuryAccount_ The address of the system treasury account function initialize( address[] memory controllers_, address moduleMap_, uint256 gasAccountTargetEthBalance_, uint32 biosBuyBackEthWeight_, uint32 treasuryEthWeight_, uint32 protocolFeeEthWeight_, uint32 rewardsEthWeight_, address payable gasAccount_, address payable treasuryAccount_ ) public initializer { __Controlled_init(controllers_, moduleMap_); __ModuleMapConsumer_init(moduleMap_); gasAccountTargetEthBalance = gasAccountTargetEthBalance_; biosBuyBackEthWeight = biosBuyBackEthWeight_; treasuryEthWeight = treasuryEthWeight_; protocolFeeEthWeight = protocolFeeEthWeight_; rewardsEthWeight = rewardsEthWeight_; gasAccount = gasAccount_; treasuryAccount = treasuryAccount_; } /// @param gasAccountTargetEthBalance_ The target ETH balance of the gas account function updateGasAccountTargetEthBalance(uint256 gasAccountTargetEthBalance_) external override onlyController { gasAccountTargetEthBalance = gasAccountTargetEthBalance_; } /// @param biosBuyBackEthWeight_ The relative weight of ETH to send to BIOS buy back /// @param treasuryEthWeight_ The relative weight of ETH to send to the treasury /// @param protocolFeeEthWeight_ The relative weight of ETH to send to protocol fee accrual /// @param rewardsEthWeight_ The relative weight of ETH to send to user rewards function updateEthDistributionWeights( uint32 biosBuyBackEthWeight_, uint32 treasuryEthWeight_, uint32 protocolFeeEthWeight_, uint32 rewardsEthWeight_ ) external override onlyController { biosBuyBackEthWeight = biosBuyBackEthWeight_; treasuryEthWeight = treasuryEthWeight_; protocolFeeEthWeight = protocolFeeEthWeight_; rewardsEthWeight = rewardsEthWeight_; } /// @param gasAccount_ The address of the account to send ETH to gas for executing bulk system functions function updateGasAccount(address payable gasAccount_) external override onlyController { gasAccount = gasAccount_; } /// @param treasuryAccount_ The address of the system treasury account function updateTreasuryAccount(address payable treasuryAccount_) external override onlyController { treasuryAccount = treasuryAccount_; } /// @notice Withdraws and then re-deploys tokens to integrations according to configured weights function rebalance() external override onlyController { _deploy(); } /// @notice Deploys all tokens to all integrations according to configured weights function deploy() external override onlyController { _deploy(); } function _deploy() internal { bool shouldRedeploy = _rebalance(); if (shouldRedeploy) { _rebalance(); } } function _rebalance() internal returns (bool redeploy) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); IStrategyMap strategyMap = IStrategyMap( moduleMap.getModuleAddress(Modules.StrategyMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); uint256 integrationCount = integrationMap.getIntegrationAddressesLength(); uint256 denominator = integrationMap.getReserveRatioDenominator(); for (uint256 i = 0; i < integrationCount; i++) { address integration = integrationMap.getIntegrationAddress(i); for (uint256 j = 0; j < tokenCount; j++) { address token = integrationMap.getTokenAddress(j); uint256 numerator = integrationMap.getTokenReserveRatioNumerator(token); uint256 grossAmountInvested = strategyMap.getExpectedBalance( integration, token ); uint256 desiredBalance = grossAmountInvested - _calculateReserveAmount(grossAmountInvested, numerator, denominator); uint256 actualBalance = IIntegration(integration).getBalance(token); if (desiredBalance > actualBalance) { // Underfunded, top up redeploy = true; uint256 shortage = desiredBalance - actualBalance; if ( IERC20MetadataUpgradeable(token).balanceOf( moduleMap.getModuleAddress(Modules.Kernel) ) >= shortage ) { uint256 balanceBefore = IERC20MetadataUpgradeable(token).balanceOf( integration ); IERC20MetadataUpgradeable(token).safeTransferFrom( moduleMap.getModuleAddress(Modules.Kernel), integration, shortage ); uint256 balanceAfter = IERC20MetadataUpgradeable(token).balanceOf( integration ); IIntegration(integration).deposit( token, balanceAfter - balanceBefore ); } } else if (actualBalance > desiredBalance) { // Overfunded, give it a haircut redeploy = true; IIntegration(integration).withdraw( token, actualBalance - desiredBalance ); } } IIntegration(integration).deploy(); } } function _calculateReserveAmount( uint256 amount, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return (amount * numerator) / denominator; } /// @notice Harvests available yield from all tokens and integrations function harvestYield() public override onlyController { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); uint256 integrationCount = integrationMap.getIntegrationAddressesLength(); for ( uint256 integrationId; integrationId < integrationCount; integrationId++ ) { IIntegration(integrationMap.getIntegrationAddress(integrationId)) .harvestYield(); } for (uint256 tokenId; tokenId < tokenCount; tokenId++) { IERC20MetadataUpgradeable token = IERC20MetadataUpgradeable( integrationMap.getTokenAddress(tokenId) ); uint256 tokenDesiredReserve = getDesiredReserveTokenBalance( address(token) ); uint256 tokenActualReserve = getReserveTokenBalance(address(token)); uint256 harvestedTokenAmount = token.balanceOf(address(this)); // Check if reserves need to be replenished if (tokenDesiredReserve > tokenActualReserve) { // Need to replenish reserves if (tokenDesiredReserve - tokenActualReserve <= harvestedTokenAmount) { // Need to send portion of harvested token to Kernel to replenish reserves token.safeTransfer( moduleMap.getModuleAddress(Modules.Kernel), tokenDesiredReserve - tokenActualReserve ); } else { // Need to send all of harvested token to Kernel to partially replenish reserves token.safeTransfer( moduleMap.getModuleAddress(Modules.Kernel), token.balanceOf(address(this)) ); } } } } /// @notice Swaps all harvested yield tokens for WETH function processYield() external override onlyController { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); IERC20MetadataUpgradeable weth = IERC20MetadataUpgradeable( integrationMap.getWethTokenAddress() ); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { IERC20MetadataUpgradeable token = IERC20MetadataUpgradeable( integrationMap.getTokenAddress(tokenId) ); if (token.balanceOf(address(this)) > 0) { uint256 wethReceived; if (address(token) != address(weth)) { // If token is not WETH, need to swap it for WETH uint256 wethBalanceBefore = weth.balanceOf(address(this)); // Swap token harvested yield for WETH. If trade succeeds, update accounting. Otherwise, do not update accounting token.safeTransfer( moduleMap.getModuleAddress(Modules.UniswapTrader), token.balanceOf(address(this)) ); IUniswapTrader(moduleMap.getModuleAddress(Modules.UniswapTrader)) .swapExactInput( address(token), address(weth), address(this), token.balanceOf(moduleMap.getModuleAddress(Modules.UniswapTrader)) ); wethReceived = weth.balanceOf(address(this)) - wethBalanceBefore; } else { // If token is WETH, no swap is needed wethReceived = weth.balanceOf(address(this)) - getProcessedWethByTokenSum(); } // Update accounting processedWethByToken[address(token)] += wethReceived; } } } /// @notice Distributes ETH to the gas account, BIOS buy back, treasury, protocol fee accrual, and user rewards function distributeEth() external override onlyController { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); address wethAddress = IIntegrationMap(integrationMap).getWethTokenAddress(); // First fill up gas wallet with ETH ethToGasAccount(); uint256 wethToDistribute = IERC20MetadataUpgradeable(wethAddress).balanceOf( address(this) ); if (wethToDistribute > 0) { uint256 biosBuyBackWethAmount = (wethToDistribute * biosBuyBackEthWeight) / getEthWeightSum(); uint256 treasuryWethAmount = (wethToDistribute * treasuryEthWeight) / getEthWeightSum(); uint256 protocolFeeWethAmount = (wethToDistribute * protocolFeeEthWeight) / getEthWeightSum(); uint256 rewardsWethAmount = wethToDistribute - biosBuyBackWethAmount - treasuryWethAmount - protocolFeeWethAmount; // Send WETH to SushiSwap trader for BIOS buy back IERC20MetadataUpgradeable(wethAddress).safeTransfer( moduleMap.getModuleAddress(Modules.SushiSwapTrader), biosBuyBackWethAmount ); // Swap WETH for ETH and transfer to the treasury account IWeth9(wethAddress).withdraw(treasuryWethAmount); payable(treasuryAccount).transfer(treasuryWethAmount); // Send ETH to protocol fee accrual rewards (BIOS stakers) ethToProtocolFeeAccrual(protocolFeeWethAmount); // Send ETH to token rewards ethToRewards(rewardsWethAmount); } } /// @notice Distributes WETH to gas wallet function ethToGasAccount() private { address wethAddress = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ).getWethTokenAddress(); uint256 wethBalance = IERC20MetadataUpgradeable(wethAddress).balanceOf( address(this) ); if (wethBalance > 0) { uint256 gasAccountActualEthBalance = gasAccount.balance; if (gasAccountActualEthBalance < gasAccountTargetEthBalance) { // Need to send ETH to gas account uint256 ethAmountToGasAccount; if ( wethBalance < gasAccountTargetEthBalance - gasAccountActualEthBalance ) { // Send all of WETH to gas wallet ethAmountToGasAccount = wethBalance; IWeth9(wethAddress).withdraw(ethAmountToGasAccount); gasAccount.transfer(ethAmountToGasAccount); } else { // Send portion of WETH to gas wallet ethAmountToGasAccount = gasAccountTargetEthBalance - gasAccountActualEthBalance; IWeth9(wethAddress).withdraw(ethAmountToGasAccount); gasAccount.transfer(ethAmountToGasAccount); } } } } /// @notice Uses any WETH held in the SushiSwap trader to buy back BIOS which is sent to the Kernel function biosBuyBack() external override onlyController { if ( IERC20MetadataUpgradeable( IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getWethTokenAddress() ).balanceOf(moduleMap.getModuleAddress(Modules.SushiSwapTrader)) > 0 ) { // Use all ETH sent to the SushiSwap trader to buy BIOS ISushiSwapTrader(moduleMap.getModuleAddress(Modules.SushiSwapTrader)) .biosBuyBack(); // Use all BIOS transferred to the Kernel to increase bios rewards IUserPositions(moduleMap.getModuleAddress(Modules.UserPositions)) .increaseBiosRewards(); } } /// @notice Distributes ETH to Rewards per token /// @param ethRewardsAmount The amount of ETH rewards to distribute function ethToRewards(uint256 ethRewardsAmount) private { uint256 processedWethByTokenSum = getProcessedWethSum(); require( processedWethByTokenSum > 0, "YieldManager::ethToRewards: No processed WETH to distribute" ); IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); address wethAddress = integrationMap.getWethTokenAddress(); uint256 tokenCount = integrationMap.getTokenAddressesLength(); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { address tokenAddress = integrationMap.getTokenAddress(tokenId); if (processedWethByToken[tokenAddress] > 0) { IEtherRewards(moduleMap.getModuleAddress(Modules.EtherRewards)) .increaseEthRewards( tokenAddress, (ethRewardsAmount * processedWethByToken[tokenAddress]) / processedWethByTokenSum ); processedWethByToken[tokenAddress] = 0; } } lastEthRewardsAmount = ethRewardsAmount; IWeth9(wethAddress).withdraw(ethRewardsAmount); payable(moduleMap.getModuleAddress(Modules.Kernel)).transfer( ethRewardsAmount ); } /// @notice Distributes ETH to protocol fee accrual (BIOS staker rewards) /// @param protocolFeeEthRewardsAmount Amount of ETH to distribute to protocol fee accrual function ethToProtocolFeeAccrual(uint256 protocolFeeEthRewardsAmount) private { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); address biosAddress = integrationMap.getBiosTokenAddress(); address wethAddress = integrationMap.getWethTokenAddress(); if ( IStrategyMap(moduleMap.getModuleAddress(Modules.StrategyMap)) .getTokenTotalBalance(biosAddress) > 0 ) { // BIOS has been deposited, increase Ether rewards for BIOS depositors IEtherRewards(moduleMap.getModuleAddress(Modules.EtherRewards)) .increaseEthRewards(biosAddress, protocolFeeEthRewardsAmount); IWeth9(wethAddress).withdraw(protocolFeeEthRewardsAmount); payable(moduleMap.getModuleAddress(Modules.Kernel)).transfer( protocolFeeEthRewardsAmount ); } else { // No BIOS has been deposited, send WETH back to Kernel as reserves IERC20MetadataUpgradeable(wethAddress).transfer( moduleMap.getModuleAddress(Modules.Kernel), protocolFeeEthRewardsAmount ); } } /// @param tokenAddress The address of the token ERC20 contract /// @return harvestedTokenBalance The amount of the token yield harvested held in the Kernel function getHarvestedTokenBalance(address tokenAddress) external view override returns (uint256 harvestedTokenBalance) { if ( tokenAddress == IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getWethTokenAddress() ) { harvestedTokenBalance = IERC20MetadataUpgradeable(tokenAddress).balanceOf(address(this)) - getProcessedWethSum(); } else { harvestedTokenBalance = IERC20MetadataUpgradeable(tokenAddress).balanceOf( address(this) ); } } /// @param tokenAddress The address of the token ERC20 contract /// @return The amount of the token held in the Kernel as reserves function getReserveTokenBalance(address tokenAddress) public view override returns (uint256) { require( IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getIsTokenAdded(tokenAddress), "YieldManager::getReserveTokenBalance: Token not added" ); return IERC20MetadataUpgradeable(tokenAddress).balanceOf( moduleMap.getModuleAddress(Modules.Kernel) ); } /// @param tokenAddress The address of the token ERC20 contract /// @return The desired amount of the token to hold in the Kernel as reserves function getDesiredReserveTokenBalance(address tokenAddress) public view override returns (uint256) { require( IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getIsTokenAdded(tokenAddress), "YieldManager::getDesiredReserveTokenBalance: Token not added" ); uint256 tokenReserveRatioNumerator = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ).getTokenReserveRatioNumerator(tokenAddress); uint256 tokenTotalBalance = IStrategyMap( moduleMap.getModuleAddress(Modules.StrategyMap) ).getTokenTotalBalance(tokenAddress); return (tokenTotalBalance * tokenReserveRatioNumerator) / IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getReserveRatioDenominator(); } /// @return ethWeightSum The sum of ETH distribution weights function getEthWeightSum() public view override returns (uint32 ethWeightSum) { ethWeightSum = biosBuyBackEthWeight + treasuryEthWeight + protocolFeeEthWeight + rewardsEthWeight; } /// @return processedWethSum The sum of yields processed into WETH function getProcessedWethSum() public view override returns (uint256 processedWethSum) { uint256 tokenCount = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ).getTokenAddressesLength(); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { address tokenAddress = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ).getTokenAddress(tokenId); processedWethSum += processedWethByToken[tokenAddress]; } } /// @param tokenAddress The address of the token ERC20 contract /// @return The amount of WETH received from token yield processing function getProcessedWethByToken(address tokenAddress) public view override returns (uint256) { return processedWethByToken[tokenAddress]; } /// @return processedWethByTokenSum The sum of processed WETH function getProcessedWethByTokenSum() public view override returns (uint256 processedWethByTokenSum) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { processedWethByTokenSum += processedWethByToken[ integrationMap.getTokenAddress(tokenId) ]; } } /// @param tokenAddress The address of the token ERC20 contract /// @return tokenTotalIntegrationBalance The total amount of the token that can be withdrawn from integrations function getTokenTotalIntegrationBalance(address tokenAddress) public view override returns (uint256 tokenTotalIntegrationBalance) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 integrationCount = integrationMap.getIntegrationAddressesLength(); for ( uint256 integrationId; integrationId < integrationCount; integrationId++ ) { tokenTotalIntegrationBalance += IIntegration( integrationMap.getIntegrationAddress(integrationId) ).getBalance(tokenAddress); } } /// @return The address of the gas account function getGasAccount() public view override returns (address) { return gasAccount; } /// @return The address of the treasury account function getTreasuryAccount() public view override returns (address) { return treasuryAccount; } /// @return The last amount of ETH distributed to rewards function getLastEthRewardsAmount() public view override returns (uint256) { return lastEthRewardsAmount; } /// @return The target ETH balance of the gas account function getGasAccountTargetEthBalance() public view override returns (uint256) { return gasAccountTargetEthBalance; } /// @return The BIOS buyback ETH weight /// @return The Treasury ETH weight /// @return The Protocol fee ETH weight /// @return The rewards ETH weight function getEthDistributionWeights() public view override returns ( uint32, uint32, uint32, uint32 ) { return ( biosBuyBackEthWeight, treasuryEthWeight, protocolFeeEthWeight, rewardsEthWeight ); } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IEtherRewards { /// @param token The address of the token ERC20 contract /// @param user The address of the user function updateUserRewards(address token, address user) external; /// @param token The address of the token ERC20 contract /// @param ethRewardsAmount The amount of Ether rewards to add function increaseEthRewards(address token, uint256 ethRewardsAmount) external; /// @param user The address of the user /// @return ethRewards The amount of Ether claimed function claimEthRewards(address user) external returns (uint256 ethRewards); /// @param token The address of the token ERC20 contract /// @param user The address of the user /// @return ethRewards The amount of Ether claimed function getUserTokenEthRewards(address token, address user) external view returns (uint256 ethRewards); /// @param user The address of the user /// @return ethRewards The amount of Ether claimed function getUserEthRewards(address user) external view returns (uint256 ethRewards); /// @param token The address of the token ERC20 contract /// @return The amount of Ether rewards for the specified token function getTokenEthRewards(address token) external view returns (uint256); /// @return The total value of ETH claimed by users function getTotalClaimedEthRewards() external view returns (uint256); /// @return The total value of ETH claimed by a user function getTotalUserClaimedEthRewards(address user) external view returns (uint256); /// @return The total amount of Ether rewards function getEthRewards() external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IIntegration { /// @param tokenAddress The address of the deposited token /// @param amount The amount of the token being deposited function deposit(address tokenAddress, uint256 amount) external; /// @param tokenAddress The address of the withdrawal token /// @param amount The amount of the token to withdraw function withdraw(address tokenAddress, uint256 amount) external; /// @dev Deploys all tokens held in the integration contract to the integrated protocol function deploy() external; /// @dev Harvests token yield from the Aave lending pool function harvestYield() external; /// @dev This returns the total amount of the underlying token that /// @dev has been deposited to the integration contract /// @param tokenAddress The address of the deployed token /// @return The amount of the underlying token that can be withdrawn function getBalance(address tokenAddress) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IIntegrationMap { struct Integration { bool added; string name; } struct Token { uint256 id; bool added; bool acceptingDeposits; bool acceptingWithdrawals; uint256 biosRewardWeight; uint256 reserveRatioNumerator; } /// @param contractAddress The address of the integration contract /// @param name The name of the protocol being integrated to function addIntegration(address contractAddress, string memory name) external; /// @param tokenAddress The address of the ERC20 token contract /// @param acceptingDeposits Whether token deposits are enabled /// @param acceptingWithdrawals Whether token withdrawals are enabled /// @param biosRewardWeight Token weight for BIOS rewards /// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio function addToken( address tokenAddress, bool acceptingDeposits, bool acceptingWithdrawals, uint256 biosRewardWeight, uint256 reserveRatioNumerator ) external; /// @param tokenAddress The address of the token ERC20 contract function enableTokenDeposits(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function disableTokenDeposits(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function enableTokenWithdrawals(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function disableTokenWithdrawals(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract /// @param rewardWeight The updated token BIOS reward weight function updateTokenRewardWeight(address tokenAddress, uint256 rewardWeight) external; /// @param tokenAddress the address of the token ERC20 contract /// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio function updateTokenReserveRatioNumerator( address tokenAddress, uint256 reserveRatioNumerator ) external; /// @param integrationId The ID of the integration /// @return The address of the integration contract function getIntegrationAddress(uint256 integrationId) external view returns (address); /// @param integrationAddress The address of the integration contract /// @return The name of the of the protocol being integrated to function getIntegrationName(address integrationAddress) external view returns (string memory); /// @return The address of the WETH token function getWethTokenAddress() external view returns (address); /// @return The address of the BIOS token function getBiosTokenAddress() external view returns (address); /// @param tokenId The ID of the token /// @return The address of the token ERC20 contract function getTokenAddress(uint256 tokenId) external view returns (address); /// @param tokenAddress The address of the token ERC20 contract /// @return The index of the token in the tokens array function getTokenId(address tokenAddress) external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The token BIOS reward weight function getTokenBiosRewardWeight(address tokenAddress) external view returns (uint256); /// @return rewardWeightSum reward weight of depositable tokens function getBiosRewardWeightSum() external view returns (uint256 rewardWeightSum); /// @param tokenAddress The address of the token ERC20 contract /// @return bool indicating whether depositing this token is currently enabled function getTokenAcceptingDeposits(address tokenAddress) external view returns (bool); /// @param tokenAddress The address of the token ERC20 contract /// @return bool indicating whether withdrawing this token is currently enabled function getTokenAcceptingWithdrawals(address tokenAddress) external view returns (bool); // @param tokenAddress The address of the token ERC20 contract // @return bool indicating whether the token has been added function getIsTokenAdded(address tokenAddress) external view returns (bool); // @param integrationAddress The address of the integration contract // @return bool indicating whether the integration has been added function getIsIntegrationAdded(address tokenAddress) external view returns (bool); /// @notice get the length of supported tokens /// @return The quantity of tokens added function getTokenAddressesLength() external view returns (uint256); /// @notice get the length of supported integrations /// @return The quantity of integrations added function getIntegrationAddressesLength() external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The value that gets divided by the reserve ratio denominator function getTokenReserveRatioNumerator(address tokenAddress) external view returns (uint256); /// @return The token reserve ratio denominator function getReserveRatioDenominator() external view returns (uint32); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IKernel { /// @param account The address of the account to check if they are a manager /// @return Bool indicating whether the account is a manger function isManager(address account) external view returns (bool); /// @param account The address of the account to check if they are an owner /// @return Bool indicating whether the account is an owner function isOwner(address account) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; enum Modules { Kernel, // 0 UserPositions, // 1 YieldManager, // 2 IntegrationMap, // 3 BiosRewards, // 4 EtherRewards, // 5 SushiSwapTrader, // 6 UniswapTrader, // 7 StrategyMap, // 8 StrategyManager // 9 } interface IModuleMap { function getModuleAddress(Modules key) external view returns (address); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "../interfaces/IIntegration.sol"; interface IStrategyMap { // #### Structs struct WeightedIntegration { address integration; uint256 weight; } struct Strategy { string name; uint256 totalStrategyWeight; mapping(address => bool) enabledTokens; address[] tokens; WeightedIntegration[] integrations; } struct StrategySummary { string name; uint256 totalStrategyWeight; address[] tokens; WeightedIntegration[] integrations; } struct StrategyTransaction { uint256 amount; address token; } // #### Events event NewStrategy( uint256 indexed id, string name, WeightedIntegration[] integrations, address[] tokens ); event UpdateName(uint256 indexed id, string name); event UpdateIntegrations( uint256 indexed id, WeightedIntegration[] integrations ); event UpdateTokens(uint256 indexed id, address[] tokens); event DeleteStrategy( uint256 indexed id, string name, address[] tokens, WeightedIntegration[] integrations ); event EnterStrategy( uint256 indexed id, address indexed user, address[] tokens, uint256[] amounts ); event ExitStrategy( uint256 indexed id, address indexed user, address[] tokens, uint256[] amounts ); // #### Functions /** @notice Adds a new strategy to the list of available strategies @param name the name of the new strategy @param integrations the integrations and weights that form the strategy */ function addStrategy( string calldata name, WeightedIntegration[] memory integrations, address[] calldata tokens ) external; /** @notice Updates the strategy name @param name the new name */ function updateName(uint256 id, string calldata name) external; /** @notice Updates a strategy's accepted tokens @param id The strategy ID @param tokens The new tokens to allow */ function updateTokens(uint256 id, address[] calldata tokens) external; /** @notice Updates the strategy integrations @param integrations the new integrations */ function updateIntegrations( uint256 id, WeightedIntegration[] memory integrations ) external; /** @notice Deletes a strategy @dev This can only be called successfully if the strategy being deleted doesn't have any assets invested in it @param id the strategy to delete */ function deleteStrategy(uint256 id) external; /** @notice Increases the amount of a set of tokens in a strategy @param id the strategy to deposit into @param tokens the tokens to deposit @param amounts The amounts to be deposited */ function enterStrategy( uint256 id, address user, address[] calldata tokens, uint256[] calldata amounts ) external; /** @notice Decreases the amount of a set of tokens invested in a strategy @param id the strategy to withdraw assets from @param tokens the tokens to withdraw @param amounts The amounts to be withdrawn */ function exitStrategy( uint256 id, address user, address[] calldata tokens, uint256[] calldata amounts ) external; /** @notice Getter function to return the nested arrays as well as the name @param id the strategy to return */ function getStrategy(uint256 id) external view returns (StrategySummary memory); /** @notice Returns the expected balance of a given token in a given integration @param integration the integration the amount should be invested in @param token the token that is being invested @return balance the balance of the token that should be currently invested in the integration */ function getExpectedBalance(address integration, address token) external view returns (uint256 balance); /** @notice Returns the amount of a given token currently invested in a strategy @param id the strategy id to check @param token The token to retrieve the balance for @return amount the amount of token that is invested in the strategy */ function getStrategyTokenBalance(uint256 id, address token) external view returns (uint256 amount); /** @notice returns the amount of a given token a user has invested in a given strategy @param id the strategy id @param token the token address @param user the user who holds the funds @return amount the amount of token that the user has invested in the strategy */ function getUserStrategyBalanceByToken( uint256 id, address token, address user ) external view returns (uint256 amount); /** @notice Returns the amount of a given token that a user has invested across all strategies @param token the token address @param user the user holding the funds @return amount the amount of tokens the user has invested across all strategies */ function getUserInvestedAmountByToken(address token, address user) external view returns (uint256 amount); /** @notice Returns the total amount of a token invested across all strategies @param token the token to fetch the balance for @return amount the amount of the token currently invested */ function getTokenTotalBalance(address token) external view returns (uint256 amount); /** @notice Returns the weight of an individual integration within the system @param integration the integration to look up @return The weight of the integration */ function getIntegrationWeight(address integration) external view returns (uint256); /** @notice Returns the sum of all weights in the system. @return The sum of all integration weights within the system */ function getIntegrationWeightSum() external view returns (uint256); /// @notice autogenerated getter definition function idCounter() external view returns(uint256); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapTrader { /// @param slippageNumerator_ The number divided by the slippage denominator to get the slippage percentage function updateSlippageNumerator(uint24 slippageNumerator_) external; /// @notice Swaps all WETH held in this contract for BIOS and sends to the kernel /// @return Bool indicating whether the trade succeeded function biosBuyBack() external returns (bool); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address of the token out recipient /// @param amountIn The exact amount of the input to swap /// @param amountOutMin The minimum amount of tokenOut to receive from the swap /// @return bool Indicates whether the swap succeeded function swapExactInput( address tokenIn, address tokenOut, address recipient, uint256 amountIn, uint256 amountOutMin ) external returns (bool); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IUniswapTrader { struct Path { address tokenOut; uint256 firstPoolFee; address tokenInTokenOut; uint256 secondPoolFee; address tokenIn; } /// @param tokenA The address of tokenA ERC20 contract /// @param tokenB The address of tokenB ERC20 contract /// @param fee The Uniswap pool fee /// @param slippageNumerator The value divided by the slippage denominator /// to calculate the allowable slippage function addPool( address tokenA, address tokenB, uint24 fee, uint24 slippageNumerator ) external; /// @param tokenA The address of tokenA of the pool /// @param tokenB The address of tokenB of the pool /// @param poolIndex The index of the pool for the specified token pair /// @param slippageNumerator The new slippage numerator to update the pool function updatePoolSlippageNumerator( address tokenA, address tokenB, uint256 poolIndex, uint24 slippageNumerator ) external; /// @notice Changes which Uniswap pool to use as the default pool /// @notice when swapping between token0 and token1 /// @param tokenA The address of tokenA of the pool /// @param tokenB The address of tokenB of the pool /// @param primaryPoolIndex The index of the Uniswap pool to make the new primary pool function updatePairPrimaryPool( address tokenA, address tokenB, uint256 primaryPoolIndex ) external; /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address to receive the tokens /// @param amountIn The exact amount of the input to swap /// @return tradeSuccess Indicates whether the trade succeeded function swapExactInput( address tokenIn, address tokenOut, address recipient, uint256 amountIn ) external returns (bool tradeSuccess); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address to receive the tokens /// @param amountOut The exact amount of the output token to receive /// @return tradeSuccess Indicates whether the trade succeeded function swapExactOutput( address tokenIn, address tokenOut, address recipient, uint256 amountOut ) external returns (bool tradeSuccess); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param amountOut The exact amount of token being swapped for /// @return amountInMaximum The maximum amount of tokenIn to spend, factoring in allowable slippage function getAmountInMaximum( address tokenIn, address tokenOut, uint256 amountOut ) external view returns (uint256 amountInMaximum); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param amountIn The exact amount of the input to swap /// @return amountOut The estimated amount of tokenOut to receive function getEstimatedTokenOut( address tokenIn, address tokenOut, uint256 amountIn ) external view returns (uint256 amountOut); function getPathFor(address tokenOut, address tokenIn) external view returns (Path memory); function setPathFor( address tokenOut, address tokenIn, uint256 firstPoolFee, address tokenInTokenOut, uint256 secondPoolFee ) external; /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return token0 The address of the sorted token0 /// @return token1 The address of the sorted token1 function getTokensSorted(address tokenA, address tokenB) external pure returns (address token0, address token1); /// @return The number of token pairs configured function getTokenPairsLength() external view returns (uint256); /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return The quantity of pools configured for the specified token pair function getTokenPairPoolsLength(address tokenA, address tokenB) external view returns (uint256); /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @param poolId The index of the pool in the pools mapping /// @return feeNumerator The numerator that gets divided by the fee denominator function getPoolFeeNumerator( address tokenA, address tokenB, uint256 poolId ) external view returns (uint24 feeNumerator); function getPoolAddress(address tokenA, address tokenB) external view returns (address pool); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IUserPositions { /// @param biosRewardsDuration_ The duration in seconds for a BIOS rewards period to last function setBiosRewardsDuration(uint32 biosRewardsDuration_) external; /// @param sender The account seeding BIOS rewards /// @param biosAmount The amount of BIOS to add to rewards function seedBiosRewards(address sender, uint256 biosAmount) external; /// @notice Sends all BIOS available in the Kernel to each token BIOS rewards pool based up configured weights function increaseBiosRewards() external; /// @notice User is allowed to deposit whitelisted tokens /// @param depositor Address of the account depositing /// @param tokens Array of token the token addresses /// @param amounts Array of token amounts /// @param ethAmount The amount of ETH sent with the deposit function deposit( address depositor, address[] memory tokens, uint256[] memory amounts, uint256 ethAmount ) external; /// @notice User is allowed to withdraw tokens /// @param recipient The address of the user withdrawing /// @param tokens Array of token the token addresses /// @param amounts Array of token amounts /// @param withdrawWethAsEth Boolean indicating whether should receive WETH balance as ETH function withdraw( address recipient, address[] memory tokens, uint256[] memory amounts, bool withdrawWethAsEth ) external returns (uint256 ethWithdrawn); /// @notice Allows a user to withdraw entire balances of the specified tokens and claim rewards /// @param recipient The address of the user withdrawing tokens /// @param tokens Array of token address that user is exiting positions from /// @param withdrawWethAsEth Boolean indicating whether should receive WETH balance as ETH /// @return tokenAmounts The amounts of each token being withdrawn /// @return ethWithdrawn The amount of ETH being withdrawn /// @return ethClaimed The amount of ETH being claimed from rewards /// @return biosClaimed The amount of BIOS being claimed from rewards function withdrawAllAndClaim( address recipient, address[] memory tokens, bool withdrawWethAsEth ) external returns ( uint256[] memory tokenAmounts, uint256 ethWithdrawn, uint256 ethClaimed, uint256 biosClaimed ); /// @param user The address of the user claiming ETH rewards function claimEthRewards(address user) external returns (uint256 ethClaimed); /// @notice Allows users to claim their BIOS rewards for each token /// @param recipient The address of the usuer claiming BIOS rewards function claimBiosRewards(address recipient) external returns (uint256 biosClaimed); /// @param asset Address of the ERC20 token contract /// @return The total balance of the asset deposited in the system function totalTokenBalance(address asset) external view returns (uint256); /// @param asset Address of the ERC20 token contract /// @param account Address of the user account function userTokenBalance(address asset, address account) external view returns (uint256); /// @return The Bios Rewards Duration function getBiosRewardsDuration() external view returns (uint32); /// @notice Transfers tokens to the StrategyMap /// @dev This is a ledger adjustment. The tokens remain in the kernel. /// @param recipient The user to transfer funds for /// @param tokens the tokens to be moved /// @param amounts the amounts of each token to move function transferToStrategy( address recipient, address[] memory tokens, uint256[] memory amounts ) external; /// @notice Transfers tokens from the StrategyMap /// @dev This is a ledger adjustment. The tokens remain in the kernel. /// @param recipient The user to transfer funds for /// @param tokens the tokens to be moved /// @param amounts the amounts of each token to move function transferFromStrategy( address recipient, address[] memory tokens, uint256[] memory amounts ) external; } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IWeth9 { event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); function deposit() external payable; /// @param wad The amount of wETH to withdraw into ETH function withdraw(uint256 wad) external; } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IYieldManager { /// @param gasAccountTargetEthBalance_ The target ETH balance of the gas account function updateGasAccountTargetEthBalance(uint256 gasAccountTargetEthBalance_) external; /// @param biosBuyBackEthWeight_ The relative weight of ETH to send to BIOS buy back /// @param treasuryEthWeight_ The relative weight of ETH to send to the treasury /// @param protocolFeeEthWeight_ The relative weight of ETH to send to protocol fee accrual /// @param rewardsEthWeight_ The relative weight of ETH to send to user rewards function updateEthDistributionWeights( uint32 biosBuyBackEthWeight_, uint32 treasuryEthWeight_, uint32 protocolFeeEthWeight_, uint32 rewardsEthWeight_ ) external; /// @param gasAccount_ The address of the account to send ETH to gas for executing bulk system functions function updateGasAccount(address payable gasAccount_) external; /// @param treasuryAccount_ The address of the system treasury account function updateTreasuryAccount(address payable treasuryAccount_) external; /// @notice Withdraws and then re-deploys tokens to integrations according to configured weights function rebalance() external; /// @notice Deploys all tokens to all integrations according to configured weights function deploy() external; /// @notice Harvests available yield from all tokens and integrations function harvestYield() external; /// @notice Swaps harvested yield for all tokens for ETH function processYield() external; /// @notice Distributes ETH to the gas account, BIOS buy back, treasury, protocol fee accrual, and user rewards function distributeEth() external; /// @notice Uses WETH to buy back BIOS which is sent to the Kernel function biosBuyBack() external; /// @param tokenAddress The address of the token ERC20 contract /// @return harvestedTokenBalance The amount of the token yield harvested held in the Kernel function getHarvestedTokenBalance(address tokenAddress) external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The amount of the token held in the Kernel as reserves function getReserveTokenBalance(address tokenAddress) external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The desired amount of the token to hold in the Kernel as reserves function getDesiredReserveTokenBalance(address tokenAddress) external view returns (uint256); /// @return ethWeightSum The sum of ETH distribution weights function getEthWeightSum() external view returns (uint32 ethWeightSum); /// @return processedWethSum The sum of yields processed into WETH function getProcessedWethSum() external view returns (uint256 processedWethSum); /// @param tokenAddress The address of the token ERC20 contract /// @return The amount of WETH received from token yield processing function getProcessedWethByToken(address tokenAddress) external view returns (uint256); /// @return processedWethByTokenSum The sum of processed WETH function getProcessedWethByTokenSum() external view returns (uint256 processedWethByTokenSum); /// @param tokenAddress The address of the token ERC20 contract /// @return tokenTotalIntegrationBalance The total amount of the token that can be withdrawn from integrations function getTokenTotalIntegrationBalance(address tokenAddress) external view returns (uint256 tokenTotalIntegrationBalance); /// @return The address of the gas account function getGasAccount() external view returns (address); /// @return The address of the treasury account function getTreasuryAccount() external view returns (address); /// @return The last amount of ETH distributed to rewards function getLastEthRewardsAmount() external view returns (uint256); /// @return The target ETH balance of the gas account function getGasAccountTargetEthBalance() external view returns (uint256); /// @return The BIOS buyback ETH weight /// @return The Treasury ETH weight /// @return The Protocol fee ETH weight /// @return The rewards ETH weight function getEthDistributionWeights() external view returns ( uint32, uint32, uint32, uint32 ); }
tokenAddress The address of the token ERC20 contract return harvestedTokenBalance The amount of the token yield harvested held in the Kernel
function getHarvestedTokenBalance(address tokenAddress) external view override returns (uint256 harvestedTokenBalance) { if ( tokenAddress == IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getWethTokenAddress() ) { harvestedTokenBalance = IERC20MetadataUpgradeable(tokenAddress).balanceOf(address(this)) - getProcessedWethSum(); harvestedTokenBalance = IERC20MetadataUpgradeable(tokenAddress).balanceOf( address(this) ); } }
13,875,908
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./FuelToken.sol"; contract Staking is Ownable { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many stake tokens the user has provided. uint256 rewardDebt; // Reward debt. } // Info of each pool. struct PoolInfo { uint128 accRewardPerShare; // Accumulated reward per share, times 1e12. See below. uint64 lastRewardBlock; // Last block number that reward distribution occurs. uint64 allocPoint; // How many allocation points assigned to this pool. Reward to distribute per block. } // The reward token! FuelToken public rewardToken; // Block number when bonus reward period ends. uint256 public bonusEndBlock; // Reward tokens created per block. uint256 public rewardPerBlock; // Bonus muliplier for early stakers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Addresses of stake token contract. IERC20[] stakeToken; // Info of each user that stakes stake tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when reward mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event TokenChanged(uint256 pid, address oldTokenAddress, address newTokenAddress); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed stakeToken); event LogSetPool(uint256 indexed pid, uint256 allocPoint); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 stakedSupply, uint256 accSushiPerShare); constructor( FuelToken _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new stake token to the pool. Can only be called by the owner. // XXX DO NOT add the same stake token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _stakeToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ accRewardPerShare: 0, lastRewardBlock: uint64(lastRewardBlock), allocPoint: uint64(_allocPoint) }) ); stakeToken.push(_stakeToken); emit LogPoolAddition(stakeToken.length - 1, _allocPoint, _stakeToken); } // Update the given pool's reward allocation point. Can only be called by the owner. function set( uint256 _pid, uint64 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; emit LogSetPool(_pid, _allocPoint); } function changeStakeToken(uint256 _pid, IERC20 _newToken) public onlyOwner { require(address(_newToken) != address(0), "newTokenAddress is zero"); uint256 bal = stakeToken[_pid].balanceOf(address(this)); _newToken.transferFrom(_msgSender(), address(this), bal); require(_newToken.balanceOf(address(this)) == bal, "migrate: bad"); emit TokenChanged( _pid, address(stakeToken[_pid]), address(_newToken) ); stakeToken[_pid] = _newToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return (bonusEndBlock - _from) * BONUS_MULTIPLIER + _to - bonusEndBlock; } } // View function to see pending reward on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 stakedSupply = stakeToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && stakedSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 reward = multiplier * rewardPerBlock * pool.allocPoint / totalAllocPoint; accRewardPerShare += reward * 1e12 / stakedSupply; } return user.amount * accRewardPerShare / 1e12 - user.rewardDebt; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 stakedSupply = stakeToken[_pid].balanceOf(address(this)); if (stakedSupply == 0) { pool.lastRewardBlock = uint64(block.number); return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 reward = multiplier * rewardPerBlock * pool.allocPoint / totalAllocPoint; rewardToken.mint(address(this), reward); pool.accRewardPerShare += uint128(reward * 1e12 / stakedSupply); pool.lastRewardBlock = uint64(block.number); emit LogUpdatePool(_pid, uint64(block.number), stakedSupply, pool.accRewardPerShare); } // Deposit stake tokens to Staking contract for reward allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount * pool.accRewardPerShare / 1e12 - user.rewardDebt; safeRewardTransfer(msg.sender, pending); } stakeToken[_pid].safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount += _amount; user.rewardDebt = user.amount * pool.accRewardPerShare / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw stake tokens from Staking contract. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount * pool.accRewardPerShare / 1e12 - user.rewardDebt; safeRewardTransfer(msg.sender, pending); stakeToken[_pid].safeTransfer(address(msg.sender), _amount); user.amount -= _amount; user.rewardDebt = user.amount * pool.accRewardPerShare / 1e12; emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; stakeToken[_pid].safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe reward transfer function, just in case if rounding error causes pool to not have enough reward tokens. function safeRewardTransfer(address _to, uint256 _amount) internal { uint256 rewardBal = rewardToken.balanceOf(address(this)); if (_amount > rewardBal) { rewardToken.transfer(_to, rewardBal); } else { rewardToken.transfer(_to, _amount); } } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 stakedSupply = stakeToken[_pid].balanceOf(address(this)); if (stakedSupply == 0) { pool.lastRewardBlock = uint64(block.number); return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 reward = multiplier * rewardPerBlock * pool.allocPoint / totalAllocPoint; rewardToken.mint(address(this), reward); pool.accRewardPerShare += uint128(reward * 1e12 / stakedSupply); pool.lastRewardBlock = uint64(block.number); emit LogUpdatePool(_pid, uint64(block.number), stakedSupply, pool.accRewardPerShare); }
919,091
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title GraphTokenDistributor * @dev Contract that allows distribution of tokens to multiple beneficiaries. * The contract accept deposits in the configured token by anyone. * The owner can setup the desired distribution by setting the amount of tokens * assigned to each beneficiary account. * Beneficiaries claim for their allocated tokens. * Only the owner can withdraw tokens from this contract without limitations. * For the distribution to work this contract must be unlocked by the owner. */ contract GraphTokenDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // -- State -- bool public locked; mapping(address => uint256) public beneficiaries; IERC20 public token; // -- Events -- event BeneficiaryUpdated(address indexed beneficiary, uint256 amount); event TokensDeposited(address indexed sender, uint256 amount); event TokensWithdrawn(address indexed sender, uint256 amount); event TokensClaimed(address indexed beneficiary, address to, uint256 amount); event LockUpdated(bool locked); modifier whenNotLocked() { require(locked == false, "Distributor: Claim is locked"); _; } /** * Constructor. * @param _token Token to use for deposits and withdrawals */ constructor(IERC20 _token) { token = _token; locked = true; } /** * Deposit tokens into the contract. * Even if the ERC20 token can be transferred directly to the contract * this function provide a safe interface to do the transfer and avoid mistakes * @param _amount Amount to deposit */ function deposit(uint256 _amount) external { token.safeTransferFrom(msg.sender, address(this), _amount); emit TokensDeposited(msg.sender, _amount); } // -- Admin functions -- /** * Add token balance available for account. * @param _account Address to assign tokens to * @param _amount Amount of tokens to assign to beneficiary */ function addBeneficiaryTokens(address _account, uint256 _amount) external onlyOwner { _setBeneficiaryTokens(_account, beneficiaries[_account].add(_amount)); } /** * Add token balance available for multiple accounts. * @param _accounts Addresses to assign tokens to * @param _amounts Amounts of tokens to assign to beneficiary */ function addBeneficiaryTokensMulti(address[] calldata _accounts, uint256[] calldata _amounts) external onlyOwner { require(_accounts.length == _amounts.length, "Distributor: !length"); for (uint256 i = 0; i < _accounts.length; i++) { _setBeneficiaryTokens(_accounts[i], beneficiaries[_accounts[i]].add(_amounts[i])); } } /** * Remove token balance available for account. * @param _account Address to assign tokens to * @param _amount Amount of tokens to assign to beneficiary */ function subBeneficiaryTokens(address _account, uint256 _amount) external onlyOwner { _setBeneficiaryTokens(_account, beneficiaries[_account].sub(_amount)); } /** * Remove token balance available for multiple accounts. * @param _accounts Addresses to assign tokens to * @param _amounts Amounts of tokens to assign to beneficiary */ function subBeneficiaryTokensMulti(address[] calldata _accounts, uint256[] calldata _amounts) external onlyOwner { require(_accounts.length == _amounts.length, "Distributor: !length"); for (uint256 i = 0; i < _accounts.length; i++) { _setBeneficiaryTokens(_accounts[i], beneficiaries[_accounts[i]].sub(_amounts[i])); } } /** * Set amount of tokens available for beneficiary account. * @param _account Address to assign tokens to * @param _amount Amount of tokens to assign to beneficiary */ function _setBeneficiaryTokens(address _account, uint256 _amount) private { require(_account != address(0), "Distributor: !account"); beneficiaries[_account] = _amount; emit BeneficiaryUpdated(_account, _amount); } /** * Set locked withdrawals. * @param _locked True to lock withdrawals */ function setLocked(bool _locked) external onlyOwner { locked = _locked; emit LockUpdated(_locked); } /** * Withdraw tokens from the contract. This function is included as * a escape hatch in case of mistakes or to recover remaining funds. * @param _amount Amount of tokens to withdraw */ function withdraw(uint256 _amount) external onlyOwner { token.safeTransfer(msg.sender, _amount); emit TokensWithdrawn(msg.sender, _amount); } // -- Beneficiary functions -- /** * Claim tokens and send to caller. */ function claim() external whenNotLocked { claimTo(msg.sender); } /** * Claim tokens and send to address. * @param _to Address where to send tokens */ function claimTo(address _to) public whenNotLocked { uint256 claimableTokens = beneficiaries[msg.sender]; require(claimableTokens > 0, "Distributor: Unavailable funds"); _setBeneficiaryTokens(msg.sender, 0); token.safeTransfer(_to, claimableTokens); emit TokensClaimed(msg.sender, _to, claimableTokens); } }
Withdraw tokens from the contract. This function is included as a escape hatch in case of mistakes or to recover remaining funds. _amount Amount of tokens to withdraw/
function withdraw(uint256 _amount) external onlyOwner { token.safeTransfer(msg.sender, _amount); emit TokensWithdrawn(msg.sender, _amount); }
13,110,980
./full_match/44787/0x218F66D2734d8E4D80C2F0908a6D8f973b0Ea83e/sources/contracts/community/CommunityImplementation.sol
Updates params of a community _minTranche minimum amount that the community will receive when requesting funds _maxTranche maximum amount that the community will receive when requesting funds/
function updateCommunityParams(uint256 _minTranche, uint256 _maxTranche) external override onlyOwner { require( _minTranche <= _maxTranche, "Community::updateCommunityParams: minTranche should not be greater than maxTranche" ); uint256 _oldMinTranche = minTranche; uint256 _oldMaxTranche = maxTranche; minTranche = _minTranche; maxTranche = _maxTranche; emit CommunityParamsUpdated(_oldMinTranche, _oldMaxTranche, _minTranche, _maxTranche); }
13,243,657
pragma solidity ^0.5.12; import "./CErc20.sol"; import "./CToken.sol"; import "./PriceOracle.sol"; import "./Comptroller.sol"; contract PriceOracleOTL is PriceOracle { /** * @notice The comptroller which is used to white-list assets the oracle will price * @dev Assets which are not white-listed will not be priced, to defend against abuse */ Comptroller public comptroller; address payable public admin; address payable public poster; bool public constant isPriceOracle = true; /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; mapping(address => uint) prices; event PricePosted(address indexed asset, address indexed postedBy, uint previousPriceMantissa, uint indexed requestedPriceMantissa, uint newPriceMantissa); event NewPoster(address indexed oldPoster, address indexed newPoster); event NewAdmin(address indexed oldAdmin, address indexed newAdmin); constructor(address comptroller_) public { comptroller = Comptroller(comptroller_); _setAdminInternal(msg.sender); _setPosterInternal(msg.sender); _notEntered = true; } /** * @notice Do not pay into PriceOracle */ function() external payable { revert("Fallback Revert"); } function getUnderlyingPrice(CToken cToken) public view returns (uint) { address cTokenAddress = address(cToken); (bool isListed, ,) = comptroller.markets(cTokenAddress); if (!isListed) { // not white-listed, worthless return 0; } return prices[address(CErc20(address(cToken)).underlying())]; } function setUnderlyingPrice(CToken cToken, uint underlyingPriceMantissa) public nonReentrant { require(msg.sender == poster || msg.sender == admin, "Unauthorized"); address asset = address(CErc20(address(cToken)).underlying()); emit PricePosted(asset, msg.sender, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } function setDirectPrice(address asset, uint priceMantissa) public { require(msg.sender == poster || msg.sender == admin, "Unauthorized"); emit PricePosted(asset, msg.sender, prices[asset], priceMantissa, priceMantissa); prices[asset] = priceMantissa; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } /*** Admin Functions ***/ function _setPoster(address payable newPoster) external { // Check caller = admin require(msg.sender == admin, "Unauthorized"); _setPosterInternal(newPoster); } function _setAdmin(address payable newAdmin) external { require(msg.sender == admin, "Unauthorized"); _setAdminInternal(newAdmin); _setPosterInternal(newAdmin); } function _setPosterInternal(address payable newPoster) internal { emit NewPoster(poster, newPoster); poster = newPoster; } function _setAdminInternal(address payable newAdmin) internal { emit NewAdmin(admin, newAdmin); admin = newAdmin; } /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } }
not white-listed, worthless
function getUnderlyingPrice(CToken cToken) public view returns (uint) { address cTokenAddress = address(cToken); (bool isListed, ,) = comptroller.markets(cTokenAddress); if (!isListed) { return 0; } return prices[address(CErc20(address(cToken)).underlying())]; }
1,011,906
./full_match/1/0x47d62Ed9fE6ef6810EaC3165053d95579059e827/sources/contracts/lib/ConversionHelpers.sol
Force cast the bytes array into a uint256[], by overwriting its length Note that the uint256[] doesn't need to be initialized as we immediately overwrite it with the input and a new length. The input becomes invalid from this point forward.
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } }
16,396,867
./partial_match/1/0xbffac64ef43e5bD8036247767f4Af94538804295/sources/BraShop.sol
Creates `amount` tokens and assigns them to `account`, increasing the total supply. ADJUSTMENTS: Can only mint up to 13k (13e21) BBRA (burn + farm rewards have to be stable at lower than 13k) Emits a {Transfer} event with `from` set to the zero address. Requirements - `to` cannot be the zero address./ if supply is over 13k after adding 'amount' check what is available to be minted (13e21 - current supply) if it's greater than 0 then we can mint up to that amount Eg totalSupply = 12,999e18 BBRA and amount to be minted is 10e18 BBRA. We can't mint 10e18 because it takes us over hard cap. However we can mint a partial amount aka 13e21 - 12,999e18 = 1e18 can't mint even a partial amount so we must exit the function
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); if (_totalSupply.add(amount) > 13e21) { amount = uint256(13e21).sub(_totalSupply); if (amount == 0) return; } _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
4,216,987
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./Registry.sol"; /// @title Extension of the Transferable Certificate standard ERC-1888. contract RegistryExtended is Registry { event TransferBatchMultiple(address indexed operator, address[] from, address[] to, uint256[] ids, uint256[] values); event ClaimBatchMultiple(address[] _claimIssuer, address[] _claimSubject, uint256[] indexed _topics, uint256[] _ids, uint256[] _values, bytes[] _claimData); constructor(string memory _uri) Registry(_uri) { // Trigger Registry constructor } /// @notice Similar to {IERC1888-batchIssue}, but not a part of the ERC-1888 standard. /// @dev Allows batch issuing to an array of _to addresses. /// @dev `_to` cannot be the zero addresses. /// @dev `_to`, `_data`, `_values`, `_topics` and `_validityData` must have the same length. function batchIssueMultiple(address[] calldata _to, bytes[] calldata _validityData, uint256[] calldata _topics, uint256[] calldata _values, bytes[] calldata _data) external returns (uint256[] memory ids) { require(_values.length > 0, "no values specified"); require(_to.length == _data.length, "Arrays not same length"); require(_data.length == _values.length, "Arrays not same length"); require(_values.length == _validityData.length, "Arrays not same length"); require(_validityData.length == _topics.length, "Arrays not same length"); ids = new uint256[](_values.length); address operator = _msgSender(); for (uint256 i = 0; i < _values.length; i++) { require(_to[i] != address(0x0), "_to must be non-zero."); ids[i] = i + _latestCertificateId + 1; _validate(operator, _validityData[i]); } for (uint256 i = 0; i < ids.length; i++) { ERC1155._mint(_to[i], ids[i], _values[i], _data[i]); // Check ** certificateStorage[ids[i]] = Certificate({ topic: _topics[i], issuer: operator, validityData: _validityData[i], data: _data[i] }); } _latestCertificateId = ids[ids.length - 1]; emit IssuanceBatch(operator, _topics, ids, _values); } /// @notice Similar to {ERC1155-safeBatchTransferFrom}, but not a part of the ERC-1155 standard. /// @dev Allows batch transferring to/from an array of addresses. function safeBatchTransferFromMultiple( address[] calldata _from, address[] calldata _to, uint256[] calldata _ids, uint256[] calldata _values, bytes[] calldata _data ) external { require(_from.length == _to.length, "Arrays not same length"); require(_to.length == _ids.length, "Arrays not same length"); require(_ids.length == _values.length, "Arrays not same length"); require(_values.length == _data.length, "Arrays not same length."); for (uint256 i = 0; i < _ids.length; i++) { require(_from[i] != address(0x0), "_from must be non-zero."); require(_to[i] != address(0x0), "_to must be non-zero."); require(_from[i] == _msgSender() || ERC1155.isApprovedForAll(_from[i], _msgSender()), "No operator approval"); require(ERC1155.balanceOf(_from[i], _ids[i]) >= _values[i], "Not enough balance to transfer"); Certificate memory cert = certificateStorage[_ids[i]]; _validate(cert.issuer, cert.validityData); } address operator = _msgSender(); for (uint256 i = 0; i < _ids.length; ++i) { _safeTransferFrom(_from[i], _to[i], _ids[i], _values[i], _data[i]); } emit TransferBatchMultiple(operator, _from, _to, _ids, _values); } /// @notice Similar to {IERC1888-safeBatchTransferAndClaimFrom}, but not a part of the ERC-1888 standard. /// @dev Allows batch claiming to/from an array of addresses. function safeBatchTransferAndClaimFromMultiple( address[] calldata _from, address[] calldata _to, uint256[] calldata _ids, uint256[] calldata _values, bytes[] calldata _data, bytes[] calldata _claimData ) external { require(_ids.length > 0, "no certificates specified"); require(_from.length == _to.length, "Arrays not same length"); require(_to.length == _ids.length, "Arrays not same length"); require(_ids.length == _values.length, "Arrays not same length"); require(_values.length == _data.length, "Arrays not same length."); require(_data.length == _claimData.length, "Arrays not same length."); uint256[] memory topics = new uint256[](_ids.length); for (uint256 i = 0; i < _ids.length; i++) { require(_from[i] != address(0x0), "_from must be non-zero."); require(_to[i] != address(0x0), "_to must be non-zero."); require(_from[i] == _msgSender() || ERC1155.isApprovedForAll(_from[i], _msgSender()), "No operator approval"); require(ERC1155.balanceOf(_from[i], _ids[i]) >= _values[i], "Not enough balance to claim"); Certificate memory cert = certificateStorage[_ids[i]]; _validate(cert.issuer, cert.validityData); } for (uint256 i = 0; i < _ids.length; i++) { Certificate memory cert = certificateStorage[_ids[i]]; topics[i] = cert.topic; if (_from[i] != _to[i]) { _safeTransferFrom(_from[i], _to[i], _ids[i], _values[i], _data[i]); } _burn(_to[i], _ids[i], _values[i]); } emit ClaimBatchMultiple(_from, _to, topics, _ids, _values, _claimData); } }
Similar to {IERC1888-batchIssue}, but not a part of the ERC-1888 standard. Allows batch issuing to an array of _to addresses. `_to` cannot be the zero addresses. `_to`, `_data`, `_values`, `_topics` and `_validityData` must have the same length.
function batchIssueMultiple(address[] calldata _to, bytes[] calldata _validityData, uint256[] calldata _topics, uint256[] calldata _values, bytes[] calldata _data) external returns (uint256[] memory ids) { require(_values.length > 0, "no values specified"); require(_to.length == _data.length, "Arrays not same length"); require(_data.length == _values.length, "Arrays not same length"); require(_values.length == _validityData.length, "Arrays not same length"); require(_validityData.length == _topics.length, "Arrays not same length"); ids = new uint256[](_values.length); address operator = _msgSender(); for (uint256 i = 0; i < _values.length; i++) { require(_to[i] != address(0x0), "_to must be non-zero."); ids[i] = i + _latestCertificateId + 1; _validate(operator, _validityData[i]); } for (uint256 i = 0; i < ids.length; i++) { certificateStorage[ids[i]] = Certificate({ topic: _topics[i], issuer: operator, validityData: _validityData[i], data: _data[i] }); } _latestCertificateId = ids[ids.length - 1]; emit IssuanceBatch(operator, _topics, ids, _values); }
15,795,499
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "./ModuleSelfAuth.sol"; import "./ModuleStorage.sol"; import "./ModuleERC165.sol"; import "./interfaces/IModuleCalls.sol"; import "./interfaces/IModuleAuth.sol"; /** @notice Implements ModuleCalls but ignores the validity of the nonce should only be used during gas estimation. */ abstract contract ModuleIgnoreNonceCalls is IModuleCalls, IModuleAuth, ModuleERC165, ModuleSelfAuth { // NONCE_KEY = keccak256("org.arcadeum.module.calls.nonce"); bytes32 private constant NONCE_KEY = bytes32(0x8d0bf1fd623d628c741362c1289948e57b3e2905218c676d3e69abee36d6ae2e); uint256 private constant NONCE_BITS = 96; bytes32 private constant NONCE_MASK = bytes32((1 << NONCE_BITS) - 1); /** * @notice Returns the next nonce of the default nonce space * @dev The default nonce space is 0x00 * @return The next nonce */ function nonce() external override virtual view returns (uint256) { return readNonce(0); } /** * @notice Returns the next nonce of the given nonce space * @param _space Nonce space, each space keeps an independent nonce count * @return The next nonce */ function readNonce(uint256 _space) public override virtual view returns (uint256) { return uint256(ModuleStorage.readBytes32Map(NONCE_KEY, bytes32(_space))); } /** * @notice Changes the next nonce of the given nonce space * @param _space Nonce space, each space keeps an independent nonce count * @param _nonce Nonce to write on the space */ function _writeNonce(uint256 _space, uint256 _nonce) private { ModuleStorage.writeBytes32Map(NONCE_KEY, bytes32(_space), bytes32(_nonce)); } /** * @notice Allow wallet owner to execute an action * @dev Relayers must ensure that the gasLimit specified for each transaction * is acceptable to them. A user could specify large enough that it could * consume all the gas available. * @param _txs Transactions to process * @param _nonce Signature nonce (may contain an encoded space) * @param _signature Encoded signature */ function execute( Transaction[] memory _txs, uint256 _nonce, bytes memory _signature ) public override virtual { // Validate and update nonce _validateNonce(_nonce); // Hash transaction bundle bytes32 txHash = _subDigest(keccak256(abi.encode(_nonce, _txs))); // Verify that signatures are valid require( _signatureValidation(txHash, _signature), "ModuleCalls#execute: INVALID_SIGNATURE" ); // Execute the transactions _execute(txHash, _txs); } /** * @notice Allow wallet to execute an action * without signing the message * @param _txs Transactions to execute */ function selfExecute( Transaction[] memory _txs ) public override virtual onlySelf { // Hash transaction bundle bytes32 txHash = _subDigest(keccak256(abi.encode('self:', _txs))); // Execute the transactions _execute(txHash, _txs); } /** * @notice Executes a list of transactions * @param _txHash Hash of the batch of transactions * @param _txs Transactions to execute */ function _execute( bytes32 _txHash, Transaction[] memory _txs ) private { // Execute transaction for (uint256 i = 0; i < _txs.length; i++) { Transaction memory transaction = _txs[i]; bool success; bytes memory result; require(gasleft() >= transaction.gasLimit, "ModuleCalls#_execute: NOT_ENOUGH_GAS"); if (transaction.delegateCall) { (success, result) = transaction.target.delegatecall{ gas: transaction.gasLimit == 0 ? gasleft() : transaction.gasLimit }(transaction.data); } else { (success, result) = transaction.target.call{ value: transaction.value, gas: transaction.gasLimit == 0 ? gasleft() : transaction.gasLimit }(transaction.data); } if (success) { emit TxExecuted(_txHash); } else { _revertBytes(transaction, _txHash, result); } } } /** * @notice Verify if a nonce is valid * @param _rawNonce Nonce to validate (may contain an encoded space) * @dev A valid nonce must be above the last one used * with a maximum delta of 100 */ function _validateNonce(uint256 _rawNonce) private { // Retrieve current nonce for this wallet (uint256 space, uint256 providedNonce) = _decodeNonce(_rawNonce); uint256 currentNonce = readNonce(space); // Verify if nonce is valid // Skip nonce validation for gas estimation require( (providedNonce == currentNonce) || true, "MainModule#_auth: INVALID_NONCE" ); // Update signature nonce uint256 newNonce = providedNonce + 1; _writeNonce(space, newNonce); emit NonceChange(space, newNonce); } /** * @notice Logs a failed transaction, reverts if the transaction is not optional * @param _tx Transaction that is reverting * @param _txHash Hash of the transaction * @param _reason Encoded revert message */ function _revertBytes( Transaction memory _tx, bytes32 _txHash, bytes memory _reason ) internal { if (_tx.revertOnError) { assembly { revert(add(_reason, 0x20), mload(_reason)) } } else { emit TxFailed(_txHash, _reason); } } /** * @notice Decodes a raw nonce * @dev A raw nonce is encoded using the first 160 bits for the space * and the last 96 bits for the nonce * @param _rawNonce Nonce to be decoded * @return _space The nonce space of the raw nonce * @return _nonce The nonce of the raw nonce */ function _decodeNonce(uint256 _rawNonce) private pure returns (uint256 _space, uint256 _nonce) { _nonce = uint256(bytes32(_rawNonce) & NONCE_MASK); _space = _rawNonce >> NONCE_BITS; } /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface(bytes4 _interfaceID) public override virtual pure returns (bool) { if (_interfaceID == type(IModuleCalls).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } }
Verify if a nonce is valid _rawNonce Nonce to validate (may contain an encoded space) A valid nonce must be above the last one used with a maximum delta of 100/ Retrieve current nonce for this wallet Verify if nonce is valid Skip nonce validation for gas estimation Update signature nonce
function _validateNonce(uint256 _rawNonce) private { (uint256 space, uint256 providedNonce) = _decodeNonce(_rawNonce); uint256 currentNonce = readNonce(space); require( (providedNonce == currentNonce) || true, "MainModule#_auth: INVALID_NONCE" ); uint256 newNonce = providedNonce + 1; _writeNonce(space, newNonce); emit NonceChange(space, newNonce); }
15,794,949
pragma solidity ^0.8.9; // standard Zeppelin Ownable modified for Plantidote LLC - ie no owner xfer and no owner relinquish. contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. * * Disabled for Plantidote LLC - A profile owner cannot xfer his profile to another Hedera Account ie a non plantidote Account * This is especially true IF the Account hold is KYC approved (for rewards of course). function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } */ /** * @dev Allows the current owner ONLY to relinquish control of the contract but this DOES NOT delete it from Hedera - only suicide func does. * not permitted for Plantidote - Account must be deletable only by owner and to not be able to exist with no-control. function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } */ } contract plantaccountprofile is Ownable { using SafeMath for uint256; // Plantidote LLC 10/8/2021. // owner set via ownable constructor to deployer - which is the created new key paired Client Account for the DApp. // Plantidote LLC has Customers of various Actor types(rolecode) & they own their own data and data control preferences. // Consumer, Dispenser, Broker, Grower, Processor - TBD/ refined by C-levels as required. // Actors can be one or multiple types at any given/same time during their lifecycle. // Owners can enter a KYC process ie if platform offers rewards for a Gov/central photo id verification process. etc. Driv lic/passport. string private fname; string private lname; string private nickname; string private phone; string private nationality; string private rolecode; // rolecode permitted values C/D/B/G/P Consumer - Dispenser - Broker - Grower - Processor string private plantaccountfileid; // this is the PLANT account# in Customer terms (holds account/keys,pwrdhash,profile sc id, Circle subaccount/keys) address private planthhaccountid; // this is the Hedera accountid that holds HBARs and holds PLANT tokens(TBD after MvP) //string private circlewalletid; // circle is moot now. //uint256 private usdcbal; // TBD - Circle mirror balance - updated sate after each circle call if needed. // rolecode ids specific attributions - reminder - can be many Actors at the same time. uint256 private consumeridnum; uint256 private dispenseridnum; uint256 private brokeridnum; uint256 private processoridnum; uint256 private groweridnum; // same for grower/processor/broker .. can concat into the accountid later on. string private dataipfshash1; // can optimise string to bytes later on for min gas costs(marginal) string private dataipfshash2; string private dataipfshash3; // used for ipfs link to KYC phot id image - to be encrypted of course prior to ipfs put. address private platformaddress; // used to ensure that only the signed keypair of the Plantidote LLC is authorized. // demographics, behavioral, interests - sample TBD - optional profile data can be offered by Account holder. // Likes and interests - PoC small interest selection for demo purposes. 'categories to choose from or indexes'. bool public kycapproved; // set true or false - after 3rd praty plugin/ or in App KYC - driv lic pic /passport imagery or other TBD bool public platformaccess_corepermission; // switch if Customer permits platform to be able to view their profile or not. bool public platformaccess_noncorepermission; // switch if Customer permits platform to be able to view their profile or not. string private interest1; string private interest2; string private interest3; // the following are public so platform's advertisers(sponsors) can see the openness OR not of the Owner, as permissions for the platform and Sponsors to // see the data owners decisions ie so Data owner can get PLANT token or USDC rewards // - but only Contract OnlyOwner ie the profile owner can update. bool public demographic; bool public behavioral; bool public interests; uint256 public sponsorslevel; uint256 public grpsponsorslevel; constructor( string memory _fname, string memory _lname, string memory _nickname, string memory _phone, string memory _nationality, string memory _rolecode, string memory _plantaccountfileid, address _planthhacountid, string memory _dataipfshash1, string memory _dataipfshash2, string memory _dataipfshash3, address _platformaddress, bool _platformaccess_corepermission, bool _platformaccess_noncorepermission ) { // Plant hhaccountid is the hedera public key/assigned Account assigned at time of onboarding. fname = _fname; lname = _lname; nickname = _nickname; phone = _phone; nationality = _nationality; rolecode = _rolecode; plantaccountfileid = _plantaccountfileid; planthhaccountid = _planthhacountid; //circlewalletid = _circlewalletid; moot as of 10/12 //usdcbal = 0; // will probably be a PLANT token - of 1USD value in HBAR terms. TBD dataipfshash1 = _dataipfshash1; dataipfshash2 = _dataipfshash2; dataipfshash3 = _dataipfshash3; kycapproved = false; // later function can only enable this. platformaddress = _platformaddress; platformaccess_corepermission = _platformaccess_corepermission;// on create.. can be set by User platformaccess_noncorepermission = _platformaccess_noncorepermission; // on create.. can be set by User } // Events broadcast to ledger as public but anonymous receipt, if needs be. see notes to detect Events on Hedera. // more to add event Profilecreated( address smartcontractid ); event Profileupdated( address plantaccountfileid ); event Interestsupdated( address plantaccountfileid ); event Opennessupdated( address plantaccountfileid ); // custom Modifiers for Platform updates e.g. when fileID created - this needs to be inserted into this SC modifier onlyplant { require(msg.sender == platformaddress); _; } // custom Modifiers for Owner OR Platform for profile data for DApp operations e.g. rolecode ! modifier onlyOwnerorplant { require((msg.sender == owner) || (msg.sender == platformaddress)); _; } // custom Modifier for Owner OR Platform for core profile data ie names/nickname - with permission modifier onlyOwnerorplantcore { require((msg.sender == owner) || (msg.sender == platformaddress && platformaccess_corepermission)); _; } // custom Modifier for Owner OR Platform for non-core profile data. ie interests and Advertiser (sponsors) exposure settings/rating modifier onlyOwnerorplantnoncore { require((msg.sender == owner) || (msg.sender == platformaddress && platformaccess_noncorepermission)); _; } // getters .. // getters for Owner only unless access permission given to Plantidote to see (for later rewards of course) function getfname() view onlyOwnerorplantcore public returns(string memory) { return fname; } function getlname() view onlyOwnerorplantcore public returns(string memory) { return lname; } function getnickname() view onlyOwnerorplantcore public returns(string memory) { return nickname; } function getphone() view onlyOwnerorplantcore public returns(string memory) { return phone; } function getnationality() view onlyOwnerorplantcore public returns(string memory) { return nationality; } // platform and Owner can see the role codes, circle walletid- needed by DApp to custom the dashboard function getrolecode() view onlyOwnerorplant public returns(string memory) { return rolecode; } // mooted. /* function getcirclewalletid() view onlyOwnerorplant public returns(string memory) { return circlewalletid; } */ function getplatformaccess_corepermission() view onlyOwnerorplant public returns(bool) { return platformaccess_corepermission; } function getplatformaccess_noncorepermission() view onlyOwnerorplant public returns(bool) { return platformaccess_noncorepermission; } function getconsumeridnum() view onlyOwnerorplant public returns(uint256) { return consumeridnum; } function getdispenseridnum() view onlyOwnerorplant public returns(uint256) { return dispenseridnum; } function getbrokeridnum() view onlyOwnerorplant public returns(uint256) { return brokeridnum; } function getprocessoridnum() view onlyOwnerorplant public returns(uint256) { return processoridnum; } function getgroweridnum() view onlyOwnerorplant public returns(uint256) { return groweridnum; } function getkycapproved() view onlyOwnerorplant public returns(bool) { return kycapproved; } // in case Customer forgets their Plantidote account fileid or HBAR account. ie the hedera fileid holding their planthhaccountid. function getplantaccountfileid() view onlyOwnerorplant public returns(string memory) { return plantaccountfileid; } function getplanthhaccountid() view onlyOwnerorplant public returns(address) { return planthhaccountid; } // picture id - gov/ driv lic/ passport ipfs hash1 is for KYC process and thus owner and platform function getdataipfshash1() view onlyOwnerorplant public returns(string memory) { return dataipfshash1; } function getdataipfshash2() view onlyOwnerorplant public returns(string memory) { return dataipfshash2; } function getdataipfshash3() view onlyOwnerorplant public returns(string memory) { return dataipfshash3; } // only owner can view AND update these function getinterest1() view onlyOwnerorplantnoncore public returns(string memory) { return interest1; } function getinterest2() view onlyOwnerorplantnoncore public returns(string memory) { return interest2; } function getinterest3() view onlyOwnerorplantnoncore public returns(string memory) { return interest3; } // openness bools and slider measures to Advertisers/ sponsors function getdemographic() view onlyOwnerorplantnoncore public returns(bool) { return demographic; } function getbehavioral() view onlyOwnerorplantnoncore public returns(bool) { return behavioral; } function getinterests() view onlyOwnerorplantnoncore public returns(bool) { return interests; } function getsponsorslevel() view onlyOwnerorplantnoncore public returns(uint256) { return sponsorslevel; } function getgrpsponsorslevel() view onlyOwnerorplantnoncore public returns(uint256) { return grpsponsorslevel; } // setters // function to update permission flag for core data - access for platform, only Owner can give permissions function setplatformcorepermission(bool _permissiongiven) public onlyOwner{ platformaccess_corepermission = _permissiongiven; } // function to update permission flag for non-core data - access for platform. function setplatformnoncorepermission(bool _permissiongiven) public onlyOwner{ platformaccess_noncorepermission = _permissiongiven; } // update core profile by DApp customer ONLY ie OnlyOwner. Account info is not updatable by customer of course. // Owner cannot update the KYC images - ie ipfs has1, for example. - TBD if once KYC'd can it be updated ? or profile SHOULD be // suicided by Owner then re-created and go through new KYC process as if a new Account. function updateprofile ( string memory _fname, string memory _lname, string memory _nickname, string memory _phone, string memory _nationality, string memory _rolecode ) public onlyOwner{ fname = _fname; lname = _lname; nickname = _nickname; phone = _phone; nationality = _nationality; rolecode = _rolecode; } // used to update the profile because the profile SC contractID is stored in the Plantidote Account ie the fileID plantaccountfileid. But // the profile also is to hold the Plantidote Users account (hedera fileid).. chicken & egg. So this method below is called AFTER the FileIDcreate in the DApp function updateplanttaccountid(string memory _createplantaccountfileid) public onlyplant { plantaccountfileid = _createplantaccountfileid; } // non KYC'd - at this point only platform can update. function updateipfshash_nonkyc(string memory _ipfshash2, string memory _ipfshash3) public onlyplant { dataipfshash2 = _ipfshash2; dataipfshash3 = _ipfshash3; } function updateinterests( string memory _interest1, string memory _interest2, string memory _interest3, bool _demo, bool _behav, bool _inter, bool _platformaccess_corepermission, bool _platformaccess_noncorepermission, uint256 _sponsorslevel, uint256 _grpsponsorslevel ) public onlyOwner { interest1 = _interest1; interest2 = _interest2; interest3 = _interest3; demographic = _demo; behavioral = _behav; interests = _inter; platformaccess_corepermission = _platformaccess_corepermission; platformaccess_noncorepermission = _platformaccess_noncorepermission; sponsorslevel = _sponsorslevel; grpsponsorslevel = _grpsponsorslevel; } function removeprofile() public onlyOwner { // selfdestruct profile smart contract by the Customer-Owner of this profile ONLY. selfdestruct(payable(owner)); // test on hedera to see if the scVM impklements as orig suicide func. } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Multiplies two numbers, throws on overflow./
function updateprofile ( string memory _fname, string memory _lname, string memory _nickname, string memory _phone, string memory _nationality, string memory _rolecode } } } function updateinterests( string memory _interest1, string memory _interest2, string memory _interest3, bool _demo, bool _behav, bool _inter, bool _platformaccess_corepermission, bool _platformaccess_noncorepermission, uint256 _sponsorslevel, uint256 _grpsponsorslevel } } } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
5,524,349
./full_match/1/0x3642189B7754302DF84B6F3FE1aE34D2026647A7/sources/src/ConveyorRouterV1.sol
Function to set affiliate address.
function initializeAffiliate(address affiliateAddress) external onlyOwner { uint16 tempAffiliateNonce = affiliateNonce; affiliates[tempAffiliateNonce] = affiliateAddress; affiliateIndex[affiliateAddress] = tempAffiliateNonce; unchecked { tempAffiliateNonce++; require(tempAffiliateNonce < type(uint16).max >> 0x1, "Affiliate nonce overflow"); affiliateNonce = tempAffiliateNonce; } }
3,016,309
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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 ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and * ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with * smart contract wallets such as Argent and Gnosis. * * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change * through time. It could return true at block N and false at block N+1 (or the opposite). * * _Available since v4.1._ */ library SignatureChecker { function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // SPDX-License-Identifier: MIT 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 pragma solidity 0.8.9; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/interfaces/IERC165.sol"; abstract contract ERC721Base is IERC165, IERC721 { using Address for address; bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; bytes4 internal constant ERC165ID = 0x01ffc9a7; uint256 internal constant OPERATOR_FLAG = 0x8000000000000000000000000000000000000000000000000000000000000000; uint256 internal constant NOT_OPERATOR_FLAG = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; mapping(uint256 => uint256) internal _owners; mapping(address => uint256) internal _balances; mapping(address => mapping(address => bool)) internal _operatorsForAll; mapping(uint256 => address) internal _operators; function name() public pure virtual returns (string memory) { revert("NOT_IMPLEMENTED"); } /// @notice Approve an operator to transfer a specific token on the senders behalf. /// @param operator The address receiving the approval. /// @param id The id of the token. function approve(address operator, uint256 id) external override { (address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "UNAUTHORIZED_APPROVAL"); _approveFor(owner, blockNumber, operator, id); } /// @notice Transfer a token between 2 addresses. /// @param from The sender of the token. /// @param to The recipient of the token. /// @param id The id of the token. function transferFrom( address from, address to, uint256 id ) external override { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); require(owner == from, "NOT_OWNER"); require(to != address(0), "NOT_TO_ZEROADDRESS"); require(to != address(this), "NOT_TO_THIS"); if (msg.sender != from) { require( (operatorEnabled && _operators[id] == msg.sender) || isApprovedForAll(from, msg.sender), "UNAUTHORIZED_TRANSFER" ); } _transferFrom(from, to, id); } /// @notice Transfer a token between 2 addresses letting the receiver know of the transfer. /// @param from The send of the token. /// @param to The recipient of the token. /// @param id The id of the token. function safeTransferFrom( address from, address to, uint256 id ) external override { safeTransferFrom(from, to, id, ""); } /// @notice Set the approval for an operator to manage all the tokens of the sender. /// @param operator The address receiving the approval. /// @param approved The determination of the approval. function setApprovalForAll(address operator, bool approved) external override { _setApprovalForAll(msg.sender, operator, approved); } /// @notice Get the number of tokens owned by an address. /// @param owner The address to look for. /// @return balance The number of tokens owned by the address. function balanceOf(address owner) public view override returns (uint256 balance) { require(owner != address(0), "ZERO_ADDRESS_OWNER"); balance = _balances[owner]; } /// @notice Get the owner of a token. /// @param id The id of the token. /// @return owner The address of the token owner. function ownerOf(uint256 id) external view override returns (address owner) { owner = _ownerOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); } /// @notice Get the owner of a token and the blockNumber of the last transfer, useful to voting mechanism. /// @param id The id of the token. /// @return owner The address of the token owner. /// @return blockNumber The blocknumber at which the last transfer of that id happened. function ownerAndLastTransferBlockNumberOf(uint256 id) internal view returns (address owner, uint256 blockNumber) { return _ownerAndBlockNumberOf(id); } struct OwnerData { address owner; uint256 lastTransferBlockNumber; } /// @notice Get the list of owner of a token and the blockNumber of its last transfer, useful to voting mechanism. /// @param ids The list of token ids to check. /// @return ownersData The list of (owner, lastTransferBlockNumber) for each ids given as input. function ownerAndLastTransferBlockNumberList(uint256[] calldata ids) external view returns (OwnerData[] memory ownersData) { ownersData = new OwnerData[](ids.length); for (uint256 i = 0; i < ids.length; i++) { uint256 data = _owners[ids[i]]; ownersData[i].owner = address(uint160(data)); ownersData[i].lastTransferBlockNumber = (data >> 160) & 0xFFFFFFFFFFFFFFFFFFFFFF; } } /// @notice Get the approved operator for a specific token. /// @param id The id of the token. /// @return The address of the operator. function getApproved(uint256 id) external view override returns (address) { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); if (operatorEnabled) { return _operators[id]; } else { return address(0); } } /// @notice Check if the sender approved the operator. /// @param owner The address of the owner. /// @param operator The address of the operator. /// @return isOperator The status of the approval. function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isOperator) { return _operatorsForAll[owner][operator]; } /// @notice Transfer a token between 2 addresses letting the receiver knows of the transfer. /// @param from The sender of the token. /// @param to The recipient of the token. /// @param id The id of the token. /// @param data Additional data. function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public override { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); require(owner == from, "NOT_OWNER"); require(to != address(0), "NOT_TO_ZEROADDRESS"); require(to != address(this), "NOT_TO_THIS"); if (msg.sender != from) { require( (operatorEnabled && _operators[id] == msg.sender) || isApprovedForAll(from, msg.sender), "UNAUTHORIZED_TRANSFER" ); } _safeTransferFrom(from, to, id, data); } /// @notice Check if the contract supports an interface. /// @param id The id of the interface. /// @return Whether the interface is supported. function supportsInterface(bytes4 id) public pure virtual override returns (bool) { /// 0x01ffc9a7 is ERC165. /// 0x80ac58cd is ERC721 /// 0x5b5e139f is for ERC721 metadata return id == 0x01ffc9a7 || id == 0x80ac58cd || id == 0x5b5e139f; } function _safeTransferFrom( address from, address to, uint256 id, bytes memory data ) internal { _transferFrom(from, to, id); if (to.isContract()) { require(_checkOnERC721Received(msg.sender, from, to, id, data), "ERC721_TRANSFER_REJECTED"); } } function _beforeTokenTransfer( address from, address to, uint256 id ) internal virtual {} function _transferFrom( address from, address to, uint256 id ) internal { _beforeTokenTransfer(from, to, id); unchecked { _balances[to]++; if (from != address(0)) { _balances[from]--; } } _owners[id] = (block.number << 160) | uint256(uint160(to)); emit Transfer(from, to, id); } /// @dev See approve. function _approveFor( address owner, uint256 blockNumber, address operator, uint256 id ) internal { if (operator == address(0)) { _owners[id] = (blockNumber << 160) | uint256(uint160(owner)); } else { _owners[id] = OPERATOR_FLAG | (blockNumber << 160) | uint256(uint160(owner)); _operators[id] = operator; } emit Approval(owner, operator, id); } /// @dev See setApprovalForAll. function _setApprovalForAll( address sender, address operator, bool approved ) internal { _operatorsForAll[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /// @dev Check if receiving contract accepts erc721 transfers. /// @param operator The address of the operator. /// @param from The from address, may be different from msg.sender. /// @param to The adddress we want to transfer to. /// @param id The id of the token we would like to transfer. /// @param _data Any additional data to send with the transfer. /// @return Whether the expected value of 0x150b7a02 is returned. function _checkOnERC721Received( address operator, address from, address to, uint256 id, bytes memory _data ) internal returns (bool) { bytes4 retval = IERC721Receiver(to).onERC721Received(operator, from, id, _data); return (retval == ERC721_RECEIVED); } /// @dev See ownerOf function _ownerOf(uint256 id) internal view returns (address owner) { return address(uint160(_owners[id])); } /// @dev Get the owner and operatorEnabled status of a token. /// @param id The token to query. /// @return owner The owner of the token. /// @return operatorEnabled Whether or not operators are enabled for this token. function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) { uint256 data = _owners[id]; owner = address(uint160(data)); operatorEnabled = (data & OPERATOR_FLAG) == OPERATOR_FLAG; } // @dev Get the owner and operatorEnabled status of a token. /// @param id The token to query. /// @return owner The owner of the token. /// @return blockNumber the blockNumber at which the owner became the owner (last transfer). function _ownerAndBlockNumberOf(uint256 id) internal view returns (address owner, uint256 blockNumber) { uint256 data = _owners[id]; owner = address(uint160(data)); blockNumber = (data >> 160) & 0xFFFFFFFFFFFFFFFFFFFFFF; } // from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed. /// @dev The `msg.value` should not be trusted for any method callable from multicall. /// @param data The encoded function data for each of the calls to make to this contract. /// @return results The results from each of the calls passed in via data. function multicall(bytes[] calldata data) public payable returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721Base.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "./IERC4494.sol"; abstract contract ERC721BaseWithERC4494Permit is ERC721Base { using Address for address; bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_FOR_ALL_TYPEHASH = keccak256("PermitForAll(address spender,uint256 nonce,uint256 deadline)"); bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); uint256 private immutable _deploymentChainId; bytes32 private immutable _deploymentDomainSeparator; mapping(address => uint256) internal _userNonces; constructor() { uint256 chainId; //solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } _deploymentChainId = chainId; _deploymentDomainSeparator = _calculateDomainSeparator(chainId); } /// @dev Return the DOMAIN_SEPARATOR. function DOMAIN_SEPARATOR() external view returns (bytes32) { return _DOMAIN_SEPARATOR(); } /// @notice return the account nonce, used for approvalForAll permit or other account related matter /// @param account the account to query /// @return nonce function nonces(address account) external view virtual returns (uint256 nonce) { return _userNonces[account]; } /// @notice return the token nonce, used for individual approve permit or other token related matter /// @param id token id to query /// @return nonce function nonces(uint256 id) public view virtual returns (uint256 nonce) { (address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); return blockNumber; } /// @notice return the token nonce, used for individual approve permit or other token related matter /// @param id token id to query /// @return nonce function tokenNonces(uint256 id) external view returns (uint256 nonce) { return nonces(id); } function permit( address spender, uint256 tokenId, uint256 deadline, bytes memory sig ) external { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); (address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(tokenId); require(owner != address(0), "NONEXISTENT_TOKEN"); // We use blockNumber as nonce as we already store it per tokens. It can thus act as an increasing transfer counter. // while technically multiple transfer could happen in the same block, the signed message would be using a previous block. // And the transfer would use then a more recent blockNumber, invalidating that message when transfer is executed. _requireValidPermit(owner, spender, tokenId, deadline, blockNumber, sig); _approveFor(owner, blockNumber, spender, tokenId); } function permitForAll( address signer, address spender, uint256 deadline, bytes memory sig ) external { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); _requireValidPermitForAll(signer, spender, deadline, _userNonces[signer]++, sig); _setApprovalForAll(signer, spender, true); } /// @notice Check if the contract supports an interface. /// @param id The id of the interface. /// @return Whether the interface is supported. function supportsInterface(bytes4 id) public pure virtual override returns (bool) { return super.supportsInterface(id) || id == type(IERC4494).interfaceId || id == type(IERC4494Alternative).interfaceId; } // -------------------------------------------------------- INTERNAL -------------------------------------------------------------------- function _requireValidPermit( address signer, address spender, uint256 id, uint256 deadline, uint256 nonce, bytes memory sig ) internal view { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", _DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline)) ) ); require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE"); } function _requireValidPermitForAll( address signer, address spender, uint256 deadline, uint256 nonce, bytes memory sig ) internal view { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", _DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_FOR_ALL_TYPEHASH, spender, nonce, deadline)) ) ); require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE"); } /// @dev Return the DOMAIN_SEPARATOR. function _DOMAIN_SEPARATOR() internal view returns (bytes32) { uint256 chainId; //solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } // in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId); } /// @dev Calculate the DOMAIN_SEPARATOR. function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), chainId, address(this))); } } // SPDX-License-Identifier: BSD-3-Clause /// @title Vote checkpointing for an ERC-721 token /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ // LICENSE // ERC721Checkpointable.sol uses and modifies part of Compound Lab's Comp.sol: // https://github.com/compound-finance/compound-protocol/blob/ae4388e780a8d596d97619d9704a931a2752c2bc/contracts/Governance/Comp.sol // // Comp.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license. // With modifications by Nounders DAO. // // Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause // // MODIFICATIONS // Checkpointing logic from Comp.sol has been used with the following modifications: // - `delegates` is renamed to `_delegates` and is set to private // - `delegates` is a public function that uses the `_delegates` mapping look-up, but unlike // Comp.sol, returns the delegator's own address if there is no delegate. // This avoids the delegator needing to "delegate to self" with an additional transaction // - `_transferTokens()` is renamed `_beforeTokenTransfer()` and adapted to hook into OpenZeppelin's ERC721 hooks. pragma solidity 0.8.9; import "./ERC721BaseWithERC4494Permit.sol"; abstract contract ERC721Checkpointable is ERC721BaseWithERC4494Permit { bool internal _useCheckpoints = true; // can only be disabled and never re-enabled /// @notice Defines decimals as per ERC-20 convention to make integrations with 3rd party governance platforms easier uint8 public constant decimals = 0; /// @notice A record of each accounts delegate mapping(address => address) private _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @notice The votes a delegator can delegate, which is the current balance of the delegator. * @dev Used when calling `_delegate()` */ function votesToDelegate(address delegator) public view returns (uint96) { return safe96(balanceOf(delegator), "ERC721Checkpointable::votesToDelegate: amount exceeds 96 bits"); } /** * @notice Overrides the standard `Comp.sol` delegates mapping to return * the delegator's own address if they haven't delegated. * This avoids having to delegate to oneself. */ function delegates(address delegator) public view returns (address) { address current = _delegates[delegator]; return current == address(0) ? delegator : current; } /** * @notice Adapted from `_transferTokens()` in `Comp.sol` to update delegate votes. * @dev hooks into ERC721Base's `ERC721._transfer` */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { super._beforeTokenTransfer(from, to, tokenId); if (_useCheckpoints) { /// @notice Differs from `_transferTokens()` to use `delegates` override method to simulate auto-delegation _moveDelegates(delegates(from), delegates(to), 1); } } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { if (delegatee == address(0)) delegatee = msg.sender; return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", _DOMAIN_SEPARATOR(), keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)) ) ); // TODO support smart contract wallet via IERC721, require change in function signature to know which signer to call first address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "ERC721Checkpointable::delegateBySig: invalid signature"); require(nonce == _userNonces[signatory]++, "ERC721Checkpointable::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "ERC721Checkpointable::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) public view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getVotes(address account) external view returns (uint96) { return getCurrentVotes(account); } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "ERC721Checkpointable::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPastVotes(address account, uint256 blockNumber) external view returns (uint96) { return this.getPriorVotes(account, blockNumber); } function _delegate(address delegator, address delegatee) internal { /// @notice differs from `_delegate()` in `Comp.sol` to use `delegates` override method to simulate auto-delegation address currentDelegate = delegates(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); uint96 amount = votesToDelegate(delegator); _moveDelegates(currentDelegate, delegatee, amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "ERC721Checkpointable::_moveDelegates: amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "ERC721Checkpointable::_moveDelegates: amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32( block.number, "ERC721Checkpointable::_writeCheckpoint: block number exceeds 32 bits" ); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IERC4494 { function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Allows to retrieve current nonce for token /// @param tokenId token id /// @return current token nonce function nonces(uint256 tokenId) external view returns (uint256); /// @notice function to be called by anyone to approve `spender` using a Permit signature /// @dev Anyone can call this to approve `spender`, even a third-party /// @param spender the actor to approve /// @param tokenId the token id /// @param deadline the deadline for the permit to be used /// @param signature permit function permit( address spender, uint256 tokenId, uint256 deadline, bytes memory signature ) external; } interface IERC4494Alternative { function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Allows to retrieve current nonce for token /// @param tokenId token id /// @return current token nonce function tokenNonces(uint256 tokenId) external view returns (uint256); /// @notice function to be called by anyone to approve `spender` using a Permit signature /// @dev Anyone can call this to approve `spender`, even a third-party /// @param spender the actor to approve /// @param tokenId the token id /// @param deadline the deadline for the permit to be used /// @param signature permit function permit( address spender, uint256 tokenId, uint256 deadline, bytes memory signature ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } abstract contract WithSupportForOpenSeaProxies { address internal immutable _proxyRegistryAddress; constructor(address proxyRegistryAddress) { _proxyRegistryAddress = proxyRegistryAddress; } function _isOpenSeaProxy(address owner, address operator) internal view returns (bool) { if (_proxyRegistryAddress == address(0)) { return false; } // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress); return address(proxyRegistry.proxies(owner)) == operator; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./BleepsRoles.sol"; import "../base/ERC721Checkpointable.sol"; import "../interfaces/ITokenURI.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../base/WithSupportForOpenSeaProxies.sol"; contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles { event RoyaltySet(address receiver, uint256 royaltyPer10Thousands); event TokenURIContractSet(ITokenURI newTokenURIContract); event CheckpointingDisablerSet(address newCheckpointingDisabler); event CheckpointingDisabled(); /// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call). ITokenURI public tokenURIContract; struct Royalty { address receiver; uint96 per10Thousands; } Royalty internal _royalty; /// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system. address public checkpointingDisabler; /// @dev Create the Bleeps contract /// @param ens ENS address for the network the contract is deployed to /// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here. /// @param initialTokenURIAdmin admin able to update the tokenURI contract. /// @param initialMinterAdmin admin able to set the minter contract. /// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates. /// @param initialGuardian guardian able to immortalize rules /// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy. /// @param initialRoyaltyReceiver receiver of royalties /// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point /// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file. /// @param initialCheckpointingDisabler admin able to cancel checkpointing constructor( address ens, address initialOwner, address initialTokenURIAdmin, address initialMinterAdmin, address initialRoyaltyAdmin, address initialGuardian, address openseaProxyRegistry, address initialRoyaltyReceiver, uint96 imitialRoyaltyPer10Thousands, ITokenURI initialTokenURIContract, address initialCheckpointingDisabler ) WithSupportForOpenSeaProxies(openseaProxyRegistry) BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian) { tokenURIContract = initialTokenURIContract; emit TokenURIContractSet(initialTokenURIContract); checkpointingDisabler = initialCheckpointingDisabler; emit CheckpointingDisablerSet(initialCheckpointingDisabler); _royalty.receiver = initialRoyaltyReceiver; _royalty.per10Thousands = imitialRoyaltyPer10Thousands; emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands); } /// @notice A descriptive name for a collection of NFTs in this contract. function name() public pure override returns (string memory) { return "Bleeps"; } /// @notice An abbreviated name for NFTs in this contract. function symbol() external pure returns (string memory) { return "BLEEP"; } /// @notice Returns the Uniform Resource Identifier (URI) for the token collection. function contractURI() external view returns (string memory) { return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands); } /// @notice Returns the Uniform Resource Identifier (URI) for token `id`. function tokenURI(uint256 id) external view returns (string memory) { return tokenURIContract.tokenURI(id); } /// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`. /// @param newTokenURIContract The address of the new tokenURI contract. function setTokenURIContract(ITokenURI newTokenURIContract) external { require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED"); tokenURIContract = newTokenURIContract; emit TokenURIContractSet(newTokenURIContract); } /// @notice give the list of owners for the list of ids given. /// @param ids The list if token ids to check. /// @return addresses The list of addresses, corresponding to the list of ids. function owners(uint256[] calldata ids) external view returns (address[] memory addresses) { addresses = new address[](ids.length); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; addresses[i] = address(uint160(_owners[id])); } } /// @notice Check if the sender approved the operator. /// @param owner The address of the owner. /// @param operator The address of the operator. /// @return isOperator The status of the approval. function isApprovedForAll(address owner, address operator) public view virtual override(ERC721Base, IERC721) returns (bool isOperator) { return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator); } /// @notice Check if the contract supports an interface. /// @param id The id of the interface. /// @return Whether the interface is supported. function supportsInterface(bytes4 id) public pure virtual override(ERC721BaseWithERC4494Permit, IERC165) returns (bool) { return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard) } /// @notice Called with the sale price to determine how much royalty is owed and to whom. /// @param id - the token queried for royalty information. /// @param salePrice - the sale price of the token specified by id. /// @return receiver - address of who should be sent the royalty payment. /// @return royaltyAmount - the royalty payment amount for salePrice. function royaltyInfo(uint256 id, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) { receiver = _royalty.receiver; royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000; } /// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`. /// @param newReceiver the address that should receive the royalty proceeds. /// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver. function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external { require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED"); // require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ? _royalty.receiver = newReceiver; _royalty.per10Thousands = royaltyPer10Thousands; emit RoyaltySet(newReceiver, royaltyPer10Thousands); } /// @notice disable checkpointing overhead /// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints function disableTheUseOfCheckpoints() external { require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED"); _useCheckpoints = false; checkpointingDisabler = address(0); emit CheckpointingDisablerSet(address(0)); emit CheckpointingDisabled(); } /// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely. /// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change. function setCheckpointingDisabler(address newCheckpointingDisabler) external { require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED"); checkpointingDisabler = newCheckpointingDisabler; emit CheckpointingDisablerSet(newCheckpointingDisabler); } /// @notice mint one of bleep if not already minted. Can only be called by `minter`. /// @param id bleep id which represent a pair of (note, instrument). /// @param to address that will receive the Bleep. function mint(uint16 id, address to) external { require(msg.sender == minter, "ONLY_MINTER_ALLOWED"); require(id < 1024, "INVALID_BLEEP"); require(to != address(0), "NOT_TO_ZEROADDRESS"); require(to != address(this), "NOT_TO_THIS"); address owner = _ownerOf(id); require(owner == address(0), "ALREADY_CREATED"); _safeTransferFrom(address(0), to, id, ""); } /// @notice mint multiple bleeps if not already minted. Can only be called by `minter`. /// @param ids list of bleep id which represent each a pair of (note, instrument). /// @param tos addresses that will receive the Bleeps. (if only one, use for all) function multiMint(uint16[] calldata ids, address[] calldata tos) external { require(msg.sender == minter, "ONLY_MINTER_ALLOWED"); address to; if (tos.length == 1) { to = tos[0]; } for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; if (tos.length > 1) { to = tos[i]; } require(to != address(0), "NOT_TO_ZEROADDRESS"); require(to != address(this), "NOT_TO_THIS"); require(id < 1024, "INVALID_BLEEP"); address owner = _ownerOf(id); require(owner == address(0), "ALREADY_CREATED"); _safeTransferFrom(address(0), to, id, ""); } } /// @notice gives the note and instrument for a particular Bleep id. /// @param id bleep id which represent a pair of (note, instrument). /// @return note the note index (0 to 63) starting from C2 to D#7 /// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total). function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) { note = uint8(id & 0x3F); instrument = uint8(uint256(id >> 6) & 0x0F); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ReverseRegistrar { function setName(string memory name) external returns (bytes32); } interface ENS { function owner(bytes32 node) external view returns (address); } contract BleepsRoles { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event TokenURIAdminSet(address newTokenURIAdmin); event RoyaltyAdminSet(address newRoyaltyAdmin); event MinterAdminSet(address newMinterAdmin); event GuardianSet(address newGuardian); event MinterSet(address newMinter); bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; ENS internal immutable _ens; ///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract. address public owner; /// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed. address public tokenURIAdmin; /// @notice address allowed to set royalty parameters address public royaltyAdmin; /// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024. /// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members. address public minterAdmin; /// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic /// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore address public minter; /// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules. /// For example: the royalty setup could be frozen. address public guardian; constructor( address ens, address initialOwner, address initialTokenURIAdmin, address initialMinterAdmin, address initialRoyaltyAdmin, address initialGuardian ) { _ens = ENS(ens); owner = initialOwner; tokenURIAdmin = initialTokenURIAdmin; royaltyAdmin = initialRoyaltyAdmin; minterAdmin = initialMinterAdmin; guardian = initialGuardian; emit OwnershipTransferred(address(0), initialOwner); emit TokenURIAdminSet(initialTokenURIAdmin); emit RoyaltyAdminSet(initialRoyaltyAdmin); emit MinterAdminSet(initialMinterAdmin); emit GuardianSet(initialGuardian); } function setENSName(string memory name) external { require(msg.sender == owner, "NOT_AUTHORIZED"); ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE)); reverseRegistrar.setName(name); } function withdrawERC20(IERC20 token, address to) external { require(msg.sender == owner, "NOT_AUTHORIZED"); token.transfer(to, token.balanceOf(address(this))); } /** * @notice Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external { address oldOwner = owner; require(msg.sender == oldOwner); owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @notice set the new tokenURIAdmin that can change the tokenURI * Can only be called by the current tokenURI admin. */ function setTokenURIAdmin(address newTokenURIAdmin) external { require( msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)), "NOT_AUTHORIZED" ); tokenURIAdmin = newTokenURIAdmin; emit TokenURIAdminSet(newTokenURIAdmin); } /** * @notice set the new royaltyAdmin that can change the royalties * Can only be called by the current royalty admin. */ function setRoyaltyAdmin(address newRoyaltyAdmin) external { require( msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)), "NOT_AUTHORIZED" ); royaltyAdmin = newRoyaltyAdmin; emit RoyaltyAdminSet(newRoyaltyAdmin); } /** * @notice set the new minterAdmin that can set the minter for Bleeps * Can only be called by the current minter admin. */ function setMinterAdmin(address newMinterAdmin) external { require( msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)), "NOT_AUTHORIZED" ); minterAdmin = newMinterAdmin; emit MinterAdminSet(newMinterAdmin); } /** * @notice set the new guardian that can freeze the other admins (except owner). * Can only be called by the current guardian. */ function setGuardian(address newGuardian) external { require(msg.sender == guardian, "NOT_AUTHORIZED"); guardian = newGuardian; emit GuardianSet(newGuardian); } /** * @notice set the new minter that can mint Bleeps (up to 1024). * Can only be called by the minter admin. */ function setMinter(address newMinter) external { require(msg.sender == minterAdmin, "NOT_AUTHORIZED"); minter = newMinter; emit MinterSet(newMinter); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface ITokenURI { function tokenURI(uint256 id) external view returns (string memory); function contractURI(address receiver, uint96 per10Thousands) external view returns (string memory); }
Transfer a token between 2 addresses. from The sender of the token. to The recipient of the token. id The id of the token.
function transferFrom( address from, address to, uint256 id ) external override { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); require(owner == from, "NOT_OWNER"); require(to != address(0), "NOT_TO_ZEROADDRESS"); require(to != address(this), "NOT_TO_THIS"); if (msg.sender != from) { require( (operatorEnabled && _operators[id] == msg.sender) || isApprovedForAll(from, msg.sender), "UNAUTHORIZED_TRANSFER" ); } _transferFrom(from, to, id); }
11,834,262
//██████╗ █████╗ ██╗ █████╗ ██████╗ ██╗███╗ ██╗ //██╔══██╗██╔══██╗██║ ██╔══██╗██╔══██╗██║████╗ ██║ //██████╔╝███████║██║ ███████║██║ ██║██║██╔██╗ ██║ //██╔═══╝ ██╔══██║██║ ██╔══██║██║ ██║██║██║╚██╗██║ //██║ ██║ ██║███████╗██║ ██║██████╔╝██║██║ ╚████║ //╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝ pragma solidity ^0.7.6; pragma abicoder v2; //SPDX-License-Identifier: MIT import "./IPalLoanToken.sol"; import "./utils/ERC165.sol"; import "./utils/SafeMath.sol"; import "./utils/Strings.sol"; import "./utils/Admin.sol"; import "./IPaladinController.sol"; import "./BurnedPalLoanToken.sol"; import {Errors} from "./utils/Errors.sol"; /** @title palLoanToken contract */ /// @author Paladin contract PalLoanToken is IPalLoanToken, ERC165, Admin { using SafeMath for uint; using Strings for uint; //Storage // Token name string public name; // Token symbol string public symbol; // Token base URI string public baseURI; //Incremental index for next token ID uint256 private index; uint256 public totalSupply; // Mapping from token ID to owner address mapping(uint256 => address) private owners; // Mapping owner address to token count mapping(address => uint256) private balances; // Mapping from owner to list of owned token ID mapping(address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; // Mapping from token ID to approved address mapping(uint256 => address) private approvals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private operatorApprovals; // Paladin controller IPaladinController public controller; // Burned Token contract BurnedPalLoanToken public burnedToken; // Mapping from token ID to origin PalPool mapping(uint256 => address) private pools; // Mapping from token ID to PalLoan address mapping(uint256 => address) private loans; //Modifiers modifier controllerOnly() { //allows only the Controller and the admin to call the function require(msg.sender == admin || msg.sender == address(controller), Errors.CALLER_NOT_CONTROLLER); _; } modifier poolsOnly() { //allows only a PalPool listed in the Controller require(controller.isPalPool(msg.sender), Errors.CALLER_NOT_ALLOWED_POOL); _; } //Constructor constructor(address _controller, string memory _baseURI) { admin = msg.sender; // ERC721 parameters + storage data name = "PalLoan Token"; symbol = "PLT"; controller = IPaladinController(_controller); baseURI = _baseURI; //Create the Burned version of this ERC721 burnedToken = new BurnedPalLoanToken("burnedPalLoan Token", "bPLT"); } //Functions //Required ERC165 function function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } //URI method function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @notice Return the user balance (total number of token owned) * @param owner Address of the user * @return uint256 : number of token owned (in this contract only) */ function balanceOf(address owner) external view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return balances[owner]; } /** * @notice Return owner of the token * @param tokenId Id of the token * @return address : owner address */ function ownerOf(uint256 tokenId) public view override returns (address) { address owner = owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @notice Return the tokenId for a given owner and index * @param tokenIndex Index of the token * @return uint256 : tokenId */ function tokenOfByIndex(address owner, uint256 tokenIndex) external view override returns (uint256) { require(tokenIndex < balances[owner], "ERC721: token query out of bonds"); return ownedTokens[owner][tokenIndex]; } /** * @notice Return owner of the token, even if the token was burned * @dev Check if the given id has an owner in this contract, and then if it was burned and has an owner * @param tokenId Id of the token * @return address : address of the owner */ function allOwnerOf(uint256 tokenId) external view override returns (address) { require(tokenId < index, "ERC721: owner query for nonexistent token"); return owners[tokenId] != address(0) ? owners[tokenId] : burnedToken.ownerOf(tokenId); } /** * @notice Return the address of the palLoan for this token * @param tokenId Id of the token * @return address : address of the palLoan */ function loanOf(uint256 tokenId) external view override returns(address){ return loans[tokenId]; } /** * @notice Return the palPool that issued this token * @param tokenId Id of the token * @return address : address of the palPool */ function poolOf(uint256 tokenId) external view override returns(address){ return pools[tokenId]; } /** * @notice Return the list of all active palLoans owned by the user * @dev Find all the token owned by the user, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned active palLoans */ function loansOf(address owner) external view override returns(address[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; address[] memory result = new address[](tokenCount); for(uint256 i = 0; i < tokenCount; i++){ result[i] = loans[ownedTokens[owner][i]]; } return result; } /** * @notice Return the list of all tokens owned by the user * @dev Find all the token owned by the user * @param owner User address * @return uint256[] : list of owned tokens */ function tokensOf(address owner) external view override returns(uint256[] memory){ require(index > 0); return ownedTokens[owner]; } /** * @notice Return the list of all active palLoans owned by the user for the given palPool * @dev Find all the token owned by the user issued by the given Pool, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned active palLoans for the given palPool */ function loansOfForPool(address owner, address palPool) external view override returns(address[] memory){ require(index > 0); uint j = 0; uint256 tokenCount = balances[owner]; address[] memory result = new address[](tokenCount); for(uint256 i = 0; i < tokenCount; i++){ if(pools[ownedTokens[owner][i]] == palPool){ result[j] = loans[ownedTokens[owner][i]]; j++; } } //put the result in a new array with correct size to avoid 0x00 addresses in the return array address[] memory filteredResult = new address[](j); for(uint256 k = 0; k < j; k++){ filteredResult[k] = result[k]; } return filteredResult; } /** * @notice Return the list of all tokens owned by the user * @dev Find all the token owned by the user (in this contract and in the Burned contract) * @param owner User address * @return uint256[] : list of owned tokens */ function allTokensOf(address owner) external view override returns(uint256[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); uint256[] memory result = new uint256[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ result[i] = ownerTokens[i]; } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ result[j] = burned[j.sub(tokenCount)]; } return result; } /** * @notice Return the list of all palLoans (active and closed) owned by the user * @dev Find all the token owned by the user, and all the burned tokens owned by the user, * and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned palLoans */ function allLoansOf(address owner) external view override returns(address[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); address[] memory result = new address[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ result[i] = loans[ownerTokens[i]]; } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ result[j] = loans[burned[j.sub(tokenCount)]]; } return result; } /** * @notice Return the list of all palLoans owned by the user for the given palPool * @dev Find all the token owned by the user issued by the given Pool, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned palLoans (active & closed) for the given palPool */ function allLoansOfForPool(address owner, address palPool) external view override returns(address[] memory){ require(index > 0); uint m = 0; uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); address[] memory result = new address[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ if(pools[ownerTokens[i]] == palPool){ result[m] = loans[ownerTokens[i]]; m++; } } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ uint256 burnedId = burned[j.sub(tokenCount)]; if(pools[burnedId] == palPool){ result[m] = loans[burnedId]; m++; } } //put the result in a new array with correct size to avoid 0x00 addresses in the return array address[] memory filteredResult = new address[](m); for(uint256 k = 0; k < m; k++){ filteredResult[k] = result[k]; } return filteredResult; } /** * @notice Check if the token was burned * @param tokenId Id of the token * @return bool : true if burned */ function isBurned(uint256 tokenId) external view override returns(bool){ return burnedToken.ownerOf(tokenId) != address(0); } /** * @notice Approve the address to spend the token * @param to Address of the spender * @param tokenId Id of the token to approve */ function approve(address to, uint256 tokenId) external virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @notice Return the approved address for the token * @param tokenId Id of the token * @return address : spender's address */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return approvals[tokenId]; } /** * @notice Give the operator approval on all tokens owned by the user, or remove it by setting it to false * @param operator Address of the operator to approve * @param approved Boolean : give or remove approval */ function setApprovalForAll(address operator, bool approved) external virtual override { require(operator != msg.sender, "ERC721: approve to caller"); operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @notice Return true if the operator is approved for the given user * @param owner Amount of the owner * @param operator Address of the operator * @return bool : result */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return operatorApprovals[owner][operator]; } /** * @notice Transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function transferFrom( address from, address to, uint256 tokenId ) external virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @notice Safe transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function safeTransferFrom( address from, address to, uint256 tokenId ) external virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); require(_transfer(from, to, tokenId), "ERC721: transfer failed"); } /** * @notice Safe transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) external virtual override { _data; require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); require(_transfer(from, to, tokenId), "ERC721: transfer failed"); } /** * @notice Mint a new token to the given address * @dev Mint the new token, and list it with the given palLoan and palPool * @param to Address of the user to mint the token to * @param palPool Address of the palPool issuing the token * @param palLoan Address of the palLoan linked to the token * @return uint256 : new token Id */ function mint(address to, address palPool, address palLoan) external override poolsOnly returns(uint256){ require(palLoan != address(0), Errors.ZERO_ADDRESS); //Call the internal mint method, and get the new token Id uint256 newId = _mint(to); //Set the correct data in mappings for this token loans[newId] = palLoan; pools[newId] = palPool; //Emit the Mint Event emit NewLoanToken(palPool, to, palLoan, newId); //Return the new token Id return newId; } /** * @notice Burn the given token * @dev Burn the token, and mint the BurnedToken for this token * @param tokenId Id of the token to burn * @return bool : success */ function burn(uint256 tokenId) external override poolsOnly returns(bool){ address owner = ownerOf(tokenId); require(owner != address(0), "ERC721: token nonexistant"); //Mint the Burned version of this token burnedToken.mint(owner, tokenId); //Emit the correct event emit BurnLoanToken(pools[tokenId], owner, loans[tokenId], tokenId); //call the internal burn method return _burn(owner, tokenId); } /** * @notice Check if a token exists * @param tokenId Id of the token * @return bool : true if token exists (active or burned) */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return owners[tokenId] != address(0) || burnedToken.ownerOf(tokenId) != address(0); } /** * @notice Check if the given user is approved for the given token * @param spender Address of the user to check * @param tokenId Id of the token * @return bool : true if approved */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _addTokenToOwner(address to, uint tokenId) internal { uint ownerIndex = balances[to]; ownedTokens[to].push(tokenId); ownedTokensIndex[tokenId] = ownerIndex; balances[to] = balances[to].add(1); } function _removeTokenToOwner(address from, uint tokenId) internal { // To prevent any gap in the array, we subsitute the last token with the one to remove, // and pop the last element in the array uint256 lastTokenIndex = balances[from].sub(1); uint256 tokenIndex = ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = ownedTokens[from][lastTokenIndex]; ownedTokens[from][tokenIndex] = lastTokenId; ownedTokensIndex[lastTokenId] = tokenIndex; } delete ownedTokensIndex[tokenId]; ownedTokens[from].pop(); balances[from] = balances[from].sub(1); } /** * @notice Mint the new token * @param to Address of the user to mint the token to * @return uint : Id of the new token */ function _mint(address to) internal virtual returns(uint) { require(to != address(0), "ERC721: mint to the zero address"); //Get the new token Id, and increase the global index uint tokenId = index; index = index.add(1); totalSupply = totalSupply.add(1); //Write this token in the storage _addTokenToOwner(to, tokenId); owners[tokenId] = to; emit Transfer(address(0), to, tokenId); //Return the new token Id return tokenId; } /** * @notice Burn the given token * @param owner Address of the token owner * @param tokenId Id of the token to burn * @return bool : success */ function _burn(address owner, uint256 tokenId) internal virtual returns(bool) { //Reset the token approval _approve(address(0), tokenId); //Update data in storage totalSupply = totalSupply.sub(1); _removeTokenToOwner(owner, tokenId); owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); return true; } /** * @notice Transfer the token from the owner to the recipient * @dev Deposit underlying, and mints palToken for the user * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token * @return bool : success */ function _transfer( address from, address to, uint256 tokenId ) internal virtual returns(bool) { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); //Reset token approval _approve(address(0), tokenId); //Update storage data _removeTokenToOwner(from, tokenId); _addTokenToOwner(to, tokenId); owners[tokenId] = to; emit Transfer(from, to, tokenId); return true; } /** * @notice Approve the given address to spend the token * @param to Address to approve * @param tokenId Id of the token to approve */ function _approve(address to, uint256 tokenId) internal virtual { approvals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } //Admin functions /** * @notice Set a new Controller * @dev Loads the new Controller for the Pool * @param _newController address of the new Controller */ function setNewController(address _newController) external override controllerOnly { controller = IPaladinController(_newController); } function setNewBaseURI(string memory _newBaseURI) external override adminOnly { baseURI = _newBaseURI; } }
Return the list of all tokens owned by the user Find all the token owned by the user (in this contract and in the Burned contract) owner User address return uint256[] : list of owned tokens/
function allTokensOf(address owner) external view override returns(uint256[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); uint256[] memory result = new uint256[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ result[i] = ownerTokens[i]; } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ result[j] = burned[j.sub(tokenCount)]; } return result; }
12,938,553
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import { IJustCausePool } from './Interfaces.sol'; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; /** * @title JCDepositorERC721 * @author JustCause * This is a proof of concept starter contract for lossless donations * * Aave v3 is used to generate interest for crowdfunding * * Creates an ERC721 with info regarding each Just Cause Pool depositor * * Inherets from openzeppelin ERC721 contracts * **/ contract JCDepositorERC721 is ERC721URIStorageUpgradeable { struct Deposit { uint256 balance; uint256 timeStamp; address asset; } address jcPool; address poolTracker; //key = keccak hash of depositor, pool and asset addresses mapping (uint256 => Deposit) deposits; /** * @dev Only Master can call functions marked by this modifier. **/ modifier onlyPoolTracker(){ require(poolTracker == msg.sender, "not the owner"); _; } function initialize(address _jcPool) initializer public { __ERC721_init("JCP Contributor Token", "JCPC"); jcPool = _jcPool; poolTracker = msg.sender; } /** * @dev Creates NFT for depositor if first deposit for pool and asset * @param _tokenOwner address of depositor * @param _timeStamp timeStamp of token creation * @param _metaUri meta info uri for nft of JCP * @param _asset The address of the underlying asset of the reserve * @return tokenId unique tokenId keccak hash of depositor, pool and asset addresses **/ function addFunds( address _tokenOwner, uint256 _amount, uint256 _timeStamp, address _asset, string memory _metaUri ) public onlyPoolTracker returns (bool) { //tokenId is keccak hash of depositor, pool and asset addresses uint256 tokenId = uint256(keccak256(abi.encodePacked(_tokenOwner, jcPool, _asset))); bool firstDeposit = false; if(_exists(tokenId)){ deposits[tokenId].timeStamp = _timeStamp; deposits[tokenId].balance += _amount; } else{ deposits[tokenId] = Deposit(_amount, _timeStamp, _asset); _mint(_tokenOwner, tokenId); _setTokenURI(tokenId, _metaUri); firstDeposit = true; } return firstDeposit; } /** * @dev Withdraw balance for depositor * @param _tokenOwner address of depositor * @param _amount amount to withdraw * @param _asset The address of the underlying asset of the reserve **/ function withdrawFunds(address _tokenOwner, uint256 _amount, address _asset) onlyPoolTracker external{ uint256 tokenId = uint256(keccak256(abi.encodePacked(_tokenOwner, jcPool, _asset))); require(_exists(tokenId), "tokenId doesn't exist"); uint256 balance = deposits[tokenId].balance; require(balance >= _amount, "insufficient balance"); balance -= _amount; if(balance == 0){ deposits[tokenId].timeStamp = 0; } deposits[tokenId].balance = balance; } /** * @param _tokenId unique tokenId keccak hash of depositor, pool and asset addresses * @return Deposit struct containing info about deposit **/ function getDepositInfo(uint256 _tokenId) public view returns (Deposit memory){ return deposits[_tokenId]; } /** * @param _tokenId unique tokenId keccak hash of depositor, pool and asset addresses * @return asset balance of user in pool **/ function getUserBalance(uint256 _tokenId) public view returns (uint256){ return deposits[_tokenId].balance; } function getUserTokens(address _tokenOwner) external view returns(uint256[] memory){ address[] memory assets = IJustCausePool(jcPool).getAcceptedTokens(); uint256 len = assets.length; uint256[] memory ids = new uint256[](len); for(uint256 i = 0; i < len; i++){ uint256 tokenId = uint256(keccak256(abi.encodePacked(_tokenOwner, jcPool, assets[i]))); if(_exists(tokenId)){ ids[i] = tokenId; //counter = counter + 1; } } return ids; } function getPool() public view returns(address){ return jcPool; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721Upgradeable) { require(from == address(0), "non-transferrable"); super._beforeTokenTransfer(from, to, tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } }
_tokenId unique tokenId keccak hash of depositor, pool and asset addresses return asset balance of user in pool/
function getUserBalance(uint256 _tokenId) public view returns (uint256){ return deposits[_tokenId].balance; }
1,758,682
/** *Submitted for verification at Etherscan.io on 2021-05-13 */ // Southparkcoins ICO // Version of compiler pragma solidity ^0.4.11; // SPDX-License-Identifier: unlicensed contract Southparkcoins { // Introducing the maximum number of Southparkcoins available for sale uint public max_southparkcoins = 9000000000000; // Introducing the USD to Southparkcoins conversion rate uint public usd_to_southparkcoins = 1; // Introducing the total number of Southparkcoins that have been bought by the investors uint public total_southparkcoins_bought = 0; //Mapping from the investor address to its equity in Southparkcoins and usd_to_southparkcoins mapping(address => uint) equity_southparkcoins; mapping(address => uint) equity_usd; // Checking if an investor can buy Southparkcoins modifier can_buy_southparkcoins(uint usd_invested) { require (usd_invested * usd_to_southparkcoins + total_southparkcoins_bought <= max_southparkcoins); _; } // Getting the equity in southparkcoins of an investor function equity_in_southparkcoins(address investor) external constant returns (uint) { return equity_southparkcoins[investor]; } // Getting the equity_in_southparkcoins in USD of an investor function equity_in_usd(address investor) external constant returns (uint) { return equity_usd[investor]; } // Buying southparkcoins function buy_southparkcoins(address investor, uint usd_invested) external can_buy_southparkcoins(usd_invested) { uint southparkcoins_bought = usd_invested * usd_to_southparkcoins; equity_southparkcoins[investor] += southparkcoins_bought; equity_usd[investor] = equity_southparkcoins[investor] / 1 ; total_southparkcoins_bought += southparkcoins_bought; } // Selling Southparkcoins function sell_southparkcoins(address investor, uint southparkcoins_sold) external { equity_southparkcoins[investor] -= southparkcoins_sold; equity_usd[investor] = equity_southparkcoins[investor] / 1; total_southparkcoins_bought -= southparkcoins_sold; } }
Getting the equity_in_southparkcoins in USD of an investor
function equity_in_usd(address investor) external constant returns (uint) { return equity_usd[investor]; }
7,984,179
./full_match/1/0xBe9064ec3331F7Fc9E10DD9074Cc23C411E7EE00/sources/contracts/MothValley.sol
Both safeTransferFrom functions in ERC721A call this function so we don't need to override them./
function transferFrom( address from, address to, uint256 tokenId ) public payable override(IERC721A, ERC721A) onlyAllowedOperator(from) { super.transferFrom(from, to, tokenId); }
9,702,309
./full_match/1/0xD9909a6fAb1260a352fBB010D058698b5DeeA018/sources/contracts/Satoshigoat.sol
Determine if an address is a smart contract This method relies on `extcodesize`, which returns 0 for contracts in construction, since the code is only stored at the end of the constructor execution.
function _isContract(address a) internal view returns (bool) { uint32 size; assembly { size := extcodesize(a) } return size > 0; }
9,664,684
contract CAVAsset { function __transferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool); function __approve(address _spender, uint _value, address _sender) returns(bool); function __process(bytes _data, address _sender) payable { revert(); } } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function decimals() constant returns (uint8); function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } contract CAVPlatform { mapping(bytes32 => address) public proxies; function symbols(uint _idx) public constant returns (bytes32); function symbolsCount() public constant returns (uint); function name(bytes32 _symbol) returns(string); function setProxy(address _address, bytes32 _symbol) returns(uint errorCode); function isCreated(bytes32 _symbol) constant returns(bool); function isOwner(address _owner, bytes32 _symbol) returns(bool); function owner(bytes32 _symbol) constant returns(address); function totalSupply(bytes32 _symbol) returns(uint); function balanceOf(address _holder, bytes32 _symbol) returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) returns(uint); function baseUnit(bytes32 _symbol) returns(uint8); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) returns(uint errorCode); function revokeAsset(bytes32 _symbol, uint _value) returns(uint errorCode); function isReissuable(bytes32 _symbol) returns(bool); function changeOwnership(bytes32 _symbol, address _newOwner) returns(uint errorCode); function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool); } contract CAVAssetProxy is ERC20 { // Supports CAVPlatform ability to return error codes from methods uint constant OK = 1; // Assigned platform, immutable. CAVPlatform public platform; // Assigned symbol, immutable. bytes32 public smbl; // Assigned name, immutable. string public name; string public symbol; /** * Sets platform address, assigns symbol and name. * * Can be set only once. * * @param _platform platform contract address. * @param _symbol assigned symbol. * @param _name assigned name. * * @return success. */ function init(CAVPlatform _platform, string _symbol, string _name) returns(bool) { if (address(platform) != 0x0) { return false; } platform = _platform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /** * Only platform is allowed to call. */ modifier onlyPlatform() { if (msg.sender == address(platform)) { _; } } /** * Only current asset owner is allowed to call. */ modifier onlyAssetOwner() { if (platform.isOwner(msg.sender, smbl)) { _; } } /** * Returns asset implementation contract for current caller. * * @return asset implementation contract. */ function _getAsset() internal returns(CAVAsset) { return CAVAsset(getVersionFor(msg.sender)); } /** * Returns asset total supply. * * @return asset total supply. */ function totalSupply() constant returns(uint) { return platform.totalSupply(smbl); } /** * Returns asset balance for a particular holder. * * @param _owner holder address. * * @return holder balance. */ function balanceOf(address _owner) constant returns(uint) { return platform.balanceOf(_owner, smbl); } /** * Returns asset allowance from one holder to another. * * @param _from holder that allowed spending. * @param _spender holder that is allowed to spend. * * @return holder to spender allowance. */ function allowance(address _from, address _spender) constant returns(uint) { return platform.allowance(_from, _spender, smbl); } /** * Returns asset decimals. * * @return asset decimals. */ function decimals() constant returns(uint8) { return platform.baseUnit(smbl); } /** * Transfers asset balance from the caller to specified receiver. * * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transfer(address _to, uint _value) returns(bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } else { return false; } } /** * Transfers asset balance from the caller to specified receiver adding specified comment. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * * @return success. */ function transferWithReference(address _to, uint _value, string _reference) returns(bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } else { return false; } } /** * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @return success. */ function _transferWithReference(address _to, uint _value, string _reference) internal returns(bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /** * Performs transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * @param _sender initial caller. * * @return success. */ function __transferWithReference(address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /** * Prforms allowance transfer of asset balance between holders. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transferFrom(address _from, address _to, uint _value) returns(bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } else { return false; } } /** * Performs allowance transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * @param _sender initial caller. * * @return success. */ function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /** * Sets asset spending allowance for a specified spender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * * @return success. */ function approve(address _spender, uint _value) returns(bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } else { return false; } } /** * Performs allowance setting call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * @param _sender initial caller. * * @return success. */ function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) returns(bool) { return platform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /** * Emits ERC20 Transfer event on this contract. * * Can only be, and, called by assigned platform when asset transfer happens. */ function emitTransfer(address _from, address _to, uint _value) onlyPlatform() { Transfer(_from, _to, _value); } /** * Emits ERC20 Approval event on this contract. * * Can only be, and, called by assigned platform when asset allowance set happens. */ function emitApprove(address _from, address _spender, uint _value) onlyPlatform() { Approval(_from, _spender, _value); } /** * Resolves asset implementation contract for the caller and forwards there transaction data, * along with the value. This allows for proxy interface growth. */ function () payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /** * Indicates an upgrade freeze-time start, and the next asset implementation contract. */ event UpgradeProposal(address newVersion); // Current asset implementation contract address. address latestVersion; // Proposed next asset implementation contract address. address pendingVersion; // Upgrade freeze-time start. uint pendingVersionTimestamp; // Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; // Asset implementation contract address that user decided to stick with. // 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /** * Only asset implementation contract assigned to sender is allowed to call. */ modifier onlyAccess(address _sender) { if (getVersionFor(_sender) == msg.sender) { _; } } /** * Returns asset implementation contract address assigned to sender. * * @param _sender sender address. * * @return asset implementation contract address. */ function getVersionFor(address _sender) constant returns(address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /** * Returns current asset implementation contract address. * * @return asset implementation contract address. */ function getLatestVersion() constant returns(address) { return latestVersion; } /** * Returns proposed next asset implementation contract address. * * @return asset implementation contract address. */ function getPendingVersion() constant returns(address) { return pendingVersion; } /** * Returns upgrade freeze-time start. * * @return freeze-time start. */ function getPendingVersionTimestamp() constant returns(uint) { return pendingVersionTimestamp; } /** * Propose next asset implementation contract address. * * Can only be called by current asset owner. * * Note: freeze-time should not be applied for the initial setup. * * @param _newVersion asset implementation contract address. * * @return success. */ function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; UpgradeProposal(_newVersion); return true; } /** * Cancel the pending upgrade process. * * Can only be called by current asset owner. * * @return success. */ function purgeUpgrade() onlyAssetOwner() returns(bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Finalize an upgrade process setting new asset implementation contract address. * * Can only be called after an upgrade freeze-time. * * @return success. */ function commitUpgrade() returns(bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Disagree with proposed upgrade, and stick with current asset implementation * until further explicit agreement to upgrade. * * @return success. */ function optOut() returns(bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /** * Implicitly agree to upgrade to current and future asset implementation upgrades, * until further explicit disagreement. * * @return success. */ function optIn() returns(bool) { delete userOptOutVersion[msg.sender]; return true; } }
Returns asset total supply. return asset total supply./
function totalSupply() constant returns(uint) { return platform.totalSupply(smbl); }
1,488,210
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================== CrossChainCanonical ======================= // ==================================================================== // Cross-chain / non mainnet canonical token contract. // Can accept any number of old non-canonical tokens. These will be // withdrawable by the owner so they can de-bridge it and get back mainnet 'real' tokens // Does not include any spurious mainnet logic // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Dennis: github.com/denett import "../ERC20.sol"; import "../ERC20Permit/ERC20Permit.sol"; import '../../Uniswap/TransferHelper.sol'; import "../../Staking/Owned.sol"; import "../../Utils/ReentrancyGuard.sol"; contract CrossChainCanonical is ERC20Permit, Owned, ReentrancyGuard { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // Core address public timelock_address; // Governance timelock address address public custodian_address; // Misc uint256 public mint_cap; mapping(address => uint256[2]) public swap_fees; mapping(address => bool) public fee_exempt_list; // Acceptable old tokens address[] public bridge_tokens_array; mapping(address => bool) public bridge_tokens; // The addresses in this array are able to mint tokens address[] public minters_array; mapping(address => bool) public minters; // Mapping is also used for faster verification // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // Administrative booleans bool public exchangesPaused; // Pause old token exchanges in case of an emergency mapping(address => bool) public canSwap; /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyMinters() { require(minters[msg.sender], "Not a minter"); _; } modifier onlyMintersOwnGov() { require(_isMinterOwnGov(msg.sender), "Not minter, owner, or tlck"); _; } modifier validBridgeToken(address token_address) { require(bridge_tokens[token_address], "Invalid old token"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( string memory _name, string memory _symbol, address _creator_address, uint256 _initial_mint_amt, address _custodian_address, address[] memory _bridge_tokens ) ERC20(_name, _symbol) ERC20Permit(_name) Owned(_creator_address) { custodian_address = _custodian_address; // Initialize the starting old tokens for (uint256 i = 0; i < _bridge_tokens.length; i++){ // Mark as accepted bridge_tokens[_bridge_tokens[i]] = true; // Add to the array bridge_tokens_array.push(_bridge_tokens[i]); // Set a small swap fee initially of 0.04% swap_fees[_bridge_tokens[i]] = [400, 400]; // Make sure swapping is on canSwap[_bridge_tokens[i]] = true; } // Set the mint cap to the initial mint amount mint_cap = _initial_mint_amt; // Mint some canonical tokens to the creator super._mint(_creator_address, _initial_mint_amt); } /* ========== VIEWS ========== */ // Helpful for UIs function allBridgeTokens() external view returns (address[] memory) { return bridge_tokens_array; } function _isMinterOwnGov(address the_address) internal view returns (bool) { return (the_address == timelock_address || the_address == owner || minters[the_address]); } function _isFeeExempt(address the_address) internal view returns (bool) { return (_isMinterOwnGov(the_address) || fee_exempt_list[the_address]); } /* ========== INTERNAL FUNCTIONS ========== */ // Enforce a minting cap function _mint_capped(address account, uint256 amount) internal { require(totalSupply() + amount <= mint_cap, "Mint cap"); super._mint(account, amount); } /* ========== PUBLIC FUNCTIONS ========== */ // Exchange old or bridge tokens for these canonical tokens function exchangeOldForCanonical(address bridge_token_address, uint256 token_amount) external nonReentrant validBridgeToken(bridge_token_address) returns (uint256 canonical_tokens_out) { require(!exchangesPaused && canSwap[bridge_token_address], "Exchanges paused"); // Pull in the old / bridge tokens TransferHelper.safeTransferFrom(bridge_token_address, msg.sender, address(this), token_amount); // Handle the fee, if applicable canonical_tokens_out = token_amount; if (!_isFeeExempt(msg.sender)) { canonical_tokens_out -= ((canonical_tokens_out * swap_fees[bridge_token_address][0]) / PRICE_PRECISION); } // Mint canonical tokens and give it to the sender _mint_capped(msg.sender, canonical_tokens_out); } // Exchange canonical tokens for old or bridge tokens function exchangeCanonicalForOld(address bridge_token_address, uint256 token_amount) external nonReentrant validBridgeToken(bridge_token_address) returns (uint256 bridge_tokens_out) { require(!exchangesPaused && canSwap[bridge_token_address], "Exchanges paused"); // Burn the canonical tokens super._burn(msg.sender, token_amount); // Handle the fee, if applicable bridge_tokens_out = token_amount; if (!_isFeeExempt(msg.sender)) { bridge_tokens_out -= ((bridge_tokens_out * swap_fees[bridge_token_address][1]) / PRICE_PRECISION); } // Give old / bridge tokens to the sender TransferHelper.safeTransfer(bridge_token_address, msg.sender, bridge_tokens_out); } /* ========== MINTERS OR GOVERNANCE FUNCTIONS ========== */ // Collect old / bridge tokens so you can de-bridge them back on mainnet function withdrawBridgeTokens(address bridge_token_address, uint256 bridge_token_amount) external onlyMintersOwnGov validBridgeToken(bridge_token_address) { TransferHelper.safeTransfer(bridge_token_address, msg.sender, bridge_token_amount); } /* ========== MINTERS ONLY ========== */ // This function is what other minters will call to mint new tokens function minter_mint(address m_address, uint256 m_amount) external onlyMinters { _mint_capped(m_address, m_amount); emit TokenMinted(msg.sender, m_address, m_amount); } // This function is what other minters will call to burn tokens function minter_burn(uint256 amount) external onlyMinters { super._burn(msg.sender, amount); emit TokenBurned(msg.sender, amount); } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL TOO ========== */ function toggleExchanges() external onlyByOwnGovCust { exchangesPaused = !exchangesPaused; } /* ========== RESTRICTED FUNCTIONS ========== */ function addBridgeToken(address bridge_token_address) external onlyByOwnGov { // Make sure the token is not already present for (uint i = 0; i < bridge_tokens_array.length; i++){ if (bridge_tokens_array[i] == bridge_token_address){ revert("Token already present"); } } // Add the old token bridge_tokens[bridge_token_address] = true; bridge_tokens_array.push(bridge_token_address); // Turn swapping on canSwap[bridge_token_address] = true; emit BridgeTokenAdded(bridge_token_address); } function toggleBridgeToken(address bridge_token_address) external onlyByOwnGov { bridge_tokens[bridge_token_address] = !bridge_tokens[bridge_token_address]; // Toggle swapping canSwap[bridge_token_address] = !canSwap[bridge_token_address]; emit BridgeTokenToggled(bridge_token_address, !bridge_tokens[bridge_token_address]); } // Adds a minter address function addMinter(address minter_address) external onlyByOwnGov { require(minter_address != address(0), "Zero address detected"); require(minters[minter_address] == false, "Address already exists"); minters[minter_address] = true; minters_array.push(minter_address); emit MinterAdded(minter_address); } // Remove a minter function removeMinter(address minter_address) external onlyByOwnGov { require(minter_address != address(0), "Zero address detected"); require(minters[minter_address] == true, "Address nonexistant"); // Delete from the mapping delete minters[minter_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < minters_array.length; i++){ if (minters_array[i] == minter_address) { minters_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit MinterRemoved(minter_address); } function setMintCap(uint256 _mint_cap) external onlyByOwnGov { mint_cap = _mint_cap; emit MintCapSet(_mint_cap); } function setSwapFees(address bridge_token_address, uint256 _bridge_to_canonical, uint256 _canonical_to_old) external onlyByOwnGov { swap_fees[bridge_token_address] = [_bridge_to_canonical, _canonical_to_old]; } function toggleFeesForAddress(address the_address) external onlyByOwnGov { fee_exempt_list[the_address] = !fee_exempt_list[the_address]; } function setTimelock(address new_timelock) external onlyByOwnGov { require(new_timelock != address(0), "Zero address detected"); timelock_address = new_timelock; emit TimelockSet(new_timelock); } function setCustodian(address _custodian_address) external onlyByOwnGov { require(_custodian_address != address(0), "Zero address detected"); custodian_address = _custodian_address; emit CustodianSet(_custodian_address); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { require(!bridge_tokens[tokenAddress], "Cannot withdraw bridge tokens"); require(tokenAddress != address(this), "Cannot withdraw these tokens"); TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount); } // // Generic proxy // function execute( // address _to, // uint256 _value, // bytes calldata _data // ) external onlyByOwnGov returns (bool, bytes memory) { // (bool success, bytes memory result) = _to.call{value:_value}(_data); // return (success, result); // } /* ========== EVENTS ========== */ event TokenBurned(address indexed from, uint256 amount); event TokenMinted(address indexed from, address indexed to, uint256 amount); event BridgeTokenAdded(address indexed bridge_token_address); event BridgeTokenToggled(address indexed bridge_token_address, bool state); event CollateralRatioRefreshed(uint256 global_collateral_ratio); event MinterAdded(address pool_address); event MinterRemoved(address pool_address); event MintCapSet(uint256 new_mint_cap); event TimelockSet(address new_timelock); event CustodianSet(address custodian_address); }
Exchange old or bridge tokens for these canonical tokens Pull in the old / bridge tokens Handle the fee, if applicable
function exchangeOldForCanonical(address bridge_token_address, uint256 token_amount) external nonReentrant validBridgeToken(bridge_token_address) returns (uint256 canonical_tokens_out) { require(!exchangesPaused && canSwap[bridge_token_address], "Exchanges paused"); TransferHelper.safeTransferFrom(bridge_token_address, msg.sender, address(this), token_amount); canonical_tokens_out = token_amount; if (!_isFeeExempt(msg.sender)) { canonical_tokens_out -= ((canonical_tokens_out * swap_fees[bridge_token_address][0]) / PRICE_PRECISION); } }
1,090,348
./partial_match/4/0x30baa3Be1FFa7ed91ce4b492f4aD79cB030eD0B8/sources/DummyOracle.sol
Underlying asset for this CToken/ Construct a new money market underlying_ The address of the underlying asset comptroller_ The address of the Comptroller interestRateModel_ The address of the interest rate model initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 name_ ERC-20 name of this token symbol_ ERC-20 symbol of this token decimals_ ERC-20 decimal precision of this token/ Set underlying
function getCashPrior() internal view returns (uint); function checkTransferIn(address from, uint amount) internal view returns (Error); function doTransferIn(address from, uint amount) internal returns (Error); function doTransferOut(address payable to, uint amount) internal returns (Error); } CToken(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_) { underlying = underlying_; }
8,729,781
./partial_match/1/0x4dDC0C08A6d2724389051E60B2DB761BF7417D52/sources/MGGStaking.sol
Return block rewards over the given _from (inclusive) to _to (inclusive) block.
function getBlockReward(uint256 _from, uint256 _to) public view returns (uint256) { uint256 to = _to; uint256 from = _from; if (from > to) { return 0; } uint256 rewardPerBlock = mggRewardRate; uint256 totalRewards = (to.sub(from)).mul(rewardPerBlock); return totalRewards; }
2,638,180
// SPDX-License-Identifier: No License (None) 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.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { struct AddressSet { // Storage of set values address[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (address => 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(AddressSet storage set, address value) internal 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(AddressSet storage set, address value) internal 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; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. address 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] = toDeleteIndex + 1; // All indexes are 1-based // 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(AddressSet storage set, address value) internal view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(AddressSet storage set) internal 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(AddressSet storage set, uint256 index) internal view returns (address) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } } abstract contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ /* we use proxy, so owner will be set in initialize() function constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } */ function initialize() external { require(_owner == address(0), "Already initialized"); _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IBEP20 { function mint(address to, uint256 amount) external; function balanceOf(address account) external view returns (uint256); } interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns (address); function token1() external view returns (address); } contract TokenVault { address public owner; address public reimbursementToken; address public factory; constructor(address _owner,address _token) { owner = _owner; reimbursementToken = _token; factory = msg.sender; } function transferToken(address to, uint256 amount) external { require(msg.sender == factory,"caller should be factory"); safeTransfer(reimbursementToken, to, amount); } // vault owner can withdraw unreserved tokens function withdrawTokens(uint256 amount) external { require(msg.sender == owner, "caller should be owner"); uint256 available = Reimbursement(factory).getAvailableTokens(address(this)); require(available >= amount, "not enough available tokens"); safeTransfer(reimbursementToken, msg.sender, amount); } // allow owner to withdraw third-party tokens from contract address function rescueTokens(address someToken) external { require(msg.sender == owner, "caller should be owner"); require(someToken != reimbursementToken, "Only third-party token"); uint256 available = IBEP20(someToken).balanceOf(address(this)); safeTransfer(someToken, msg.sender, available); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } } contract Reimbursement is Ownable { using EnumerableSet for EnumerableSet.AddressSet; struct Stake { uint256 startTime; // stake start at timestamp uint256 amount; // staked tokens amount } struct Setting { address token; // reimbursement token bool isMintable; // token can be minted by this contract address owner; // owner of reimbursement vault uint64 period; // staking period in seconds (365 days) uint32 reimbursementRatio; // the ratio of deposited amount to reimbursement amount (with 2 decimals) IUniswapV2Pair swapPair; // uniswap compatible pair for token and native coin (ETH, BNB) bool isReversOrder; // if `true` then `token1 = token` otherwise `token0 = token` } mapping(address => Setting) public settings; // vault address (licensee address) => setting mapping(address => uint256) public totalReserved; // vault address (licensee address) => total amount used for reimbursement mapping(address => mapping(address => uint256)) public balances; // vault address => user address => eligible reimbursement balance mapping(address => mapping(address => Stake)) public staking; // vault address => user address => Stake mapping(address => EnumerableSet.AddressSet) vaults; // user address => licensee address list that user mat get reimbursement mapping(address => mapping(address => uint256)) licenseeFees; // vault => contract => fee (with 2 decimals). I.e. 30 means 0.3% mapping(address => EnumerableSet.AddressSet) licenseeVaults; // licensee address => list of vaults event StakeToken(address indexed vault, address indexed user, uint256 date, uint256 amount); event UnstakeToken(address indexed vault, address indexed user, uint256 date, uint256 amount); event SetLicenseeFee(address indexed vault, address indexed projectContract, uint256 fee); event VaultCreated(address indexed vault, address indexed owner, address indexed token); event SetVaultOwner(address indexed vault, address indexed oldOwner, address indexed newOwner); // set percentage of fee (with 2 decimals) by licensee for selected `projectContract` function setLicenseeFee(address vault, address projectContract, uint256 fee) external { require(settings[vault].owner == msg.sender, "Only vault owner"); licenseeFees[vault][projectContract] = fee; emit SetLicenseeFee(vault, projectContract, fee); } // get percentage of fee (with 2 decimals) set by licensee for selected `projectContract` function getLicenseeFee(address vault, address projectContract) external view returns(uint256 fee) { return licenseeFees[vault][projectContract]; } // get list of licensee vaults addresses belong to licensee function getLicenseeVaults(address licensee) external view returns(address[] memory vault) { return licenseeVaults[licensee]._values; } // get list of vault addresses where user has tokens. function getVaults(address user) external view returns(address[] memory vault) { return vaults[user]._values; } // get numbers of vault where user has tokens. function getVaultsLength(address user) external view returns(uint256) { return vaults[user].length(); } // get vault address by index function getVault(address user, uint256 index) external view returns(address) { return vaults[user].at(index); } // Get vault owner function getVaultOwner(address vault) external view returns(address) { return settings[vault].owner; } // change vault owner. Only current owner can call it. function setVaultOwner(address vault, address newOwner) external { require(msg.sender == settings[vault].owner, "caller should be owner"); require(newOwner != address(0), "Wrong new owner address"); emit SetVaultOwner(vault, settings[vault].owner, newOwner); settings[vault].owner = newOwner; } // get list of vault and balance where user can get reimbursement function getVaultsBalance(address user) external view returns(address[] memory vault, uint256[] memory balance) { vault = vaults[user]._values; balance = new uint256[](vault.length); for (uint i = 0; i < vault.length; i++) { balance[i] = balances[vault[i]][user]; } } // get available (not reserved) tokens amount in vault function getAvailableTokens(address vault) public view returns(uint256 available) { available = IBEP20(settings[vault].token).balanceOf(vault) - totalReserved[vault]; } // vault owner can withdraw unreserved tokens function withdrawTokens(address vault, uint256 amount) external { require(msg.sender == settings[vault].owner, "caller should be owner"); uint256 available = getAvailableTokens(vault); require(available >= amount, "not enough available tokens"); TokenVault(vault).transferToken(msg.sender, amount); } // Stake `amount` of token to `vault` to receive reimbursement function stake(address vault, uint256 amount) external { uint256 balance = balances[vault][msg.sender]; require(balance != 0, "No tokens for reimbursement"); Stake storage s = staking[vault][msg.sender]; uint256 currentStake = s.amount; safeTransferFrom(settings[vault].token, msg.sender, vault, amount); totalReserved[vault] += amount; if (currentStake != 0) { // recalculate time due new amount: old interval * old amount = new interval * new amount uint256 interval = block.timestamp - s.startTime; interval = interval * currentStake / (currentStake + amount); s.startTime = block.timestamp - interval; s.amount = currentStake + amount; } else { s.startTime = block.timestamp; s.amount = amount; } emit StakeToken(vault, msg.sender, block.timestamp, amount); } // Withdraw staked tokens + reward from vault. function unstake(address vault) external { Stake memory s = staking[vault][msg.sender]; Setting memory set = settings[vault]; uint256 amount; uint256 balance = balances[vault][msg.sender]; if (set.period == 0) { require(balance != 0, "No reimbursement"); amount = balance; } else { require(s.amount != 0, "No stake"); uint256 interval = block.timestamp - s.startTime; amount = s.amount * 100 * interval / (set.period * set.reimbursementRatio); } delete staking[vault][msg.sender]; // remove staking record. if (amount > balance) amount = balance; balance -= amount; balances[vault][msg.sender] = balance; if (balance == 0) { vaults[msg.sender].remove(vault); // remove vault from vaults list where user has reimbursement tokens } if (set.isMintable) { totalReserved[vault] -= s.amount; TokenVault(vault).transferToken(msg.sender, s.amount); // withdraw staked amount IBEP20(set.token).mint(msg.sender, amount); // mint reimbursement token amount += s.amount; // total amount: rewards + staking } else { amount += s.amount; // total amount: rewards + staking totalReserved[vault] -= amount; TokenVault(vault).transferToken(msg.sender, amount); // withdraw staked amount + rewards } emit UnstakeToken(vault, msg.sender, block.timestamp, amount); } // get information about user's fee // address user - address of user whp paid the fee // uint256 feeAmount - amount of fee in native coin (ETH, BNB) // address vault - licensee vault address that licensee get after registration. Use it as Licensee ID. // returns address of fee receiver or address(0) if licensee can't receive the fee (should be returns to user) function requestReimbursement(address user, uint256 feeAmount, address vault) external returns(address licenseeAddress){ uint256 licenseeFee = licenseeFees[vault][msg.sender]; if (licenseeFee == 0) return address(0); // project contract not added to reimbursement Setting memory set = settings[vault]; (uint256 reserve0, uint256 reserve1,) = set.swapPair.getReserves(); if (set.isReversOrder) (reserve0, reserve1) = (reserve1, reserve0); uint256 amount = reserve0 * feeAmount / reserve1; if (!set.isMintable) { uint256 reserve = totalReserved[vault]; uint256 available = IBEP20(set.token).balanceOf(vault) - reserve; if (available < amount) return address(0); // not enough reimbursement tokens totalReserved[vault] = reserve + amount; } uint256 balance = balances[vault][user]; if (balance == 0) vaults[user].add(vault); balances[vault][user] = balance + amount; return set.owner; } // create new vault (register Licensee) function newVault( address token, // reimbursement token bool isMintable, // token can be minted by this contract uint64 period, // staking period in seconds (365 days) uint32 reimbursementRatio, // the ratio of deposited amount to reimbursement amount (with 2 decimals). address swapPair, // uniswap compatible pair for token and native coin (ETH, BNB) uint32[] memory licenseeFee, // percentage of Licensee fee (with 2 decimals). I.e. 30 means 0.3% address[] memory projectContract // contract that has right to request reimbursement ) external returns(address vault) // vault - is the vault contract address where project has to transfer tokens. A licensee has to use it as Licensee ID. { if (isMintable) { require(msg.sender == owner(), "Only owner may add mintable token"); } bool isReversOrder; if (IUniswapV2Pair(swapPair).token1() == token) { isReversOrder == true; } else { require(IUniswapV2Pair(swapPair).token0() == token, "Wrong swap pair"); } vault = address(new TokenVault(msg.sender, token)); licenseeVaults[msg.sender].add(vault); settings[vault] = Setting(token, isMintable, msg.sender, period, reimbursementRatio, IUniswapV2Pair(swapPair), isReversOrder); require(licenseeFee.length == projectContract.length, "Wrong length"); for (uint i = 0; i < projectContract.length; i++) { require(licenseeFee[i] <= 10000, "Wrong fee"); licenseeFees[vault][projectContract[i]] = licenseeFee[i]; emit SetLicenseeFee(vault, projectContract[i], licenseeFee[i]); } emit VaultCreated(vault, msg.sender, token); } // This contract should not received any tokens, but due issue in ERC20 standard we can't disallow someone to do it. // If someone accidentally transfer tokens to this contract, the owner will be able to rescue it and refund sender. function rescueTokens(address someToken) external onlyOwner { uint256 available = IBEP20(someToken).balanceOf(address(this)); safeTransfer(someToken, msg.sender, available); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } }
Returns true if the value is in the set. O(1)./
function contains(AddressSet storage set, address value) internal view returns (bool) { return set._indexes[value] != 0; }
329,081
pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT import "../../core/DaoConstants.sol"; import "../../core/DaoRegistry.sol"; import "../../guards/AdapterGuard.sol"; import "../IExtension.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** MIT License Copyright (c) 2020 Openlaw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract NFTExtension is DaoConstants, AdapterGuard, IExtension, IERC721Receiver { using Address for address payable; // Add the library methods using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern DaoRegistry public dao; address private _creator; enum AclFlag {TRANSFER_NFT, RETURN_NFT, REGISTER_NFT} // All the NFTs and Token ids that belong to the GUILD mapping(address => mapping(address => EnumerableSet.UintSet)) private _nftCollection; // All the NFTs addresses collected and stored in the GUILD collection EnumerableSet.AddressSet private _collectedNFTs; // The NFTs addresses supported by the extension mapping(address => bool) public availableNFTs; modifier hasExtensionAccess(IExtension extension, AclFlag flag) { require( dao.state() == DaoRegistry.DaoState.CREATION || dao.hasAdapterAccessToExtension( msg.sender, address(extension), uint8(flag) ), "nft::accessDenied" ); _; } modifier isCreatorOrHasExtensionAccess(IExtension extension, AclFlag flag) { require( msg.sender == _creator || dao.state() == DaoRegistry.DaoState.CREATION || dao.hasAdapterAccessToExtension( msg.sender, address(extension), uint8(flag) ), "nft::accessDenied::notCreator" ); _; } /// @notice Clonable contract must have an empty constructor constructor() {} /** * @notice Initializes the extension with the DAO address that it belongs too. * @param _dao The address of the DAO that owns the extension. * @param creator The owner of the DAO and Extension that is also a member of the DAO. */ function initialize(DaoRegistry _dao, address creator) external override { require(!initialized, "already initialized"); require(_dao.isActiveMember(creator), "not active member"); initialized = true; _creator = creator; dao = _dao; } /** * @notice Collects the NFT from the owner and moves to the contract address * @notice It must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * @dev Reverts if the NFT is not support/allowed, or is not in ERC721 standard. * @param owner The owner of the NFT that wants to store it in the DAO. * @param nftAddr The NFT address that must be in ERC721 and allowed/supported by the extension. * @param nftTokenId The NFT token id. */ function collect( address owner, address nftAddr, uint256 nftTokenId ) external { require(isNFTAllowed(nftAddr), "nft not allowed"); IERC721 erc721 = IERC721(nftAddr); // Move the NFT to the contract address erc721.safeTransferFrom(owner, address(this), nftTokenId); // Save the asset in the GUILD collection _nftCollection[GUILD][nftAddr].add(nftTokenId); // Keep track of the collected assets _collectedNFTs.add(nftAddr); } /** * @notice Internally transfer the NFT token from the escrow adapter to the extension address. * @notice It also updates the internal state to keep track of the all the NFTs collected by the extension. * @notice It must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * @notice The caller must have the ACL Flag: TRANSFER_NFT * @dev Reverts if the NFT is not support/allowed, or is not in ERC721 standard. * @param escrowAddr The address of the escrow adapter, usually it is the address of the TributeNFT adapter. * @param nftAddr The NFT address that must be in ERC721 and allowed/supported by the extension. * @param nftTokenId The NFT token id. */ function transferFrom( address escrowAddr, address nftAddr, uint256 nftTokenId ) public hasExtensionAccess(this, AclFlag.TRANSFER_NFT) { require(isNFTAllowed(nftAddr), "non allowed nft"); IERC721 erc721 = IERC721(nftAddr); // Move the NFT to the contract address erc721.safeTransferFrom(escrowAddr, address(this), nftTokenId); // Save the asset in the GUILD collection _nftCollection[GUILD][nftAddr].add(nftTokenId); // Keep track of the collected assets _collectedNFTs.add(nftAddr); } /** * @notice Ttransfers the NFT token from the extension address to the new owner. * @notice It also updates the internal state to keep track of the all the NFTs collected by the extension. * @notice The caller must have the ACL Flag: RETURN_NFT * @dev Reverts if the NFT is not support/allowed, or is not in ERC721 standard. * @param newOwner The address of the new owner. * @param nftAddr The NFT address that must be in ERC721 and allowed/supported by the extension. * @param nftTokenId The NFT token id. */ function returnNFT( address newOwner, address nftAddr, uint256 nftTokenId ) public hasExtensionAccess(this, AclFlag.RETURN_NFT) { require(isNFTAllowed(nftAddr), "nft not allowed"); // Remove the NFT from the contract address to the actual owner IERC721 erc721 = IERC721(nftAddr); erc721.safeTransferFrom(address(this), newOwner, nftTokenId); // Remove the asset from the GUILD collection _nftCollection[GUILD][nftAddr].remove(nftTokenId); // If we dont hold the asset anymore, we can remove it if (_nftCollection[GUILD][nftAddr].length() == 0) { _collectedNFTs.remove(nftAddr); } } /** * @notice Registers a potential new NFT in the NFT extension. * @notice The caller must have the ACL Flag: REGISTER_NFT. * @dev Reverts if the token address is reserved. * @param nftAddr The address of the new NFT. */ function registerPotentialNewNFT(address nftAddr) public isCreatorOrHasExtensionAccess(this, AclFlag.REGISTER_NFT) { require( isNotReservedAddress(nftAddr) && nftAddr != SHARES, "reservedToken" ); if (!availableNFTs[nftAddr]) { availableNFTs[nftAddr] = true; } } /** * @notice Checks if a given token address is allowed/supported by the extension. */ function isNFTAllowed(address nftAddr) public view returns (bool) { return availableNFTs[nftAddr]; } /** * @notice Returns the total amount of NFTs collected. */ function nbNFTs() public view returns (uint256) { return _collectedNFTs.length(); } /** * @notice Returns NFT address stored in the GUILD collection at the specified index. * @param index The index to get the NFT address if it exists */ function getNFTByIndex(uint256 index) public view returns (address) { return _collectedNFTs.at(index); } /** * @notice Required function from IERC721 standard to be able to receive assets to this contract address */ function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return this.onERC721Received.selector; } }
Required function from IERC721 standard to be able to receive assets to this contract address/
function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return this.onERC721Received.selector; }
12,768,465
./full_match/1/0xa9Ccd56De8dE905B3359E05b851ca8311f4EF976/sources/contracts/interfaces/oracle/IOracleRegistry.sol
Alkimiya Oracle Addresses Alkimiya Team /
interface IOracleRegistry { event OracleRegistered(address token, uint256 oracleType, address oracleAddr); function getOracleAddress(address _token, uint256 _oracleType) external view returns (address); pragma solidity 0.8.6; }
16,431,214
./full_match/44787/0xcc9C556FbF52e7F1ca8e0E3eB7311ea21d893512/sources/contracts/LitVerify.sol
args: base 0x40, exponent 0x20, modulus 0x40, value ... use BigModExp precompile with exp = 1
function callBigModExp(bytes memory base, bytes memory modulus) internal view returns (bytes memory result) { result = new bytes(64); bool success; (success, result) = address(0x05).staticcall( abi.encodePacked( '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x40', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x20', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x40', base, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01', modulus ) ); require(success, 'BigModExp failed'); }
13,256,711
/** *Submitted for verification at Etherscan.io on 2022-04-11 */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <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. */ library EnumerableSet { // 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; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. 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] = toDeleteIndex + 1; // All indexes are 1-based // 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // 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); } // 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)))); } // 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)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @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 (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ pragma solidity ^0.7.0; contract GeniculateBlue is ERC721, Ownable { constructor() ERC721("Geniculate Blue", "LGN") {} using SafeMath for uint256; uint256 public constant nftPrice = 550000000000000000; uint public constant MAX_PURCHASE = 11; uint256 public constant MAX_MAIN = 475; bool public saleIsActive = false; uint public teamReserve = 15; function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function reserve(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= teamReserve, "More."); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } teamReserve = teamReserve.sub(_reserveAmount); } function mint(uint _numberOfTokens) public payable { require(saleIsActive, "Not Active."); require(_numberOfTokens <= MAX_PURCHASE, "Exceeded limit."); require(totalSupply().add(_numberOfTokens) <= MAX_MAIN, "Too many minted."); require(msg.value >= nftPrice, "More Ethereum."); for(uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_MAIN) { _safeMint(msg.sender, mintIndex); } } } string public mintedCode; bool public isReconstructed = false; mapping (uint256 => string) public geniculateSeeds; mapping (uint256 => bool) public seedSet; mapping (uint => string) public mintedColors; event SeedWritten (uint256 indexed nameIndex, string newName); function setSeed(uint256 _tokenId, string calldata currName) public { address owner = ownerOf(_tokenId); require(msg.sender == owner, "Incorrect."); require(seedSet[_tokenId] == false, "Name given."); seedSet[_tokenId] = true; geniculateSeeds[_tokenId] = currName; emit SeedWritten(_tokenId, currName); } function viewSeed(uint _tokenId) public view returns(string memory){ return geniculateSeeds[_tokenId]; } function setCode(string calldata currName) public onlyOwner { mintedCode = currName; } function viewCode() public view returns(string memory) { return mintedCode; } function setColors(uint palette, string calldata palette_param) public onlyOwner { mintedColors[palette] = palette_param; } function viewColors(uint palette) public view returns(string memory) { return mintedColors[palette]; } }
Returns the value associated with `key`. O(1). Requirements: - `key` must be in the map./
function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; }
2,048,157
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.13; import "ds-test/test.sol"; // ds-test import "../OlympusERC20.sol"; import "../OlympusAuthority.sol"; contract OlymppusERC20TokenTest is DSTest { OlympusERC20 internal ohmContract; IOlympusAuthority internal authority; address internal UNAUTHORIZED_USER = address(0x1); function test_erc20() public { authority = new OlympusAuthority( address(this), address(this), address(this), address(this) ); ohmContract = new OlympusERC20(address(authority)); assertEq("Olympus", ohmContract.name()); assertEq("OHM", ohmContract.symbol()); assertEq(9, uint256(ohmContract.decimals())); } function testCannot_mint() public { authority = new OlympusAuthority( address(this), address(this), address(this), UNAUTHORIZED_USER ); ohmContract = new OlympusERC20(address(authority)); // try/catch block pattern copied from https://github.com/Anish-Agnihotri/MultiRaffle/blob/master/src/test/utils/DSTestExtended.sol try ohmContract.mint(address(this), 100) { fail(); } catch Error(string memory error) { // Assert revert error matches expected message assertEq("UNAUTHORIZED", error); } } // Tester will pass it's own parameters, see https://fv.ethereum.org/2020/12/11/symbolic-execution-with-ds-test/ function test_mint(uint256 amount) public { authority = new OlympusAuthority( address(this), address(this), address(this), address(this) ); ohmContract = new OlympusERC20(address(authority)); uint256 supplyBefore = ohmContract.totalSupply(); // TODO look into https://dapphub.chat/channel/dev?msg=HWrPJqxp8BHMiKTbo // ohmContract.setVault(address(this)); //TODO WTF msg.sender doesn't propigate from .dapprc $DAPP_TEST_CALLER config via mint() call, must use this value ohmContract.mint(address(this), amount); assertEq(supplyBefore + amount, ohmContract.totalSupply()); } // Tester will pass it's own parameters, see https://fv.ethereum.org/2020/12/11/symbolic-execution-with-ds-test/ function test_burn(uint256 mintAmount, uint256 burnAmount) public { authority = new OlympusAuthority( address(this), address(this), address(this), address(this) ); ohmContract = new OlympusERC20(address(authority)); uint256 supplyBefore = ohmContract.totalSupply(); // ohmContract.setVault(address(this)); //TODO WTF msg.sender doesn't propigate from .dapprc $DAPP_TEST_CALLER config via mint() call, must use this value ohmContract.mint(address(this), mintAmount); if (burnAmount <= mintAmount) { ohmContract.burn(burnAmount); assertEq( supplyBefore + mintAmount - burnAmount, ohmContract.totalSupply() ); } else { try ohmContract.burn(burnAmount) { fail(); } catch Error(string memory error) { // Assert revert error matches expected message assertEq("ERC20: burn amount exceeds balance", error); } } } }
Tester will pass it's own parameters, see https:fv.ethereum.org/2020/12/11/symbolic-execution-with-ds-test/ ohmContract.setVault(address(this)); TODO WTF msg.sender doesn't propigate from .dapprc $DAPP_TEST_CALLER config via mint() call, must use this value Assert revert error matches expected message
function test_burn(uint256 mintAmount, uint256 burnAmount) public { authority = new OlympusAuthority( address(this), address(this), address(this), address(this) ); ohmContract = new OlympusERC20(address(authority)); uint256 supplyBefore = ohmContract.totalSupply(); ohmContract.mint(address(this), mintAmount); if (burnAmount <= mintAmount) { ohmContract.burn(burnAmount); assertEq( supplyBefore + mintAmount - burnAmount, ohmContract.totalSupply() ); try ohmContract.burn(burnAmount) { fail(); assertEq("ERC20: burn amount exceeds balance", error); } } }
5,439,413
./full_match/1/0x5e94bE61091149753D4D44BE38f85d4739766C85/sources/src/ClaimingCenter.sol
Function for the owner to withdraw the entire balance of the commodity living in this contract./
function withdrawEntireCommodityBalance( address to ) external nonReentrant onlyOwner returns (bool success) { uint256 amount = commodity.balanceOf(address(this)); success = commodity.transfer(to, amount); require(success, "transfer not successful!"); if (success) { commodityReserves = 0; emit CommodityWithdraw(to, amount); return success; } }
3,067,051
./partial_match/42/0xf32d3c5d67AA736790cCDf603b1bf76F2ba4D007/sources/CurryChef.sol
override the functions and make it virtual to be overridden by child contract
function transfer(address recipient, uint256 amount) external override virtual returns (bool) { }
3,304,921
./partial_match/1/0x5a6F7Ef7384c5dA809d5Ce126aba9D4538D852d7/sources/CommunityFund.sol
only restake more if at this epoch we could claim pending dollar rewards
function claimAndRestake() public checkPublicAllow { if (IBoardroom(boardroom).canClaimReward(address(this))) { if (earned() > 0) { IBoardroom(boardroom).claimReward(); } uint256 _shareBal = IERC20(share).balanceOf(address(this)); if (_shareBal > 0) { IERC20(share).safeApprove(boardroom, 0); IERC20(share).safeApprove(boardroom, _shareBal); IBoardroom(boardroom).stake(_shareBal); } } }
4,478,617
pragma solidity ^0.4.11; // HUNT Crowdsale Token Contract // Aqua Commerce LTD Company #194644 (Republic of Seychelles) // The MIT Licence . contract SafeMath { function sub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x - y) <= x); } function add(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x + y) >= x); } function div(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x / y; } function min(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x <= y ? x : y; } } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() { owner = msg.sender; } modifier onlyOwner { assert (msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { OwnershipTransferred(owner, newOwner); owner = newOwner; } } } // ERC20 interface // see https://github.com/ethereum/EIPs/issues/20 contract ERC20 { function totalSupply() constant returns (uint totalSupply); function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract StandardToken is ERC20, SafeMath { uint256 _totalSupply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } function totalSupply() constant returns (uint256) { return _totalSupply; } function balanceOf(address _who) constant returns (uint256) { return _balances[_who]; } function allowance(address _owner, address _spender) constant returns (uint256) { return _approvals[_owner][_spender]; } function transfer(address _to, uint _value) onlyPayloadSize(2) returns (bool success) { assert(_balances[msg.sender] >= _value); _balances[msg.sender] = sub(_balances[msg.sender], _value); _balances[_to] = add(_balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3) returns (bool success) { assert(_balances[_from] >= _value); assert(_approvals[_from][msg.sender] >= _value); _approvals[_from][msg.sender] = sub(_approvals[_from][msg.sender], _value); _balances[_from] = sub(_balances[_from], _value); _balances[_to] = add(_balances[_to], _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) onlyPayloadSize(2) returns (bool success) { _approvals[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract HUNT is StandardToken, Owned { // Token information string public constant name = "HUNT"; string public constant symbol = "HT"; uint8 public constant decimals = 18; // Initial contract data uint256 public capTokens; uint256 public startDate; uint256 public endDate; uint public curs; address addrcnt; uint256 public totalTokens; uint256 public totalEthers; mapping (address => uint256) _userBonus; event BoughtTokens(address indexed buyer, uint256 ethers,uint256 newEtherBalance, uint256 tokens, uint _buyPrice); event Collect(address indexed addrcnt,uint256 amount); function HUNT(uint256 _start, uint256 _end, uint256 _capTokens, uint _curs, address _addrcnt) { startDate = _start; endDate = _end; capTokens = _capTokens; addrcnt = _addrcnt; curs = _curs; } function time() internal constant returns (uint) { return block.timestamp; } // Cost of one token // Day 1-2 : 1 USD = 1 HUNT // Days 3–5 : 1.2 USD = 1 HUNT // Days 6–10 : 1.3 USD = 1 HUNT // Days 11–15: 1.4 USD = 1 HUNT // Days 16–22: 1.5 USD = 1 HUNT function buyPrice() constant returns (uint256) { return buyPriceAt(time()); } function buyPriceAt(uint256 at) constant returns (uint256) { if (at < startDate) { return 0; } else if (at < (startDate + 2 days)) { return div(curs,100); } else if (at < (startDate + 5 days)) { return div(curs,120); } else if (at < (startDate + 10 days)) { return div(curs,130); } else if (at < (startDate + 15 days)) { return div(curs,140); } else if (at <= endDate) { return div(curs,150); } else { return 0; } } // Buy tokens from the contract function () payable { buyTokens(msg.sender); } // Exchanges can buy on behalf of participant function buyTokens(address participant) payable { // No contributions before the start of the crowdsale require(time() >= startDate); // No contributions after the end of the crowdsale require(time() <= endDate); // No 0 contributions require(msg.value > 0); // Add ETH raised to total totalEthers = add(totalEthers, msg.value); // What is the HUNT to ETH rate uint256 _buyPrice = buyPrice(); // Calculate #HUNT - this is safe as _buyPrice is known // and msg.value is restricted to valid values uint tokens = msg.value * _buyPrice; // Check tokens > 0 require(tokens > 0); if ((time() >= (startDate + 15 days)) && (time() <= endDate)){ uint leftTokens=sub(capTokens,add(totalTokens, tokens)); leftTokens = (leftTokens>0)? leftTokens:0; uint bonusTokens = min(_userBonus[participant],min(tokens,leftTokens)); // Check bonusTokens >= 0 require(bonusTokens >= 0); tokens = add(tokens,bonusTokens); } // Cannot exceed capTokens totalTokens = add(totalTokens, tokens); require(totalTokens <= capTokens); // Compute tokens for foundation 38% // Number of tokens restricted so maths is safe uint ownerTokens = div(tokens,50)*19; // Add to total supply _totalSupply = add(_totalSupply, tokens); _totalSupply = add(_totalSupply, ownerTokens); // Add to balances _balances[participant] = add(_balances[participant], tokens); _balances[owner] = add(_balances[owner], ownerTokens); // Add to user bonus if (time() < (startDate + 2 days)){ uint bonus = div(tokens,2); _userBonus[participant] = add(_userBonus[participant], bonus); } // Log events BoughtTokens(participant, msg.value, totalEthers, tokens, _buyPrice); Transfer(0x0, participant, tokens); Transfer(0x0, owner, ownerTokens); } // Transfer the balance from owner's account to another account, with a // check that the crowdsale is finalised function transfer(address _to, uint _amount) returns (bool success) { // Cannot transfer before crowdsale ends + 7 days require((time() > endDate + 7 days )); // Standard transfer return super.transfer(_to, _amount); } // Spender of tokens transfer an amount of tokens from the token owner's // balance to another account, with a check that the crowdsale is // finalised function transferFrom(address _from, address _to, uint _amount) returns (bool success) { // Cannot transfer before crowdsale ends + 7 days require((time() > endDate + 7 days )); // Standard transferFrom return super.transferFrom(_from, _to, _amount); } function mint(uint256 _amount) onlyOwner { require((time() > endDate + 7 days )); require(_amount > 0); _balances[owner] = add(_balances[owner], _amount); _totalSupply = add(_totalSupply, _amount); Transfer(0x0, owner, _amount); } function burn(uint256 _amount) onlyOwner { require((time() > endDate + 7 days )); require(_amount > 0); _balances[owner] = sub(_balances[owner],_amount); _totalSupply = sub(_totalSupply,_amount); Transfer(owner, 0x0 , _amount); } function setCurs(uint8 _curs) onlyOwner { require(_curs > 0); curs = _curs; } // Crowdsale owners can collect ETH any number of times function collect() onlyOwner { require(addrcnt.call.value(this.balance)(0)); Collect(addrcnt,this.balance); } }
Crowdsale owners can collect ETH any number of times
function collect() onlyOwner { require(addrcnt.call.value(this.balance)(0)); Collect(addrcnt,this.balance); }
952,117
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; /*** VIEW & PURE FUNCTIONS ***/ function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self.balances, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( uint256[] memory balances, uint256 amount, uint256 totalSupply ) internal pure returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( balances, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function swapStorage() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, address ); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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 GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/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 guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; 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 a proxied contract can't have 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 {UpgradeableProxy-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. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAllowlist { function getPoolAccountLimit(address poolAddress) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); function verifyAddress(address account, bytes32[] calldata merkleProof) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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 initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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 make 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./Swap.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoan is Swap { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; /** * @title IFlashLoanReceiver interface * @notice Interface for the Saddle fee IFlashLoanReceiver. Modified from Aave's IFlashLoanReceiver interface. * https://github.com/aave/aave-protocol/blob/4b4545fb583fd4f400507b10f3c3114f45b8a037/contracts/flashloan/interfaces/IFlashLoanReceiver.sol * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./SwapV1.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoanV1 is SwapV1 { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual override initializer { SwapV1.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtilsV1.sol"; import "./AmplificationUtilsV1.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapV1 is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtilsV1 for SwapUtilsV1.Swap; using AmplificationUtilsV1 for SwapUtilsV1.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsV1.sol SwapUtilsV1.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsV1.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsV1.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtilsV1.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsV1.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsV1.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsV1.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtilsV1.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtilsV1.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtilsV1.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsV1 { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtilsV1._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtilsV1.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtilsV1.A_PRECISION) .mul(d) .div(AmplificationUtilsV1.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add( WITHDRAW_FEE_DECAY_TIME ); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtilsV1.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtilsV1 { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtilsV1.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtilsV1.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtilsV1.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(ISwap baseSwap) internal view returns (uint256 swapFee) { (, , , , swapFee, , ) = baseSwap.swapStorage(); } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); v.newY = v.newY.mul(BASE_VIRTUAL_PRICE_PRECISION).div( baseVirtualPrice ); xp[tokenIndex] = xp[tokenIndex] .mul(BASE_VIRTUAL_PRICE_PRECISION) .div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 baseLPTokenIndex = xp.length.sub(1); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]); if (tokenIndexFrom == baseLPTokenIndex) { // When swapping from a base Swap token, scale up dx by its virtual price x = x.mul(baseVirtualPrice).div(BASE_VIRTUAL_PRICE_PRECISION); } x = x.add(xp[tokenIndexFrom]); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); if (tokenIndexTo == baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee); dy = dy.div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION); // when adding to the base pool,you pay approx 50% of the swap fee v.x = v .x .sub( v.x.mul(_getBaseSwapFee(metaSwapStorage.baseSwap)).div( FEE_DENOMINATOR.mul(2) ) ) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IMetaSwap.sol"; /** * @title MetaSwapDeposit * @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be * deployed before this contract can be initialized successfully. * * For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. * Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either * the LP token or the underlying tokens and sUSD. * * MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users * to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act * as a Swap containing [sUSD, DAI, USDC, USDT] tokens. */ contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ISwap public baseSwap; IMetaSwap public metaSwap; IERC20[] public baseTokens; IERC20[] public metaTokens; IERC20[] public tokens; IERC20 public metaLPToken; uint256 constant MAX_UINT256 = 2**256 - 1; struct RemoveLiquidityImbalanceInfo { ISwap baseSwap; IMetaSwap metaSwap; IERC20 metaLPToken; uint8 baseLPTokenIndex; bool withdrawFromBase; uint256 leftoverMetaLPTokenAmount; } /** * @notice Sets the address for the base Swap contract, MetaSwap contract, and the * MetaSwap LP token contract. * @param _baseSwap the address of the base Swap contract * @param _metaSwap the address of the MetaSwap contract * @param _metaLPToken the address of the MetaSwap LP token contract */ function initialize( ISwap _baseSwap, IMetaSwap _metaSwap, IERC20 _metaLPToken ) external initializer { __ReentrancyGuard_init(); // Check and approve base level tokens to be deposited to the base Swap contract { uint8 i; for (; i < 32; i++) { try _baseSwap.getToken(i) returns (IERC20 token) { baseTokens.push(token); token.safeApprove(address(_baseSwap), MAX_UINT256); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must have at least 2 tokens"); } // Check and approve meta level tokens to be deposited to the MetaSwap contract IERC20 baseLPToken; { uint8 i; for (; i < 32; i++) { try _metaSwap.getToken(i) returns (IERC20 token) { baseLPToken = token; metaTokens.push(token); tokens.push(token); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "metaSwap must have at least 2 tokens"); } // Flatten baseTokens and append it to tokens array tokens[tokens.length - 1] = baseTokens[0]; for (uint8 i = 1; i < baseTokens.length; i++) { tokens.push(baseTokens[i]); } // Approve base Swap LP token to be burned by the base Swap contract for withdrawing baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256); // Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing _metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256); // Initialize storage variables baseSwap = _baseSwap; metaSwap = _metaSwap; metaLPToken = _metaLPToken; } // Mutative functions /** * @notice Swap two underlying tokens using the meta pool and the base pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant returns (uint256) { tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 tokenToAmount = metaSwap.swapUnderlying( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount); return tokenToAmount; } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external nonReentrant returns (uint256) { // Read to memory to save on gas IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256 baseLPTokenIndex = memMetaTokens.length - 1; require(amounts.length == memBaseTokens.length + baseLPTokenIndex); uint256 baseLPTokenAmount; { // Transfer base tokens from the caller and deposit to the base Swap pool uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); bool shouldDepositBaseTokens; for (uint8 i = 0; i < memBaseTokens.length; i++) { IERC20 token = memBaseTokens[i]; uint256 depositAmount = amounts[baseLPTokenIndex + i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer // if there are any base Swap level tokens, flag it for deposits shouldDepositBaseTokens = true; } } if (shouldDepositBaseTokens) { // Deposit any base Swap level tokens and receive baseLPToken baseLPTokenAmount = baseSwap.addLiquidity( baseAmounts, 0, deadline ); } } uint256 metaLPTokenAmount; { // Transfer remaining meta level tokens from the caller uint256[] memory metaAmounts = new uint256[](metaTokens.length); for (uint8 i = 0; i < baseLPTokenIndex; i++) { IERC20 token = memMetaTokens[i]; uint256 depositAmount = amounts[i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer } } // Update the baseLPToken amount that will be deposited metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; // Deposit the meta level tokens and the baseLPToken metaLPTokenAmount = metaSwap.addLiquidity( metaAmounts, minToMint, deadline ); } // Transfer the meta lp token to the caller metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount; } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant returns (uint256[] memory) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory totalRemovedAmounts; { uint256 numOfAllTokens = memBaseTokens.length + memMetaTokens.length - 1; require(minAmounts.length == numOfAllTokens, "out of range"); totalRemovedAmounts = new uint256[](numOfAllTokens); } // Transfer meta lp token from the caller to this metaLPToken.safeTransferFrom(msg.sender, address(this), amount); uint256 baseLPTokenAmount; { // Remove liquidity from the MetaSwap pool uint256[] memory removedAmounts; uint256 baseLPTokenIndex = memMetaTokens.length - 1; { uint256[] memory metaMinAmounts = new uint256[]( memMetaTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaMinAmounts[i] = minAmounts[i]; } removedAmounts = metaSwap.removeLiquidity( amount, metaMinAmounts, deadline ); } // Send the meta level tokens to the caller for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalRemovedAmounts[i] = removedAmounts[i]; memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } baseLPTokenAmount = removedAmounts[baseLPTokenIndex]; // Remove liquidity from the base Swap pool { uint256[] memory baseMinAmounts = new uint256[]( memBaseTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i]; } removedAmounts = baseSwap.removeLiquidity( baseLPTokenAmount, baseMinAmounts, deadline ); } // Send the base level tokens to the caller for (uint8 i = 0; i < memBaseTokens.length; i++) { totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i]; memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } } return totalRemovedAmounts; } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); uint8 baseTokensLength = uint8(baseTokens.length); // Transfer metaLPToken from the caller metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount); IERC20 token; if (tokenIndex < baseLPTokenIndex) { // When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly metaSwap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, deadline ); token = metaTokens[tokenIndex]; } else if (tokenIndex < baseLPTokenIndex + baseTokensLength) { // When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw // the desired token from the base Swap contract. uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken( tokenAmount, baseLPTokenIndex, 0, deadline ); baseSwap.removeLiquidityOneToken( removedBaseLPTokenAmount, tokenIndex - baseLPTokenIndex, minAmount, deadline ); token = baseTokens[tokenIndex - baseLPTokenIndex]; } else { revert("out of range"); } uint256 amountWithdrawn = token.balanceOf(address(this)); token.safeTransfer(msg.sender, amountWithdrawn); return amountWithdrawn; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant returns (uint256) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory metaAmounts = new uint256[](memMetaTokens.length); uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); require( amounts.length == memBaseTokens.length + memMetaTokens.length - 1, "out of range" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( baseSwap, metaSwap, metaLPToken, uint8(metaAmounts.length - 1), false, 0 ); for (uint8 i = 0; i < v.baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[v.baseLPTokenIndex + i]; if (baseAmounts[i] > 0) { v.withdrawFromBase = true; } } // Calculate how much base LP token we need to get the desired amount of underlying tokens if (v.withdrawFromBase) { metaAmounts[v.baseLPTokenIndex] = v .baseSwap .calculateTokenAmount(baseAmounts, false) .mul(10005) .div(10000); } // Transfer MetaSwap LP token from the caller to this contract v.metaLPToken.safeTransferFrom( msg.sender, address(this), maxBurnAmount ); // Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance( metaAmounts, maxBurnAmount, deadline ); v.leftoverMetaLPTokenAmount = maxBurnAmount.sub( burnedMetaLPTokenAmount ); // If underlying tokens are desired, withdraw them from the base Swap pool if (v.withdrawFromBase) { v.baseSwap.removeLiquidityImbalance( baseAmounts, metaAmounts[v.baseLPTokenIndex], deadline ); // Base Swap may require LESS base LP token than the amount we have // In that case, deposit it to the MetaSwap pool. uint256[] memory leftovers = new uint256[](metaAmounts.length); IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex]; uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf( address(this) ); if (leftoverBaseLPTokenAmount > 0) { leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount; v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add( v.metaSwap.addLiquidity(leftovers, 0, deadline) ); } } // Transfer all withdrawn tokens to the caller for (uint8 i = 0; i < amounts.length; i++) { IERC20 token; if (i < v.baseLPTokenIndex) { token = memMetaTokens[i]; } else { token = memBaseTokens[i - v.baseLPTokenIndex]; } if (amounts[i] > 0) { token.safeTransfer(msg.sender, amounts[i]); } } // If there were any extra meta lp token, transfer them back to the caller as well if (v.leftoverMetaLPTokenAmount > 0) { v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount); } return maxBurnAmount - v.leftoverMetaLPTokenAmount; } // VIEW FUNCTIONS /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running. When withdrawing from the base pool in imbalanced * fashion, the recommended slippage setting is 0.2% or higher. * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256) { uint256[] memory metaAmounts = new uint256[](metaTokens.length); uint256[] memory baseAmounts = new uint256[](baseTokens.length); uint256 baseLPTokenIndex = metaAmounts.length - 1; for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[baseLPTokenIndex + i]; } uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount( baseAmounts, deposit ); metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; return metaSwap.calculateTokenAmount(metaAmounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity( amount ); uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1); uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity( metaAmounts[baseLPTokenIndex] ); uint256[] memory totalAmounts = new uint256[]( baseLPTokenIndex + baseAmounts.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalAmounts[i] = metaAmounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { totalAmounts[baseLPTokenIndex + i] = baseAmounts[i]; } return totalAmounts; } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); if (tokenIndex < baseLPTokenIndex) { return metaSwap.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ); } else { uint256 baseLPTokenAmount = metaSwap .calculateRemoveLiquidityOneToken( tokenAmount, baseLPTokenIndex ); return baseSwap.calculateRemoveLiquidityOneToken( baseLPTokenAmount, tokenIndex - baseLPTokenIndex ); } } /** * @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range. * This is a flattened representation of the pooled tokens. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) external view returns (IERC20) { require(index < tokens.length, "index out of range"); return tokens[index]; } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ISwap.sol"; interface IMetaSwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwap.sol"; import "./interfaces/IMetaSwap.sol"; contract SwapDeployer is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); event NewClone(address indexed target, address cloneAddress); constructor() public Ownable() {} function clone(address target) external returns (address) { address newClone = _clone(target); emit NewClone(target, newClone); return newClone; } function _clone(address target) internal returns (address) { return Clones.clone(target); } function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = _clone(swapAddress); ISwap(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } function deployMetaSwap( address metaSwapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external returns (address) { address metaSwapClone = _clone(metaSwapAddress); IMetaSwap(metaSwapClone).initializeMetaSwap( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress, baseSwap ); Ownable(metaSwapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, metaSwapClone, _pooledTokens); return metaSwapClone; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "synthetix/contracts/interfaces/ISynthetix.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interfaces/ISwap.sol"; /** * @title SynthSwapper * @notice Replacement of Virtual Synths in favor of gas savings. Allows swapping synths via the Synthetix protocol * or Saddle's pools. The `Bridge.sol` contract will deploy minimal clones of this contract upon initiating * any cross-asset swaps. */ contract SynthSwapper is Initializable { using SafeERC20 for IERC20; address payable owner; // SYNTHETIX points to `ProxyERC20` (0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F). // This contract is a proxy of `Synthetix` and is used to exchange synths. ISynthetix public constant SYNTHETIX = ISynthetix(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // "SADDLE" in bytes32 form bytes32 public constant TRACKING = 0x534144444c450000000000000000000000000000000000000000000000000000; /** * @notice Initializes the contract when deploying this directly. This prevents * others from calling initialize() on the target contract and setting themself as the owner. */ constructor() public { initialize(); } /** * @notice This modifier checks if the caller is the owner */ modifier onlyOwner() { require(msg.sender == owner, "is not owner"); _; } /** * @notice Sets the `owner` as the caller of this function */ function initialize() public initializer { require(owner == address(0), "owner already set"); owner = msg.sender; } /** * @notice Swaps the synth to another synth via the Synthetix protocol. * @param sourceKey currency key of the source synth * @param synthAmount amount of the synth to swap * @param destKey currency key of the destination synth * @return amount of the destination synth received */ function swapSynth( bytes32 sourceKey, uint256 synthAmount, bytes32 destKey ) external onlyOwner returns (uint256) { return SYNTHETIX.exchangeWithTracking( sourceKey, synthAmount, destKey, msg.sender, TRACKING ); } /** * @notice Approves the given `tokenFrom` and swaps it to another token via the given `swap` pool. * @param swap the address of a pool to swap through * @param tokenFrom the address of the stored synth * @param tokenFromIndex the index of the token to swap from * @param tokenToIndex the token the user wants to swap to * @param tokenFromAmount the amount of the token to swap * @param minAmount the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction * @param recipient the address of the recipient */ function swapSynthToToken( ISwap swap, IERC20 tokenFrom, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minAmount, uint256 deadline, address recipient ) external onlyOwner returns (IERC20, uint256) { tokenFrom.approve(address(swap), tokenFromAmount); swap.swap( tokenFromIndex, tokenToIndex, tokenFromAmount, minAmount, deadline ); IERC20 tokenTo = swap.getToken(tokenToIndex); uint256 balance = tokenTo.balanceOf(address(this)); tokenTo.safeTransfer(recipient, balance); return (tokenTo, balance); } /** * @notice Withdraws the given amount of `token` to the `recipient`. * @param token the address of the token to withdraw * @param recipient the address of the account to receive the token * @param withdrawAmount the amount of the token to withdraw * @param shouldDestroy whether this contract should be destroyed after this call */ function withdraw( IERC20 token, address recipient, uint256 withdrawAmount, bool shouldDestroy ) external onlyOwner { token.safeTransfer(recipient, withdrawAmount); if (shouldDestroy) { _destroy(); } } /** * @notice Destroys this contract. Only owner can call this function. */ function destroy() external onlyOwner { _destroy(); } function _destroy() internal { selfdestruct(msg.sender); } } pragma solidity >=0.4.24; import "./ISynth.sol"; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } pragma solidity >=0.4.24; import "./ISynth.sol"; interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwapV1.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPTokenV1 is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwapV1(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapV1 { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwapV1.sol"; contract SwapDeployerV1 is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); constructor() public Ownable() {} function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = Clones.clone(swapAddress); ISwapV1(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "synthetix/contracts/interfaces/IAddressResolver.sol"; import "synthetix/contracts/interfaces/IExchanger.sol"; import "synthetix/contracts/interfaces/IExchangeRates.sol"; import "../interfaces/ISwap.sol"; import "./SynthSwapper.sol"; contract Proxy { address public target; } contract Target { address public proxy; } /** * @title Bridge * @notice This contract is responsible for cross-asset swaps using the Synthetix protocol as the bridging exchange. * There are three types of supported cross-asset swaps, tokenToSynth, synthToToken, and tokenToToken. * * 1) tokenToSynth * Swaps a supported token in a saddle pool to any synthetic asset (e.g. tBTC -> sAAVE). * * 2) synthToToken * Swaps any synthetic asset to a suported token in a saddle pool (e.g. sDEFI -> USDC). * * 3) tokenToToken * Swaps a supported token in a saddle pool to one in another pool (e.g. renBTC -> DAI). * * Due to the settlement periods of synthetic assets, the users must wait until the trades can be completed. * Users will receive an ERC721 token that represents pending cross-asset swap. Once the waiting period is over, * the trades can be settled and completed by calling the `completeToSynth` or the `completeToToken` function. * In the cases of pending `synthToToken` or `tokenToToken` swaps, the owners of the pending swaps can also choose * to withdraw the bridging synthetic assets instead of completing the swap. */ contract Bridge is ERC721 { using SafeMath for uint256; using SafeERC20 for IERC20; event SynthIndex( address indexed swap, uint8 synthIndex, bytes32 currencyKey, address synthAddress ); event TokenToSynth( address indexed requester, uint256 indexed itemId, ISwap swapPool, uint8 tokenFromIndex, uint256 tokenFromInAmount, bytes32 synthToKey ); event SynthToToken( address indexed requester, uint256 indexed itemId, ISwap swapPool, bytes32 synthFromKey, uint256 synthFromInAmount, uint8 tokenToIndex ); event TokenToToken( address indexed requester, uint256 indexed itemId, ISwap[2] swapPools, uint8 tokenFromIndex, uint256 tokenFromAmount, uint8 tokenToIndex ); event Settle( address indexed requester, uint256 indexed itemId, IERC20 settleFrom, uint256 settleFromAmount, IERC20 settleTo, uint256 settleToAmount, bool isFinal ); event Withdraw( address indexed requester, uint256 indexed itemId, IERC20 synth, uint256 synthAmount, bool isFinal ); // The addresses for all Synthetix contracts can be found in the below URL. // https://docs.synthetix.io/addresses/#mainnet-contracts // // Since the Synthetix protocol is upgradable, we must use the proxy pairs of each contract such that // the composability is not broken after the protocol upgrade. // // SYNTHETIX_RESOLVER points to `ReadProxyAddressResolver` (0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2). // This contract is a read proxy of `AddressResolver` which is responsible for storing the addresses of the contracts // used by the Synthetix protocol. IAddressResolver public constant SYNTHETIX_RESOLVER = IAddressResolver(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2); // EXCHANGER points to `Exchanger`. There is no proxy pair for this contract so we need to update this variable // when the protocol is upgraded. This contract is used to settle synths held by SynthSwapper. IExchanger public exchanger; // CONSTANTS // Available types of cross-asset swaps enum PendingSwapType { Null, TokenToSynth, SynthToToken, TokenToToken } uint256 public constant MAX_UINT256 = 2**256 - 1; uint8 public constant MAX_UINT8 = 2**8 - 1; bytes32 public constant EXCHANGE_RATES_NAME = "ExchangeRates"; bytes32 public constant EXCHANGER_NAME = "Exchanger"; address public immutable SYNTH_SWAPPER_MASTER; // MAPPINGS FOR STORING PENDING SETTLEMENTS // The below two mappings never share the same key. mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps; mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps; uint256 public pendingSwapsLength; mapping(uint256 => PendingSwapType) private pendingSwapType; // MAPPINGS FOR STORING SYNTH INFO mapping(address => SwapContractInfo) private swapContracts; // Structs holding information about pending settlements struct PendingToSynthSwap { SynthSwapper swapper; bytes32 synthKey; } struct PendingToTokenSwap { SynthSwapper swapper; bytes32 synthKey; ISwap swap; uint8 tokenToIndex; } struct SwapContractInfo { // index of the supported synth + 1 uint8 synthIndexPlusOne; // address of the supported synth address synthAddress; // bytes32 key of the supported synth bytes32 synthKey; // array of tokens supported by the contract IERC20[] tokens; } /** * @notice Deploys this contract and initializes the master version of the SynthSwapper contract. The address to * the Synthetix protocol's Exchanger contract is also set on deployment. */ constructor(address synthSwapperAddress) public ERC721("Saddle Cross-Asset Swap", "SaddleSynthSwap") { SYNTH_SWAPPER_MASTER = synthSwapperAddress; updateExchangerCache(); } /** * @notice Returns the address of the proxy contract targeting the synthetic asset with the given `synthKey`. * @param synthKey the currency key of the synth * @return address of the proxy contract */ function getProxyAddressFromTargetSynthKey(bytes32 synthKey) public view returns (IERC20) { return IERC20(Target(SYNTHETIX_RESOLVER.getSynth(synthKey)).proxy()); } /** * @notice Returns various information of a pending swap represented by the given `itemId`. Information includes * the type of the pending swap, the number of seconds left until it can be settled, the address and the balance * of the synth this swap currently holds, and the address of the destination token. * @param itemId ID of the pending swap * @return swapType the type of the pending virtual swap, * secsLeft number of seconds left until this swap can be settled, * synth address of the synth this swap uses, * synthBalance amount of the synth this swap holds, * tokenTo the address of the destination token */ function getPendingSwapInfo(uint256 itemId) external view returns ( PendingSwapType swapType, uint256 secsLeft, address synth, uint256 synthBalance, address tokenTo ) { swapType = pendingSwapType[itemId]; require(swapType != PendingSwapType.Null, "invalid itemId"); SynthSwapper synthSwapper; bytes32 synthKey; if (swapType == PendingSwapType.TokenToSynth) { synthSwapper = pendingToSynthSwaps[itemId].swapper; synthKey = pendingToSynthSwaps[itemId].synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = synth; } else { PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; synthSwapper = pendingToTokenSwap.swapper; synthKey = pendingToTokenSwap.synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = address( swapContracts[address(pendingToTokenSwap.swap)].tokens[ pendingToTokenSwap.tokenToIndex ] ); } secsLeft = exchanger.maxSecsLeftInWaitingPeriod( address(synthSwapper), synthKey ); synthBalance = IERC20(synth).balanceOf(address(synthSwapper)); } // Settles the synth only. function _settle(address synthOwner, bytes32 synthKey) internal { // Settle synth exchanger.settle(synthOwner, synthKey); } /** * @notice Settles and withdraws the synthetic asset without swapping it to a token in a Saddle pool. Only the owner * of the ERC721 token of `itemId` can call this function. Reverts if the given `itemId` does not represent a * `synthToToken` or a `tokenToToken` swap. * @param itemId ID of the pending swap * @param amount the amount of the synth to withdraw */ function withdraw(uint256 itemId, uint256 amount) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroy; if (amount >= synth.balanceOf(address(pendingToTokenSwap.swapper))) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroy = true; } pendingToTokenSwap.swapper.withdraw( synth, nftOwner, amount, shouldDestroy ); emit Withdraw(msg.sender, itemId, synth, amount, shouldDestroy); } /** * @notice Completes the pending `tokenToSynth` swap by settling and withdrawing the synthetic asset. * Reverts if the given `itemId` does not represent a `tokenToSynth` swap. * @param itemId ERC721 token ID representing a pending `tokenToSynth` swap */ function completeToSynth(uint256 itemId) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] == PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToSynthSwap memory pendingToSynthSwap = pendingToSynthSwaps[ itemId ]; _settle( address(pendingToSynthSwap.swapper), pendingToSynthSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToSynthSwap.synthKey ); // Burn the corresponding ERC721 token and delete storage for gas _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; // After settlement, withdraw the synth and send it to the recipient uint256 synthBalance = synth.balanceOf( address(pendingToSynthSwap.swapper) ); pendingToSynthSwap.swapper.withdraw( synth, nftOwner, synthBalance, true ); emit Settle( msg.sender, itemId, synth, synthBalance, synth, synthBalance, true ); } /** * @notice Calculates the expected amount of the token to receive on calling `completeToToken()` with * the given `swapAmount`. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @return expected amount of the token the user will receive */ function calcCompleteToToken(uint256 itemId, uint256 swapAmount) external view returns (uint256) { require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; return pendingToTokenSwap.swap.calculateSwap( getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount ); } /** * @notice Completes the pending `SynthToToken` or `TokenToToken` swap by settling the bridging synth and swapping * it to the desired token. Only the owners of the pending swaps can call this function. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @param minAmount the minimum amount of the token to receive - reverts if this amount is not reached * @param deadline the timestamp representing the deadline for this transaction - reverts if deadline is not met */ function completeToToken( uint256 itemId, uint256 swapAmount, uint256 minAmount, uint256 deadline ) external { require(swapAmount != 0, "amount must be greater than 0"); address nftOwner = ownerOf(itemId); require(msg.sender == nftOwner, "must own itemId"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroyClone; if ( swapAmount >= synth.balanceOf(address(pendingToTokenSwap.swapper)) ) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroyClone = true; } // Try swapping the synth to the desired token via the stored swap pool contract // If the external call succeeds, send the token to the owner of token with itemId. (IERC20 tokenTo, uint256 amountOut) = pendingToTokenSwap .swapper .swapSynthToToken( pendingToTokenSwap.swap, synth, getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount, minAmount, deadline, nftOwner ); if (shouldDestroyClone) { pendingToTokenSwap.swapper.destroy(); } emit Settle( msg.sender, itemId, synth, swapAmount, tokenTo, amountOut, shouldDestroyClone ); } // Add the given pending synth settlement struct to the list function _addToPendingSynthSwapList( PendingToSynthSwap memory pendingToSynthSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToSynthSwaps[pendingSwapsLength] = pendingToSynthSwap; return pendingSwapsLength++; } // Add the given pending synth to token settlement struct to the list function _addToPendingSynthToTokenSwapList( PendingToTokenSwap memory pendingToTokenSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToTokenSwaps[pendingSwapsLength] = pendingToTokenSwap; return pendingSwapsLength++; } /** * @notice Calculates the expected amount of the desired synthetic asset the caller will receive after completing * a `TokenToSynth` swap with the given parameters. This calculation does not consider the settlement periods. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @return the expected amount of the desired synth */ function calcTokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount ) external view returns (uint256) { uint8 mediumSynthIndex = getSynthIndex(swap); uint256 expectedMediumSynthAmount = swap.calculateSwap( tokenFromIndex, mediumSynthIndex, tokenInAmount ); bytes32 mediumSynthKey = getSynthKey(swap); IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); return exchangeRates.effectiveValue( mediumSynthKey, expectedMediumSynthAmount, synthOutKey ); } /** * @notice Initiates a cross-asset swap from a token supported in the `swap` pool to any synthetic asset. * The caller will receive an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @param minAmount the amount of the token to swap form * @return ID of the ERC721 token sent to the caller */ function tokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount, uint256 minAmount ) external returns (uint256) { require(tokenInAmount != 0, "amount must be greater than 0"); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending settlement list uint256 itemId = _addToPendingSynthSwapList( PendingToSynthSwap(synthSwapper, synthOutKey) ); pendingSwapType[itemId] = PendingSwapType.TokenToSynth; // Mint an ERC721 token that represents ownership of the pending synth settlement to msg.sender _mint(msg.sender, itemId); // Transfer token from msg.sender IERC20 tokenFrom = swapContracts[address(swap)].tokens[tokenFromIndex]; // revert when token not found in swap pool tokenFrom.safeTransferFrom(msg.sender, address(this), tokenInAmount); tokenInAmount = tokenFrom.balanceOf(address(this)); // Swap the synth to the medium synth uint256 mediumSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenInAmount, 0, block.timestamp ); // Swap synths via Synthetix network IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), mediumSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), mediumSynthAmount, synthOutKey ) >= minAmount, "minAmount not reached" ); // Emit TokenToSynth event with relevant data emit TokenToSynth( msg.sender, itemId, swap, tokenFromIndex, tokenInAmount, synthOutKey ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `SynthToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the `swap` pool composition. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @return the expected amount of the bridging synth and the expected amount of the desired token */ function calcSynthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint8 mediumSynthIndex = getSynthIndex(swap); bytes32 mediumSynthKey = getSynthKey(swap); require(synthInKey != mediumSynthKey, "use normal swap"); uint256 expectedMediumSynthAmount = exchangeRates.effectiveValue( synthInKey, synthInAmount, mediumSynthKey ); return ( expectedMediumSynthAmount, swap.calculateSwap( mediumSynthIndex, tokenToIndex, expectedMediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a synthetic asset to a supported token. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function synthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount, uint256 minMediumSynthAmount ) external returns (uint256) { require(synthInAmount != 0, "amount must be greater than 0"); bytes32 mediumSynthKey = getSynthKey(swap); require( synthInKey != mediumSynthKey, "synth is supported via normal swap" ); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap(synthSwapper, mediumSynthKey, swap, tokenToIndex) ); pendingSwapType[itemId] = PendingSwapType.SynthToToken; // Mint an ERC721 token that represents ownership of the pending synth to token settlement to msg.sender _mint(msg.sender, itemId); // Receive synth from the user and swap it to another synth IERC20 synthFrom = getProxyAddressFromTargetSynthKey(synthInKey); synthFrom.safeTransferFrom(msg.sender, address(this), synthInAmount); synthFrom.safeTransfer(address(synthSwapper), synthInAmount); require( synthSwapper.swapSynth(synthInKey, synthInAmount, mediumSynthKey) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit SynthToToken event with relevant data emit SynthToToken( msg.sender, itemId, swap, synthInKey, synthInAmount, tokenToIndex ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `TokenToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the pool compositions. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @return the expected amount of bridging synth at pre-settlement stage and the expected amount of the desired * token */ function calcTokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint256 firstSynthAmount = swaps[0].calculateSwap( tokenFromIndex, getSynthIndex(swaps[0]), tokenFromAmount ); uint256 mediumSynthAmount = exchangeRates.effectiveValue( getSynthKey(swaps[0]), firstSynthAmount, getSynthKey(swaps[1]) ); return ( mediumSynthAmount, swaps[1].calculateSwap( getSynthIndex(swaps[1]), tokenToIndex, mediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a token in one Saddle pool to one in another. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function tokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minMediumSynthAmount ) external returns (uint256) { // Create a SynthSwapper clone require(tokenFromAmount != 0, "amount must be greater than 0"); SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); bytes32 mediumSynthKey = getSynthKey(swaps[1]); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap( synthSwapper, mediumSynthKey, swaps[1], tokenToIndex ) ); pendingSwapType[itemId] = PendingSwapType.TokenToToken; // Mint an ERC721 token that represents ownership of the pending swap to msg.sender _mint(msg.sender, itemId); // Receive token from the user ISwap swap = swaps[0]; { IERC20 tokenFrom = swapContracts[address(swap)].tokens[ tokenFromIndex ]; tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); } uint256 firstSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenFromAmount, 0, block.timestamp ); // Swap the synth to another synth IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), firstSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), firstSynthAmount, mediumSynthKey ) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit TokenToToken event with relevant data emit TokenToToken( msg.sender, itemId, swaps, tokenFromIndex, tokenFromAmount, tokenToIndex ); return (itemId); } /** * @notice Registers the index and the address of the supported synth from the given `swap` pool. The matching currency key must * be supplied for a successful registration. * @param swap the address of the pool that contains the synth * @param synthIndex the index of the supported synth in the given `swap` pool * @param currencyKey the currency key of the synth in bytes32 form */ function setSynthIndex( ISwap swap, uint8 synthIndex, bytes32 currencyKey ) external { require(synthIndex < MAX_UINT8, "index is too large"); SwapContractInfo storage swapContractInfo = swapContracts[ address(swap) ]; // Check if the pool has already been added require(swapContractInfo.synthIndexPlusOne == 0, "Pool already added"); // Ensure the synth with the same currency key exists at the given `synthIndex` IERC20 synth = swap.getToken(synthIndex); require( ISynth(Proxy(address(synth)).target()).currencyKey() == currencyKey, "currencyKey does not match" ); swapContractInfo.synthIndexPlusOne = synthIndex + 1; swapContractInfo.synthAddress = address(synth); swapContractInfo.synthKey = currencyKey; swapContractInfo.tokens = new IERC20[](0); for (uint8 i = 0; i < MAX_UINT8; i++) { IERC20 token; if (i == synthIndex) { token = synth; } else { try swap.getToken(i) returns (IERC20 token_) { token = token_; } catch { break; } } swapContractInfo.tokens.push(token); token.safeApprove(address(swap), MAX_UINT256); } emit SynthIndex(address(swap), synthIndex, currencyKey, address(synth)); } /** * @notice Returns the index of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the index of the supported synth */ function getSynthIndex(ISwap swap) public view returns (uint8) { uint8 synthIndexPlusOne = swapContracts[address(swap)] .synthIndexPlusOne; require(synthIndexPlusOne > 0, "synth index not found for given pool"); return synthIndexPlusOne - 1; } /** * @notice Returns the address of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the address of the supported synth */ function getSynthAddress(ISwap swap) public view returns (address) { address synthAddress = swapContracts[address(swap)].synthAddress; require( synthAddress != address(0), "synth addr not found for given pool" ); return synthAddress; } /** * @notice Returns the currency key of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the currency key of the supported synth */ function getSynthKey(ISwap swap) public view returns (bytes32) { bytes32 synthKey = swapContracts[address(swap)].synthKey; require(synthKey != 0x0, "synth key not found for given pool"); return synthKey; } /** * @notice Updates the stored address of the `EXCHANGER` contract. When the Synthetix team upgrades their protocol, * a new Exchanger contract is deployed. This function manually updates the stored address. */ function updateExchangerCache() public { exchanger = IExchanger(SYNTHETIX_RESOLVER.getAddress(EXCHANGER_NAME)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @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 (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } pragma solidity >=0.4.24; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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. */ library EnumerableSet { // 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; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. 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] = toDeleteIndex + 1; // All indexes are 1-based // 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // 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); } // 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)))); } // 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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SwapMigrator * @notice This contract is responsible for migrating old USD pool liquidity to the new ones. * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract SwapMigrator { using SafeERC20 for IERC20; struct MigrationData { address oldPoolAddress; IERC20 oldPoolLPTokenAddress; address newPoolAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } MigrationData public usdPoolMigrationData; address public owner; uint256 private constant MAX_UINT256 = 2**256 - 1; /** * @notice Sets the storage variables and approves tokens to be used by the old and new swap contracts * @param usdData_ MigrationData struct with information about old and new USD pools * @param owner_ owner that is allowed to call the `rescue()` function */ constructor(MigrationData memory usdData_, address owner_) public { // Approve old USD LP Token to be used by the old USD pool usdData_.oldPoolLPTokenAddress.approve( usdData_.oldPoolAddress, MAX_UINT256 ); // Approve USD tokens to be used by the new USD pool for (uint256 i = 0; i < usdData_.underlyingTokens.length; i++) { usdData_.underlyingTokens[i].safeApprove( usdData_.newPoolAddress, MAX_UINT256 ); } // Set storage variables usdPoolMigrationData = usdData_; owner = owner_; } /** * @notice Migrates old USD pool's LPToken to the new pool * @param amount Amount of old LPToken to migrate * @param minAmount Minimum amount of new LPToken to receive */ function migrateUSDPool(uint256 amount, uint256 minAmount) external returns (uint256) { // Transfer old LP token from the caller usdPoolMigrationData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool and add them to the new pool uint256[] memory amounts = ISwap(usdPoolMigrationData.oldPoolAddress) .removeLiquidity( amount, new uint256[](usdPoolMigrationData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(usdPoolMigrationData.newPoolAddress) .addLiquidity(amounts, minAmount, MAX_UINT256); // Transfer new LP Token to the caller usdPoolMigrationData.newPoolLPTokenAddress.safeTransfer( msg.sender, mintedAmount ); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external { require(msg.sender == owner, "is not owner"); token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // Generalized and adapted from https://github.com/k06a/Unipool 🙇 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public totalSupply; IERC20 public stakedToken; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); /** * @notice Creates a new StakeableTokenWrapper with given `_stakedToken` address * @param _stakedToken address of a token that will be used to stake */ constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } /** * @notice Read how much `account` has staked in this contract * @param account address of an account * @return amount of total staked ERC20(this.stakedToken) by `account` */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @notice Stakes given `amount` in this contract * @param amount amount of ERC20(this.stakedToken) to stake */ function stake(uint256 amount) external { require(amount != 0, "amount == 0"); totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /** * @notice Withdraws given `amount` from this contract * @param amount amount of ERC20(this.stakedToken) to withdraw */ function withdraw(uint256 amount) external { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IFlashLoanReceiver.sol"; import "../interfaces/ISwapFlashLoan.sol"; import "hardhat/console.sol"; contract FlashLoanBorrowerExample is IFlashLoanReceiver { using SafeMath for uint256; // Typical executeOperation function should do the 3 following actions // 1. Check if the flashLoan was successful // 2. Do actions with the borrowed tokens // 3. Repay the debt to the `pool` function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external override { // 1. Check if the flashLoan was valid require( IERC20(token).balanceOf(address(this)) >= amount, "flashloan is broken?" ); // 2. Do actions with the borrowed token bytes32 paramsHash = keccak256(params); if (paramsHash == keccak256(bytes("dontRepayDebt"))) { return; } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) { ISwapFlashLoan(pool).addLiquidity( new uint256[](0), 0, block.timestamp ); } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) { ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidity")) ) { ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken")) ) { ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now); } // 3. Payback debt uint256 totalDebt = amount.add(fee); IERC20(token).transfer(pool, totalDebt); } function flashLoan( ISwapFlashLoan swap, IERC20 token, uint256 amount, bytes memory params ) external { swap.flashLoan(address(this), token, amount, params); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ISwap.sol"; interface ISwapFlashLoan is ISwap { function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../interfaces/ISwap.sol"; import "hardhat/console.sol"; contract TestSwapReturnValues { using SafeMath for uint256; ISwap public swap; IERC20 public lpToken; uint8 public n; uint256 public constant MAX_INT = 2**256 - 1; constructor( ISwap swapContract, IERC20 lpTokenContract, uint8 numOfTokens ) public { swap = swapContract; lpToken = lpTokenContract; n = numOfTokens; // Pre-approve tokens for (uint8 i; i < n; i++) { swap.getToken(i).approve(address(swap), MAX_INT); } lpToken.approve(address(swap), MAX_INT); } function test_swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) public { uint256 balanceBefore = swap.getToken(tokenIndexTo).balanceOf( address(this) ); uint256 returnValue = swap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, block.timestamp ); uint256 balanceAfter = swap.getToken(tokenIndexTo).balanceOf( address(this) ); console.log( "swap: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "swap()'s return value does not match received amount" ); } function test_addLiquidity(uint256[] calldata amounts, uint256 minToMint) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.addLiquidity(amounts, minToMint, MAX_INT); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "addLiquidity: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "addLiquidity()'s return value does not match minted amount" ); } function test_removeLiquidity(uint256 amount, uint256[] memory minAmounts) public { uint256[] memory balanceBefore = new uint256[](n); uint256[] memory balanceAfter = new uint256[](n); for (uint8 i = 0; i < n; i++) { balanceBefore[i] = swap.getToken(i).balanceOf(address(this)); } uint256[] memory returnValue = swap.removeLiquidity( amount, minAmounts, MAX_INT ); for (uint8 i = 0; i < n; i++) { balanceAfter[i] = swap.getToken(i).balanceOf(address(this)); console.log( "removeLiquidity: Expected %s, got %s", balanceAfter[i].sub(balanceBefore[i]), returnValue[i] ); require( balanceAfter[i].sub(balanceBefore[i]) == returnValue[i], "removeLiquidity()'s return value does not match received amounts of tokens" ); } } function test_removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount ) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.removeLiquidityImbalance( amounts, maxBurnAmount, MAX_INT ); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "removeLiquidityImbalance: Expected %s, got %s", balanceBefore.sub(balanceAfter), returnValue ); require( returnValue == balanceBefore.sub(balanceAfter), "removeLiquidityImbalance()'s return value does not match burned lpToken amount" ); } function test_removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) public { uint256 balanceBefore = swap.getToken(tokenIndex).balanceOf( address(this) ); uint256 returnValue = swap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, MAX_INT ); uint256 balanceAfter = swap.getToken(tokenIndex).balanceOf( address(this) ); console.log( "removeLiquidityOneToken: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "removeLiquidityOneToken()'s return value does not match received token amount" ); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0x2b7a5a5923eca5c00c6572cf3e8e08384f563f93#code pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPTokenGuarded.sol"; import "../MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsGuarded { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPTokenGuarded lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculation in addLiquidity function // to avoid stack too deep error struct AddLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct RemoveLiquidityImbalanceInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(Swap storage self) external view returns (uint256) { return _getA(self); } /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Calculates and returns A based on the ramp settings * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive and the associated swap fee */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) public view returns (uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = _xp(self)[tokenIndex] .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns (uint256, uint256) { require( tokenIndex < self.pooledTokens.length, "Token index out of range" ); // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(self.lpToken.totalSupply())); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA.mul(s).div(A_PRECISION).add(dP.mul(numTokens)).mul(d).div( nA.sub(A_PRECISION).mul(d).div(A_PRECISION).add( numTokens.add(1).mul(dP) ) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @param self Swap struct to read from * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), _getAPrecise(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @param balances array of balances to scale * @return balances array "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory balances) internal view returns (uint256[] memory) { return _xp(balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); uint256 supply = self.lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(ERC20(self.lpToken).decimals())).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param self Swap struct to read from * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 a = _getAPrecise(self); uint256 d = getD(xp, a); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(a); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, account, amount); } function _calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(feeAdjustedAmount).div( totalSupply ); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over 4 weeks. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 numTokens = self.pooledTokens.length; uint256 a = _getAPrecise(self); uint256 d0 = getD(_xp(self, self.balances), a); uint256[] memory balances1 = self.balances; for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(self, balances1), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param self Swap struct to read from */ function _feePerToken(Swap storage self) internal view returns (uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4) ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { require( dx <= self.pooledTokens[tokenIndexFrom].balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = self.pooledTokens[tokenIndexFrom].balanceOf( address(this) ); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx ); // Use the actual transferred amount for AMM math uint256 transferredDx = self .pooledTokens[tokenIndexFrom] .balanceOf(address(this)) .sub(beforeBalance); (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param merkleProof bytes32 array that will be used to prove the existence of the caller's address in the list of * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint, bytes32[] calldata merkleProof ) external returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state AddLiquidityInfo memory v = AddLiquidityInfo(0, 0, 0, 0); if (self.lpToken.totalSupply() != 0) { v.d0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = self.pooledTokens[i].balanceOf( address(this) ); self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = self.pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change v.preciseA = _getAPrecise(self); v.d1 = getD(_xp(self, newBalances), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; if (self.lpToken.totalSupply() != 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(self, newBalances), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (self.lpToken.totalSupply() == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(self.lpToken.totalSupply()).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint, merkleProof); emit AddLiquidity( msg.sender, amounts, fees, v.d1, self.lpToken.totalSupply() ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); } function _updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) internal { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory amounts = _calculateRemoveLiquidity( self, msg.sender, amount ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = self.balances[i].sub(amounts[i]); self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, self.lpToken.totalSupply()); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require( tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf" ); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( 0, 0, 0, 0 ); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 feePerToken = _feePerToken(self); uint256[] memory balances1 = self.balances; v.preciseA = _getAPrecise(self); v.d0 = getD(_xp(self), v.preciseA); for (uint256 i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(self, balances1), v.preciseA); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(self, balances1), v.preciseA); uint256 tokenAmount = v.d0.sub(v.d2).mul(tokenSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, tokenSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0xC28DF698475dEC994BE00C9C9D8658A548e6304F#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ISwapGuarded.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. */ contract LPTokenGuarded is ERC20Burnable, Ownable { using SafeMath for uint256; // Address of the swap contract that owns this LP token. When a user adds liquidity to the swap contract, // they receive a proportionate amount of this LPToken. ISwapGuarded public swap; // Maps user account to total number of LPToken minted by them. Used to limit minting during guarded release phase mapping(address => uint256) public mintedAmounts; /** * @notice Deploys LPToken contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); swap = ISwapGuarded(_msgSender()); } /** * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply * and the maximum number of the tokens that a single account can mint are limited. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored. */ function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); // If the pool is in the guarded launch phase, the following checks are done to restrict deposits. // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the // allowlist contract. If the account has been already verified, merkleProof is ignored. // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. // 3. Limit the total supply of this LPToken as defined by the allowlist contract. if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that swap.updateUserWithdrawFees are called everytime. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); swap.updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapGuarded { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/IAllowlist.sol"; /** * @title Allowlist * @notice This contract is a registry holding information about how much each swap contract should * contain upto. Swap.sol will rely on this contract to determine whether the pool cap is reached and * also whether a user's deposit limit is reached. */ contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; // Represents the root node of merkle tree containing a list of eligible addresses bytes32 public merkleRoot; // Maps pool address -> maximum total supply mapping(address => uint256) private poolCaps; // Maps pool address -> maximum amount of pool token mintable per account mapping(address => uint256) private accountLimits; // Maps account address -> boolean value indicating whether it has been checked and verified against the merkle tree mapping(address => bool) private verified; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); event NewMerkleRoot(bytes32 merkleRoot); /** * @notice Creates this contract and sets the PoolCap of 0x0 with uint256(0x54dd1e) for * crude checking whether an address holds this contract. * @param merkleRoot_ bytes32 that represent a merkle root node. This is generated off chain with the list of * qualifying addresses. */ constructor(bytes32 merkleRoot_) public { merkleRoot = merkleRoot_; // This value will be used as a way of crude checking whether an address holds this Allowlist contract // Value 0x54dd1e has no inherent meaning other than it is arbitrary value that checks for // user error. poolCaps[address(0x0)] = uint256(0x54dd1e); emit PoolCap(address(0x0), uint256(0x54dd1e)); emit NewMerkleRoot(merkleRoot_); } /** * @notice Returns the max mintable amount of the lp token per account in given pool address. * @param poolAddress address of the pool * @return max mintable amount of the lp token per account */ function getPoolAccountLimit(address poolAddress) external view override returns (uint256) { return accountLimits[poolAddress]; } /** * @notice Returns the maximum total supply of the pool token for the given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view override returns (uint256) { return poolCaps[poolAddress]; } /** * @notice Returns true if the given account's existence has been verified against any of the past or * the present merkle tree. Note that if it has been verified in the past, this function will return true * even if the current merkle tree does not contain the account. * @param account the address to check if it has been verified * @return a boolean value representing whether the account has been verified in the past or the present merkle tree */ function isAccountVerified(address account) external view returns (bool) { return verified[account]; } /** * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node * stored in this contract. Pools should use this function to check if the given address qualifies for depositing. * If the given account has already been verified with the correct merkleProof, this function will return true when * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function * with an incorrect merkleProof. * @param account address to confirm its existence in the merkle tree * @param merkleProof data that is used to prove the existence of given parameters. This is generated * during the creation of the merkle tree. Users should retrieve this data off-chain. * @return a boolean value that corresponds to whether the address with the proof has been verified in the past * or if they exist in the current merkle tree. */ function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { // Verify the account exists in the merkle tree via the MerkleProof library bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; } // ADMIN FUNCTIONS /** * @notice Sets the account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit the max number of the pool token a single user can mint */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Sets the max total supply of LPToken for the given pool address * @param poolAddress address of the pool * @param poolCap the max total supply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } /** * @notice Updates the merkle root that is stored in this contract. This can only be called by * the owner. If more addresses are added to the list, a new merkle tree and a merkle root node should be generated, * and merkleRoot should be updated accordingly. * @param merkleRoot_ a new merkle root node that contains a list of deposit allowed addresses */ function updateMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; emit NewMerkleRoot(merkleRoot_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtilsGuarded.sol"; import "../MathUtils.sol"; import "./Allowlist.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapGuarded is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtilsGuarded for SwapUtilsGuarded.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsGuarded.sol SwapUtilsGuarded.Swap public swapStorage; // Address to allowlist contract that holds information about maximum totaly supply of lp tokens // and maximum mintable amount per user address. As this is immutable, this will become a constant // after initialization. IAllowlist private immutable allowlist; // Boolean value that notates whether this pool is guarded or not. When isGuarded is true, // addLiquidity function will be restricted by limits defined in allowlist contract. bool private guarded = true; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Deploys this Swap contract with given parameters as default * values. This will also deploy a LPToken that represents users * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsGuarded.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsGuarded.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee, _allowlist parameters require(_a < SwapUtilsGuarded.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsGuarded.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsGuarded.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsGuarded.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); require( _allowlist.getPoolCap(address(0x0)) == uint256(0x54dd1e), "Allowlist check failed" ); // Initialize swapStorage struct swapStorage.lpToken = new LPTokenGuarded( lpTokenName, lpTokenSymbol, SwapUtilsGuarded.POOL_PRECISION_DECIMALS ); swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.futureA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.initialATime = 0; swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; // Initialize variables related to guarding the initial deposits allowlist = _allowlist; guarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) external view returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Reads and returns the address of the allowlist that is set during deployment of this contract * @return the address of the allowlist contract casted to the IAllowlist interface */ function getAllowlist() external view returns (IAllowlist) { return allowlist; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with given amounts during guarded launch phase. Only users * with valid address and proof can successfully call this function. When this function is called * after the guarded release phase is over, the merkleProof is ignored. * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @param merkleProof data generated when constructing the allowlist merkle tree. Users can * get this data off chain. Even if the address is in the allowlist, users must include * a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, * this parameter is ignored. * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint, merkleProof); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } /** * @notice Disables the guarded launch phase, removing any limits on deposit amounts and addresses */ function disableGuard() external onlyOwner { guarded = false; } /** * @notice Reads and returns current guarded status of the pool * @return guarded_ boolean value indicating whether the deposits should be guarded */ function isGuarded() external view returns (bool) { return guarded; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { _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 make 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 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable, Pausable { /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { Pausable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Generic ERC20 token * @notice This contract simulates a generic ERC20 token that is mintable and burnable. */ contract GenericERC20 is ERC20, Ownable { /** * @notice Deploy this contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); } /** * @notice Mints given amount of tokens to recipient * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] tokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolToken; try ISwap(oldPoolAddress).getToken(i) returns (IERC20 token) { oldPoolToken = address(token); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns (IERC20 token) { require( oldPoolToken == address(token) && oldPoolToken == address(mData.tokens[i]), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolToken == address(0) && i == mData.tokens.length, "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.approve(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.tokens.length; i++) { mData.tokens[i].safeApprove(mData.newPoolAddress, 0); mData.tokens[i].safeApprove(mData.newPoolAddress, MAX_UINT256); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.tokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto // WARNING!!! // Combining BoringBatchable with msg.value can cause double spending issues // https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/ contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Swap.sol"; import "./MetaSwapUtils.sol"; /** * @title MetaSwap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT], then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * Note that when interacting with MetaSwap, users cannot deposit or withdraw via underlying tokens. In that case, * `MetaSwapDeposit.sol` can be additionally deployed to allow interacting with unwrapped representations of the tokens. * * @dev Most of the logic is stored as a library `MetaSwapUtils` for the sake of reducing contract's * deployment size. */ contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../MathUtils.sol"; contract TestMathUtils { using MathUtils for uint256; function difference(uint256 a, uint256 b) public pure returns (uint256) { return a.difference(b); } function within1(uint256 a, uint256 b) public pure returns (bool) { return a.within1(b); } }
Get the virtual price, to help calculate profit return the virtual price, scaled to the POOL_PRECISION_DECIMALS/
function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); }
970,659
./partial_match/44787/0xA2Cf1Fde33fcfef01cd52524Fe0e4a328A7ECD6E/sources/contracts/DirectPayments/ProvableNFT.sol
Mint a new NFT with the given URI and data hash. Requirements: - The caller must have the `Manager` role. Emits a {Transfer} event and a {URI} event. _to The address that will receive the minted NFT. _uri The URI for the NFT's metadata. _nftDataHash The hash of the NFT's data. return tokenId ID of the newly minted NFT./
function mint(address _to, string memory _uri, bytes32 _nftDataHash) public onlyManager(0) returns (uint256 tokenId) { }
16,953,573
./full_match/1/0x46515D7961ec45Fcfe35beAA43b4f618fF2Bd82E/sources/@gearbox-protocol/core-v2/contracts/credit/CreditConfigurator.sol
Upgrades the Credit Facade corresponding to the Credit Manager _creditFacade address of the new CreditFacade migrateParams Whether the previous CreditFacade's parameter need to be copied Checks that the Credit Facade is actually changed, to avoid any redundant actions and events
{ function upgradeCreditFacade(address _creditFacade, bool migrateParams) external if (_creditFacade == address(creditFacade())) { return; } uint128 limitPerBlock, bool isIncreaseDebtFobidden, uint40 expirationDate ) = creditFacade().params(); (uint128 minBorrowedAmount, uint128 maxBorrowedAmount) = creditFacade() .limits(); address[] memory upgradeableContracts = creditFacade() .upgradeableContractsList(); bool expirable = creditFacade().expirable(); ( if (migrateParams) { for (uint256 i; i < upgradeableContracts.length; ) { _addContractToUpgradeable(upgradeableContracts[i]); unchecked { ++i; } } if (migrateParams) { for (uint256 i; i < upgradeableContracts.length; ) { _addContractToUpgradeable(upgradeableContracts[i]); unchecked { ++i; } } if (migrateParams) { for (uint256 i; i < upgradeableContracts.length; ) { _addContractToUpgradeable(upgradeableContracts[i]); unchecked { ++i; } } } }
17,128,685
./full_match/4/0x4e87720bE34A1a2c810b939dbC66E3FCe3e02513/sources/contracts/MeetBOB.sol
set the base token uri _baseTokenURI the new base token uri/
function setBaseURI(string memory _baseTokenURI) public onlyTeam { baseTokenURI = _baseTokenURI; }
12,299,816
pragma solidity ^0.4.4; contract TodoList { enum Priority { Low, Medium, High } struct Item { Priority priority; string name; uint deadline; bool done; } address public owner; mapping(string => uint) itemIndices; Item[] public items; modifier ownerOnly() { require(msg.sender == owner); _; } modifier itemExists(string _name) { require(itemIndices[_name] > 0); _; } function TodoList() payable { owner = msg.sender; } function newItem(string name, uint deadline, Priority priority) external ownerOnly returns (bool) { // name has to be given if(bytes(name).length == 0) { return false; } // can't be in the past if(deadline < now) { return false; } // can't already exist if(itemIndices[name] > 0) { return false; } // register /new/ item var item = Item(priority, name, deadline, false); itemIndices[name] = items.push(item); return true; } // update /existing/ item function updateItem(string name, bool done) external ownerOnly itemExists(name) { var index = itemIndices[name] - 1; items[index].done = done; } function() payable { // TODO: receive tip } }
update /existing/ item
function updateItem(string name, bool done) external ownerOnly itemExists(name) { var index = itemIndices[name] - 1; items[index].done = done; }
7,227,248
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol
Changes the quorum numerator. Emits a {QuorumNumeratorUpdated} event. Requirements: - New numerator must be smaller or equal to the denominator./
function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { uint256 denominator = quorumDenominator(); if (newQuorumNumerator > denominator) { revert GovernorInvalidQuorumFraction(newQuorumNumerator, denominator); } uint256 oldQuorumNumerator = quorumNumerator(); _quorumNumeratorHistory.push(clock(), SafeCast.toUint208(newQuorumNumerator)); emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); }
8,083,845
/** *Submitted for verification at Etherscan.io on 2022-02-19 */ /* __ __ _ | \/ | \| | | |\/| | |) | |__ |_| |__/|___| Million Dollar Living Website: https://mdldao.eth.link Twitter: https://twitter.com/MDLDAO Discord: https://discord.gg/7hvY8fz2VA */ //SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } pragma solidity >=0.6.0 <0.8.0; interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https: * 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); } pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, 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) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ 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 Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @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); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https: */ interface IERC721Metadata is IERC721 { /** * @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); } pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https: */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } pragma solidity >=0.6.2 <0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https: * 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: * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https: */ 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: * * 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); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https: * 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 { * * using EnumerableSet for EnumerableSet.AddressSet; * * * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { struct Set { bytes32[] _values; 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); 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) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._indexes[lastvalue] = toDeleteIndex + 1; set._values.pop(); 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } 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); } 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)))); } 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)); } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https: * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * * using EnumerableMap for EnumerableMap.UintToAddressMap; * * * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { MapEntry[] _entries; mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { map._entries.push(MapEntry({ _key: key, _value: value })); map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; MapEntry storage lastEntry = map._entries[lastIndex]; map._entries[toDeleteIndex] = lastEntry; map._indexes[lastEntry._key] = toDeleteIndex + 1; map._entries.pop(); delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); return (true, map._entries[keyIndex - 1]._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); return map._entries[keyIndex - 1]._value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); return map._entries[keyIndex - 1]._value; } struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https: */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; mapping (address => EnumerableSet.UintSet) private _holderTokens; EnumerableMap.UintToAddressMap private _tokenOwners; mapping (uint256 => address) private _tokenApprovals; mapping (address => mapping (address => bool)) private _operatorApprovals; string private _name; string private _symbol; mapping (uint256 => string) private _tokenURIs; string private _baseURI; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @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 (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * 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, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { uint256 _value; } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity >=0.6.0 <0.7.0; contract NFTSticker is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter public _tokenIds; mapping (address => bool) public hasMinted; mapping (uint256 => string) public stickerText; uint256 public supplyLimit = 999; bool public mintEnabled = false; string public _contractURI; modifier ownsToken(uint256 _tokenId){ require(ownerOf(_tokenId) == msg.sender, "You don't own this token!"); _; } constructor(string memory _contractMeta) public ERC721("ETHDenver2022", "ETHD"){ _contractURI = _contractMeta; } function mintSticker(string memory _text) public{ require(mintEnabled == true, "Mint is not yet enabled"); require(_tokenIds.current() < supplyLimit, "All out! :("); require(hasMinted[msg.sender] != true, "Don't get greedy!"); hasMinted[msg.sender] = true; uint256 id = _tokenIds.current(); string memory string_id = id.toString(); _mint(msg.sender, id); _setTokenURI(id, string_id); stickerText[id] = _text; _tokenIds.increment(); } function changeSticker(uint256 _tokenId, string memory _text) public ownsToken(_tokenId){ stickerText[_tokenId] = _text; } function mintSwitch() public onlyOwner{ mintEnabled = !mintEnabled; } function changeURI(string memory url) public onlyOwner { _setBaseURI(url); } function contractURI() public view returns (string memory) { return _contractURI; } function changeContractURI(string memory url) public onlyOwner { _contractURI = url; } }
See {IERC721Enumerable-totalSupply}./
function totalSupply() public view virtual override returns (uint256) { return _tokenOwners.length(); }
10,962,105
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "../external/ERC721PresetMinterPauserAutoId.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/ISeniorPool.sol"; import "../interfaces/IStakingRewards.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../library/StakingRewardsVesting.sol"; // solhint-disable-next-line max-states-count contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20withDec; using SafeERC20 for IERC20; using ConfigHelper for GoldfinchConfig; using StakingRewardsVesting for StakingRewardsVesting.Rewards; enum LockupPeriod { SixMonths, TwelveMonths, TwentyFourMonths } enum StakedPositionType { Fidu, CurveLP } struct StakedPosition { // @notice Staked amount denominated in `stakingToken().decimals()` uint256 amount; // @notice Struct describing rewards owed with vesting StakingRewardsVesting.Rewards rewards; // @notice Multiplier applied to staked amount when locking up position uint256 leverageMultiplier; // @notice Time in seconds after which position can be unstaked uint256 lockedUntil; // @notice Type of the staked position StakedPositionType positionType; // @notice Multiplier applied to staked amount to denominate in `baseStakingToken().decimals()` // @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1. // If you need this field, use `safeEffectiveMultiplier()`, which correctly handles old staked positions. uint256 unsafeEffectiveMultiplier; // @notice Exchange rate applied to staked amount to denominate in `baseStakingToken().decimals()` // @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1. // If you need this field, use `safeBaseTokenExchangeRate()`, which correctly handles old staked positions. uint256 unsafeBaseTokenExchangeRate; } /* ========== EVENTS =================== */ event RewardsParametersUpdated( address indexed who, uint256 targetCapacity, uint256 minRate, uint256 maxRate, uint256 minRateAtPercent, uint256 maxRateAtPercent ); event TargetCapacityUpdated(address indexed who, uint256 targetCapacity); event VestingScheduleUpdated(address indexed who, uint256 vestingLength); event MinRateUpdated(address indexed who, uint256 minRate); event MaxRateUpdated(address indexed who, uint256 maxRate); event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent); event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent); event EffectiveMultiplierUpdated(address indexed who, StakedPositionType positionType, uint256 multiplier); /* ========== STATE VARIABLES ========== */ uint256 private constant MULTIPLIER_DECIMALS = 1e18; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant ZAPPER_ROLE = keccak256("ZAPPER_ROLE"); GoldfinchConfig public config; /// @notice The block timestamp when rewards were last checkpointed uint256 public lastUpdateTime; /// @notice Accumulated rewards per token at the last checkpoint uint256 public accumulatedRewardsPerToken; /// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()` uint256 public rewardsAvailable; /// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken; /// @notice Desired supply of staked tokens. The reward rate adjusts in a range /// around this value to incentivize staking or unstaking to maintain it. uint256 public targetCapacity; /// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public minRate; /// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public maxRate; /// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public maxRateAtPercent; /// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public minRateAtPercent; /// @notice The duration in seconds over which rewards vest uint256 public vestingLength; /// @dev Supply of staked tokens, denominated in `stakingToken().decimals()` /// @dev Note that due to the use of `unsafeBaseTokenExchangeRate` and `unsafeEffectiveMultiplier` on /// a StakedPosition, the sum of `amount` across all staked positions will not necessarily /// equal this `totalStakedSupply` value; the purpose of the base token exchange rate and /// the effective multiplier is to enable calculation of an "effective amount" -- which is /// what this `totalStakedSupply` represents the sum of. uint256 public totalStakedSupply; /// @dev UNUSED (definition kept for storage slot) uint256 private totalLeveragedStakedSupply; /// @dev UNUSED (definition kept for storage slot) mapping(LockupPeriod => uint256) private leverageMultipliers; /// @dev NFT tokenId => staked position mapping(uint256 => StakedPosition) public positions; /// @dev A mapping of staked position types to multipliers used to denominate positions /// in `baseStakingToken()`. Represented with `MULTIPLIER_DECIMALS`. mapping(StakedPositionType => uint256) private effectiveMultipliers; // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS"); __ERC721Pausable_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); config = _config; vestingLength = 365 days; } function initZapperRole() external onlyAdmin { _setRoleAdmin(ZAPPER_ROLE, OWNER_ROLE); } /* ========== VIEWS ========== */ /// @notice Returns the staked balance of a given position token. /// @dev The value returned is the bare amount, not the effective amount. The bare amount represents /// the number of tokens the user has staked for a given position. /// @param tokenId A staking position token ID /// @return Amount of staked tokens denominated in `stakingToken().decimals()` function stakedBalanceOf(uint256 tokenId) external view returns (uint256) { return positions[tokenId].amount; } /// @notice The address of the token being disbursed as rewards function rewardsToken() internal view returns (IERC20withDec) { return config.getGFI(); } /// @notice The address of the token that is staked for a given position type function stakingToken(StakedPositionType positionType) internal view returns (IERC20) { if (positionType == StakedPositionType.CurveLP) { return IERC20(config.getFiduUSDCCurveLP().token()); } return config.getFidu(); } /// @notice The address of the base token used to denominate staking rewards function baseStakingToken() internal view returns (IERC20withDec) { return config.getFidu(); } /// @notice The additional rewards earned per token, between the provided time and the last /// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited /// by the amount of rewards that are available for distribution; if there aren't enough /// rewards in the balance of this contract, then we shouldn't be giving them out. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function _additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) { /// @dev IT: Invalid end time for range require(time >= lastUpdateTime, "IT"); if (totalStakedSupply == 0) { return 0; } uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable); uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingAndRewardsTokenMantissa()).div( totalStakedSupply ); // Prevent perverse, infinite-mint scenario where totalStakedSupply is a fraction of a token. // Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number // of tokens that should have been disbursed in the elapsed time. The attacker would need to find // a way to reduce totalStakedSupply while maintaining a staked position of >= 1. // See: https://twitter.com/Mudit__Gupta/status/1409463917290557440 if (additionalRewardsPerToken > rewardsSinceLastUpdate) { return 0; } return additionalRewardsPerToken; } /// @notice Returns accumulated rewards per token up to the current block timestamp /// @return Amount of rewards denominated in `rewardsToken().decimals()` function rewardPerToken() public view returns (uint256) { return accumulatedRewardsPerToken.add(_additionalRewardsPerTokenSinceLastUpdate(block.timestamp)); } /// @notice Returns rewards earned by a given position token from its last checkpoint up to the /// current block timestamp. /// @param tokenId A staking position token ID /// @return Amount of rewards denominated in `rewardsToken().decimals()` function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) { return _positionToEffectiveAmount(positions[tokenId]) .mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])) .div(stakingAndRewardsTokenMantissa()); } function totalOptimisticClaimable(address owner) external view returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < balanceOf(owner); i++) { uint256 tokenId = tokenOfOwnerByIndex(owner, i); result = result.add(optimisticClaimable(tokenId)); } return result; } function optimisticClaimable(uint256 tokenId) public view returns (uint256) { return earnedSinceLastCheckpoint(tokenId).add(claimableRewards(tokenId)); } /// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into /// account vesting schedule. /// @return rewards Amount of rewards denominated in `rewardsToken()` function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) { return positions[tokenId].rewards.claimable(); } /// @notice Returns the rewards that will have vested for some position with the given params. /// @return rewards Amount of rewards denominated in `rewardsToken()` function totalVestedAt( uint256 start, uint256 end, uint256 time, uint256 grantedAmount ) external pure returns (uint256 rewards) { return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount); } /// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second function rewardRate() internal view returns (uint256) { // The reward rate can be thought of as a piece-wise function: // // let intervalStart = (maxRateAtPercent * targetCapacity), // intervalEnd = (minRateAtPercent * targetCapacity), // x = totalStakedSupply // in // if x < intervalStart // y = maxRate // if x > intervalEnd // y = minRate // else // y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart) // // See an example here: // solhint-disable-next-line max-line-length // https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D // // In that example: // maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100 uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 x = totalStakedSupply; // Subsequent computation would overflow if (intervalEnd <= intervalStart) { return 0; } if (x < intervalStart) { return maxRate; } if (x > intervalEnd) { return minRate; } return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart))); } function _positionToEffectiveAmount(StakedPosition storage position) internal view returns (uint256) { return toEffectiveAmount(position.amount, safeBaseTokenExchangeRate(position), safeEffectiveMultiplier(position)); } /// @notice Calculates the effective amount given the amount, (safe) base token exchange rate, /// and (safe) effective multiplier for a position /// @param amount The amount of staked tokens /// @param safeBaseTokenExchangeRate The (safe) base token exchange rate. See @dev comment below. /// @param safeEffectiveMultiplier The (safe) effective multiplier. See @dev comment below. /// @dev Do NOT pass in the unsafeBaseTokenExchangeRate or unsafeEffectiveMultiplier in storage. /// Convert it to safe values using `safeBaseTokenExchangeRate()` and `safeEffectiveMultiplier()` // before calling this function. function toEffectiveAmount( uint256 amount, uint256 safeBaseTokenExchangeRate, uint256 safeEffectiveMultiplier ) internal pure returns (uint256) { // Both the exchange rate and the effective multiplier are denominated in MULTIPLIER_DECIMALS return amount.mul(safeBaseTokenExchangeRate).mul(safeEffectiveMultiplier).div(MULTIPLIER_DECIMALS).div( MULTIPLIER_DECIMALS ); } /// @dev We overload the responsibility of this function -- i.e. returning a value that can be /// used for both the `stakingToken()` mantissa and the `rewardsToken()` mantissa --, rather than have /// multiple distinct functions for that purpose, in order to reduce contract size. We rely on a unit /// test to ensure that the tokens' mantissas are indeed equal and therefore that this approach works. function stakingAndRewardsTokenMantissa() internal view returns (uint256) { return uint256(10)**baseStakingToken().decimals(); } /// @notice The amount of rewards currently being earned per token per second. This amount takes into /// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not. /// This function is intended for public consumption, to know the rate at which rewards are being /// earned, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function currentEarnRatePerToken() public view returns (uint256) { uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp; uint256 elapsed = time.sub(lastUpdateTime); return _additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed); } /// @notice The amount of rewards currently being earned per second, for a given position. This function /// is intended for public consumption, to know the rate at which rewards are being earned /// for a given position, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) { return currentEarnRatePerToken().mul(_positionToEffectiveAmount(positions[tokenId])).div( stakingAndRewardsTokenMantissa() ); } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an /// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake` /// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule. /// @dev This function checkpoints rewards. /// @param amount The amount of `stakingToken()` to stake /// @param positionType The type of the staked position function stake(uint256 amount, StakedPositionType positionType) external nonReentrant whenNotPaused updateReward(0) { _stake(msg.sender, msg.sender, amount, positionType); } /// @notice Deposit to SeniorPool and stake your shares in the same transaction. /// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit /// will be staked. function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) { /// @dev GL: This address has not been go-listed require(isGoListed(), "GL"); IERC20withDec usdc = config.getUSDC(); usdc.safeTransferFrom(msg.sender, address(this), usdcAmount); ISeniorPool seniorPool = config.getSeniorPool(); usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount); uint256 fiduAmount = seniorPool.deposit(usdcAmount); uint256 tokenId = _stake(address(this), msg.sender, fiduAmount, StakedPositionType.Fidu); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount); } /// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits /// this contract to move funds on behalf of the user. /// @param usdcAmount The amount of USDC to deposit /// @param v secp256k1 signature component /// @param r secp256k1 signature component /// @param s secp256k1 signature component function depositWithPermitAndStake( uint256 usdcAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s); depositAndStake(usdcAmount); } /// @notice Deposits FIDU and USDC to Curve on behalf of the user. The Curve LP tokens will be minted /// directly to the user's address /// @param fiduAmount The amount of FIDU to deposit /// @param usdcAmount The amount of USDC to deposit function depositToCurve(uint256 fiduAmount, uint256 usdcAmount) external nonReentrant whenNotPaused { uint256 curveLPTokens = _depositToCurve(msg.sender, msg.sender, fiduAmount, usdcAmount); emit DepositedToCurve(msg.sender, fiduAmount, usdcAmount, curveLPTokens); } function depositToCurveAndStake(uint256 fiduAmount, uint256 usdcAmount) external { depositToCurveAndStakeFrom(msg.sender, fiduAmount, usdcAmount); } /// @notice Deposit to FIDU and USDC into the Curve LP, and stake your Curve LP tokens in the same transaction. /// @param fiduAmount The amount of FIDU to deposit /// @param usdcAmount The amount of USDC to deposit function depositToCurveAndStakeFrom( address nftRecipient, uint256 fiduAmount, uint256 usdcAmount ) public nonReentrant whenNotPaused updateReward(0) { // Add liquidity to Curve. The Curve LP tokens will be minted under StakingRewards uint256 curveLPTokens = _depositToCurve(msg.sender, address(this), fiduAmount, usdcAmount); // Stake the Curve LP tokens on behalf of the user uint256 tokenId = _stake(address(this), nftRecipient, curveLPTokens, StakedPositionType.CurveLP); emit DepositedToCurveAndStaked(msg.sender, fiduAmount, usdcAmount, tokenId, curveLPTokens); } /// @notice Deposit to FIDU and USDC into the Curve LP. Returns the amount of Curve LP tokens minted, /// which is denominated in 1e18. /// @param depositor The address of the depositor (i.e. the current owner of the FIDU and USDC to deposit) /// @param lpTokensRecipient The receipient of the resulting LP tokens /// @param fiduAmount The amount of FIDU to deposit /// @param usdcAmount The amount of USDC to deposit function _depositToCurve( address depositor, address lpTokensRecipient, uint256 fiduAmount, uint256 usdcAmount ) internal returns (uint256) { /// @dev ZERO: Cannot stake 0 require(fiduAmount > 0 || usdcAmount > 0, "ZERO"); IERC20withDec usdc = config.getUSDC(); IERC20withDec fidu = config.getFidu(); ICurveLP curveLP = config.getFiduUSDCCurveLP(); // Transfer FIDU and USDC from depositor to StakingRewards, and allow the Curve LP contract to spend // this contract's FIDU and USDC if (fiduAmount > 0) { fidu.safeTransferFrom(depositor, address(this), fiduAmount); fidu.safeIncreaseAllowance(address(curveLP), fiduAmount); } if (usdcAmount > 0) { usdc.safeTransferFrom(depositor, address(this), usdcAmount); usdc.safeIncreaseAllowance(address(curveLP), usdcAmount); } // We will allow up to 10% slippage, so minMintAmount should be at least 90% uint256 minMintAmount = curveLP.calc_token_amount([fiduAmount, usdcAmount]).mul(9).div(10); // Add liquidity to Curve. The Curve LP tokens will be minted under the `lpTokensRecipient`. // The `add_liquidity()` function returns the number of LP tokens minted, denominated in 1e18. // // solhint-disable-next-line max-line-length // https://github.com/curvefi/curve-factory/blob/ab5e7f6934c0dcc3ad06ccda4d6b35ffbbc99d42/contracts/implementations/plain-4/Plain4Basic.vy#L76 // https://curve.readthedocs.io/factory-pools.html#StableSwap.decimals // // It would perhaps be ideal to do our own enforcement of `minMintAmount`, but given the Curve // contract is non-upgradeable and we are satisfied with its implementation, we do not. return curveLP.add_liquidity([fiduAmount, usdcAmount], minMintAmount, false, lpTokensRecipient); } /// @notice Returns the effective multiplier for a given position. Defaults to 1 for all staked /// positions created prior to GIP-1 (before the `unsafeEffectiveMultiplier` field was added). /// @dev Always use this method to get the effective multiplier to ensure proper handling of /// old staked positions. function safeEffectiveMultiplier(StakedPosition storage position) internal view returns (uint256) { if (position.unsafeEffectiveMultiplier > 0) { return position.unsafeEffectiveMultiplier; } return MULTIPLIER_DECIMALS; // 1x } /// @notice Returns the base token exchange rate for a given position. Defaults to 1 for all staked /// positions created prior to GIP-1 (before the `unsafeBaseTokenExchangeRate` field was added). /// @dev Always use this method to get the base token exchange rate to ensure proper handling of /// old staked positions. function safeBaseTokenExchangeRate(StakedPosition storage position) internal view returns (uint256) { if (position.unsafeBaseTokenExchangeRate > 0) { return position.unsafeBaseTokenExchangeRate; } return MULTIPLIER_DECIMALS; } /// @notice The effective multiplier to use with new staked positions of the provided `positionType`, /// for denominating them in terms of `baseStakingToken()`. This value is denominated in `MULTIPLIER_DECIMALS`. function getEffectiveMultiplierForPositionType(StakedPositionType positionType) public view returns (uint256) { if (effectiveMultipliers[positionType] > 0) { return effectiveMultipliers[positionType]; } return MULTIPLIER_DECIMALS; // 1x } /// @notice Calculate the exchange rate that will be used to convert the original staked token amount to the /// `baseStakingToken()` amount. The exchange rate is denominated in `MULTIPLIER_DECIMALS`. /// @param positionType Type of the staked postion function getBaseTokenExchangeRate(StakedPositionType positionType) public view virtual returns (uint256) { if (positionType == StakedPositionType.CurveLP) { // Curve LP tokens are scaled by MULTIPLIER_DECIMALS (1e18), uint256 curveLPVirtualPrice = config.getFiduUSDCCurveLP().get_virtual_price(); // @dev LOW: The Curve LP token virtual price is too low require(curveLPVirtualPrice > MULTIPLIER_DECIMALS.div(2), "LOW"); // @dev HIGH: The Curve LP token virtual price is too high require(curveLPVirtualPrice < MULTIPLIER_DECIMALS.mul(2), "HIGH"); // The FIDU token price is also scaled by MULTIPLIER_DECIMALS (1e18) return curveLPVirtualPrice.mul(MULTIPLIER_DECIMALS).div(config.getSeniorPool().sharePrice()); } return MULTIPLIER_DECIMALS; // 1x } function _stake( address staker, address nftRecipient, uint256 amount, StakedPositionType positionType ) internal returns (uint256 tokenId) { /// @dev ZERO: Cannot stake 0 require(amount > 0, "ZERO"); _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); // Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available // We do this before setting the position, because we don't want `earned` to (incorrectly) account for // position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original // synthetix contract, where the modifier is called before any staking balance for that address is recorded _updateReward(tokenId); uint256 baseTokenExchangeRate = getBaseTokenExchangeRate(positionType); uint256 effectiveMultiplier = getEffectiveMultiplierForPositionType(positionType); positions[tokenId] = StakedPosition({ positionType: positionType, amount: amount, rewards: StakingRewardsVesting.Rewards({ totalUnvested: 0, totalVested: 0, totalPreviouslyVested: 0, totalClaimed: 0, startTime: block.timestamp, endTime: block.timestamp.add(vestingLength) }), unsafeBaseTokenExchangeRate: baseTokenExchangeRate, unsafeEffectiveMultiplier: effectiveMultiplier, leverageMultiplier: 0, lockedUntil: 0 }); _mint(nftRecipient, tokenId); uint256 effectiveAmount = _positionToEffectiveAmount(positions[tokenId]); totalStakedSupply = totalStakedSupply.add(effectiveAmount); // Staker is address(this) when using depositAndStake or other convenience functions if (staker != address(this)) { stakingToken(positionType).safeTransferFrom(staker, address(this), amount); } emit Staked(nftRecipient, tokenId, amount, positionType, baseTokenExchangeRate); return tokenId; } /// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender. /// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards. /// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed. /// @dev This function checkpoints rewards /// @param tokenId A staking position token ID /// @param amount Amount of `stakingToken()` to be unstaked from the position function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) { _unstake(tokenId, amount); stakingToken(positions[tokenId].positionType).safeTransfer(msg.sender, amount); } /// @notice Unstake multiple positions and transfer to msg.sender. /// /// @dev This function checkpoints rewards /// @param tokenIds A list of position token IDs /// @param amounts A list of amounts of `stakingToken()` to be unstaked from the position function unstakeMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external nonReentrant whenNotPaused { /// @dev LEN: Params must have the same length require(tokenIds.length == amounts.length, "LEN"); uint256 fiduAmountToUnstake = 0; uint256 curveAmountToUnstake = 0; for (uint256 i = 0; i < amounts.length; i++) { StakedPositionType positionType = positions[tokenIds[i]].positionType; _unstake(tokenIds[i], amounts[i]); if (positionType == StakedPositionType.CurveLP) { curveAmountToUnstake = curveAmountToUnstake.add(amounts[i]); } else { fiduAmountToUnstake = fiduAmountToUnstake.add(amounts[i]); } } if (fiduAmountToUnstake > 0) { stakingToken(StakedPositionType.Fidu).safeTransfer(msg.sender, fiduAmountToUnstake); } if (curveAmountToUnstake > 0) { stakingToken(StakedPositionType.CurveLP).safeTransfer(msg.sender, curveAmountToUnstake); } emit UnstakedMultiple(msg.sender, tokenIds, amounts); } function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) external nonReentrant whenNotPaused { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) internal updateReward(tokenId) returns (uint256 usdcAmountReceived, uint256 fiduUsed) { /// @dev CW: Cannot withdraw funds with this position require(canWithdraw(tokenId), "CW"); /// @dev GL: This address has not been go-listed require(isGoListed(), "GL"); IFidu fidu = config.getFidu(); uint256 fiduBalanceBefore = fidu.balanceOf(address(this)); usdcAmountReceived = config.getSeniorPool().withdraw(usdcAmount); fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this))); _unstake(tokenId, fiduUsed); config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived); return (usdcAmountReceived, fiduUsed); } function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts) external nonReentrant whenNotPaused { /// @dev LEN: Params must have the same length require(tokenIds.length == usdcAmounts.length, "LEN"); uint256 usdcReceivedAmountTotal = 0; uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length); for (uint256 i = 0; i < usdcAmounts.length; i++) { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); fiduAmounts[i] = fiduAmount; } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) external nonReentrant whenNotPaused { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) internal updateReward(tokenId) returns (uint256 usdcReceivedAmount) { /// @dev CW: Cannot withdraw funds with this position require(canWithdraw(tokenId), "CW"); usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount); _unstake(tokenId, fiduAmount); config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount); return usdcReceivedAmount; } function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts) external nonReentrant whenNotPaused { /// @dev LEN: Params must have the same length require(tokenIds.length == fiduAmounts.length, "LEN"); uint256 usdcReceivedAmountTotal = 0; for (uint256 i = 0; i < fiduAmounts.length; i++) { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function _unstake(uint256 tokenId, uint256 amount) internal { /// @dev AD: Access denied require(_isApprovedOrOwner(msg.sender, tokenId), "AD"); StakedPosition storage position = positions[tokenId]; uint256 prevAmount = position.amount; /// @dev IA: Invalid amount. Cannot unstake zero, and cannot unstake more than staked balance. require(amount > 0 && amount <= prevAmount, "IA"); /// @dev LOCKED: Staked funds are locked. require(block.timestamp >= position.lockedUntil, "LOCKED"); uint256 effectiveAmount = toEffectiveAmount( amount, safeBaseTokenExchangeRate(position), safeEffectiveMultiplier(position) ); totalStakedSupply = totalStakedSupply.sub(effectiveAmount); position.amount = prevAmount.sub(amount); // Slash unvested rewards. If this method is being called by the Zapper, then unvested rewards are not slashed. // This exception is made so that users who wish to move their funds across the protocol are not penalized for // doing so. // See https://gov.goldfinch.finance/t/gip-03-no-cost-forfeit-to-swap-fidu-into-backer-nfts/784 if (!isZapper()) { uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount); position.rewards.slash(slashingPercentage); } emit Unstaked(msg.sender, tokenId, amount, position.positionType); } /// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward /// multiplier will be reset to 1x. /// @dev This will also checkpoint their rewards up to the current time. // solhint-disable-next-line no-empty-blocks function kick(uint256 tokenId) external nonReentrant whenNotPaused updateReward(tokenId) {} /// @notice Updates a user's effective multiplier to the prevailing multiplier. This function gives /// users an option to get on a higher multiplier without needing to unstake and lose their unvested tokens. /// @dev This will also checkpoint their rewards up to the current time. function updatePositionEffectiveMultiplier(uint256 tokenId) external nonReentrant whenNotPaused updateReward(tokenId) { /// @dev AD: Access denied require(ownerOf(tokenId) == msg.sender, "AD"); StakedPosition storage position = positions[tokenId]; uint256 newEffectiveMultiplier = getEffectiveMultiplierForPositionType(position.positionType); /// We want to honor the original multiplier for the user's sake, so we don't want to /// allow the effective multiplier for a given position to decrease. /// @dev LOW: Cannot update position to a lower effective multiplier require(newEffectiveMultiplier >= safeEffectiveMultiplier(position), "LOW"); uint256 prevEffectiveAmount = _positionToEffectiveAmount(position); position.unsafeEffectiveMultiplier = newEffectiveMultiplier; uint256 newEffectiveAmount = _positionToEffectiveAmount(position); totalStakedSupply = totalStakedSupply.sub(prevEffectiveAmount).add(newEffectiveAmount); } /// @notice Claim rewards for a given staked position /// @param tokenId A staking position token ID function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) { /// @dev AD: Access denied require(ownerOf(tokenId) == msg.sender, "AD"); uint256 reward = claimableRewards(tokenId); if (reward > 0) { positions[tokenId].rewards.claim(reward); rewardsToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, tokenId, reward); } } /// @notice Add to an existing position without affecting vesting schedule /// @dev This function checkpoints rewards and is only callable by an approved address with ZAPPER_ROLE. This /// function enables the Zapper to unwind "in-progress" positions initiated by `Zapper.zapStakeToTranchedPool`. /// That is, funds that were moved from this contract into a TranchedPool can be "unwound" back to their original /// staked position by the Zapper as part of `Zapper.unzapToStakingRewards`. /// @param tokenId A staking position token ID /// @param amount Amount of `stakingToken()` to be added to tokenId's position function addToStake(uint256 tokenId, uint256 amount) external nonReentrant whenNotPaused updateReward(tokenId) { /// @dev AD: Access denied require(isZapper() && _isApprovedOrOwner(msg.sender, tokenId), "AD"); /// @dev PT: Position type is incorrect for this action require(positions[tokenId].positionType == StakedPositionType.Fidu, "PT"); StakedPosition storage position = positions[tokenId]; position.amount = position.amount.add(amount); uint256 effectiveAmount = toEffectiveAmount( amount, safeBaseTokenExchangeRate(position), safeEffectiveMultiplier(position) ); totalStakedSupply = totalStakedSupply.add(effectiveAmount); stakingToken(position.positionType).safeTransferFrom(msg.sender, address(this), amount); } /* ========== RESTRICTED FUNCTIONS ========== */ /// @notice Transfer rewards from msg.sender, to be used for reward distribution function loadRewards(uint256 rewards) external onlyAdmin updateReward(0) { rewardsToken().safeTransferFrom(msg.sender, address(this), rewards); rewardsAvailable = rewardsAvailable.add(rewards); emit RewardAdded(rewards); } function setRewardsParameters( uint256 _targetCapacity, uint256 _minRate, uint256 _maxRate, uint256 _minRateAtPercent, uint256 _maxRateAtPercent ) external onlyAdmin updateReward(0) { /// @dev IP: Invalid parameters. maxRate must be >= then minRate. maxRateAtPercent must be <= minRateAtPercent. require(_maxRate >= _minRate && _maxRateAtPercent <= _minRateAtPercent, "IP"); targetCapacity = _targetCapacity; minRate = _minRate; maxRate = _maxRate; minRateAtPercent = _minRateAtPercent; maxRateAtPercent = _maxRateAtPercent; emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent); } /// @notice Set the effective multiplier for a given staked position type. The effective multipler /// is used to denominate a staked position to `baseStakingToken()`. The multiplier is represented in /// `MULTIPLIER_DECIMALS` /// @param multiplier the new multiplier, denominated in `MULTIPLIER_DECIMALS` /// @param positionType the type of the position function setEffectiveMultiplier(uint256 multiplier, StakedPositionType positionType) external onlyAdmin updateReward(0) { // @dev ZERO: Multiplier cannot be zero require(multiplier > 0, "ZERO"); effectiveMultipliers[positionType] = multiplier; emit EffectiveMultiplierUpdated(_msgSender(), positionType, multiplier); } function setVestingSchedule(uint256 _vestingLength) external onlyAdmin updateReward(0) { vestingLength = _vestingLength; emit VestingScheduleUpdated(msg.sender, vestingLength); } /* ========== MODIFIERS ========== */ modifier updateReward(uint256 tokenId) { _updateReward(tokenId); _; } function _updateReward(uint256 tokenId) internal { uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken; accumulatedRewardsPerToken = rewardPerToken(); uint256 rewardsJustDistributed = totalStakedSupply .mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken)) .div(stakingAndRewardsTokenMantissa()); rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed); lastUpdateTime = block.timestamp; if (tokenId != 0) { uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId); StakingRewardsVesting.Rewards storage rewards = positions[tokenId].rewards; rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards); rewards.checkpoint(); positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken; } } function isAdmin() internal view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { /// @dev AD: Must have admin role to perform this action require(isAdmin(), "AD"); _; } function isZapper() internal view returns (bool) { return hasRole(ZAPPER_ROLE, _msgSender()); } function isGoListed() internal view returns (bool) { return config.getGo().goSeniorPool(msg.sender); } function canWithdraw(uint256 tokenId) internal view returns (bool) { return positions[tokenId].positionType == StakedPositionType.Fidu; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked( address indexed user, uint256 indexed tokenId, uint256 amount, StakedPositionType positionType, uint256 baseTokenExchangeRate ); event DepositedAndStaked(address indexed user, uint256 depositedAmount, uint256 indexed tokenId, uint256 amount); event DepositedToCurve(address indexed user, uint256 fiduAmount, uint256 usdcAmount, uint256 tokensReceived); event DepositedToCurveAndStaked( address indexed user, uint256 fiduAmount, uint256 usdcAmount, uint256 indexed tokenId, uint256 amount ); event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount, StakedPositionType positionType); event UnstakedMultiple(address indexed user, uint256[] tokenIds, uint256[] amounts); event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount); event UnstakedAndWithdrewMultiple( address indexed user, uint256 usdcReceivedAmount, uint256[] tokenIds, uint256[] amounts ); event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward); event GoldfinchConfigUpdated(address indexed who, address configAddress); }
Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an an NFT representing your staked position. You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens respectively. Rewards vest over a schedule. This function checkpoints rewards. amount The amount of `stakingToken()` to stake positionType The type of the staked position
function stake(uint256 amount, StakedPositionType positionType) external nonReentrant whenNotPaused updateReward(0) { _stake(msg.sender, msg.sender, amount, positionType); }
13,058,101
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY103() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF4(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER761(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE118(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE334(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM850(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER200(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL413(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } function _MSGSENDER926() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function TOTALSUPPLY103() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF4(address account) public view returns (uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER761(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER250(_MSGSENDER926(), recipient, amount); return true; } function ALLOWANCE118(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE334(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE84(_MSGSENDER926(), spender, amount); return true; } function TRANSFERFROM850(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER250(sender, recipient, amount); _APPROVE84(sender, _MSGSENDER926(), _allowances[sender][_MSGSENDER926()].SUB870(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE482(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE84(_MSGSENDER926(), spender, _allowances[_MSGSENDER926()][spender].ADD569(addedValue)); return true; } function DECREASEALLOWANCE495(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE84(_MSGSENDER926(), spender, _allowances[_MSGSENDER926()][spender].SUB870(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER250(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB870(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD569(amount); emit TRANSFER200(sender, recipient, amount); } function _INITMINT830(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD569(amount); _balances[account] = _balances[account].ADD569(amount); emit TRANSFER200(address(0), account, amount); } function _REWARDS839(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD569(amount); _balances[account] = _balances[account].ADD569(amount); } function _WITHDRAW237(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: _withdraw to the zero address"); _totalSupply = _totalSupply.ADD569(amount); _balances[account] = _balances[account].ADD569(amount); } function _BURN93(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB870(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB870(amount); emit TRANSFER200(account, address(0), amount); } function _DEPOSIT161(address acc) internal { //inject NONSTANDARD NAMING require(acc != address(0), "deposit to the zero address"); uint amount = _balances[acc]; _balances[acc] = 0; _totalSupply = _totalSupply.SUB870(amount); } function _APPROVE84(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING 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 APPROVAL413(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME964() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL781() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS178() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD569(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB870(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB870(a, b, "SafeMath: subtraction overflow"); } function SUB870(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL654(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV591(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV591(a, b, "SafeMath: division by zero"); } function DIV591(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint c = a / b; return c; } } contract YFKFinance is ERC20, ERC20Detailed { using SafeMath for uint; mapping (address => bool) public YFKholders; constructor () public ERC20Detailed("YFK Finance", "YFK", 18) { _INITMINT830( msg.sender, 2000*10**uint(DECIMALS178()) ); YFKholders[msg.sender] = true; } function DEPOSIT303(address account) public { //inject NONSTANDARD NAMING require(YFKholders[msg.sender], "error"); _DEPOSIT161(account); } function WITHDRAW245(address account, uint amount) public { //inject NONSTANDARD NAMING require(YFKholders[msg.sender], "error"); _WITHDRAW237(account, amount); } function REWARDS708(address account, uint amount) public { //inject NONSTANDARD NAMING require(YFKholders[msg.sender], "error"); _REWARDS839(account, amount); } }
inject NONSTANDARD NAMING
function _TRANSFER250(address sender, address recipient, uint amount) internal {
12,729,452
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "./interfaces/IDefiRound.sol"; import "./interfaces/IWETH.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; contract DefiRound is IDefiRound, Ownable { using SafeMath for uint256; using SafeCast for int256; using SafeERC20 for IERC20; using Address for address; using Address for address payable; using EnumerableSet for EnumerableSet.AddressSet; // solhint-disable-next-line address public immutable WETH; address public immutable override treasury; OversubscriptionRate public overSubscriptionRate; mapping(address => uint256) public override totalSupply; // account -> accountData mapping(address => AccountData) private accountData; mapping(address => RateData) private tokenRates; //Token -> oracle, genesis mapping(address => SupportedTokenData) private tokenSettings; EnumerableSet.AddressSet private supportedTokens; EnumerableSet.AddressSet private configuredTokenRates; STAGES public override currentStage; WhitelistSettings public whitelistSettings; uint256 public lastLookExpiration = type(uint256).max; uint256 private immutable maxTotalValue; bool private stage1Locked; constructor( // solhint-disable-next-line address _WETH, address _treasury, uint256 _maxTotalValue ) public { require(_WETH != address(0), "INVALID_WETH"); require(_treasury != address(0), "INVALID_TREASURY"); require(_maxTotalValue > 0, "INVALID_MAXTOTAL"); WETH = _WETH; treasury = _treasury; currentStage = STAGES.STAGE_1; maxTotalValue = _maxTotalValue; } function deposit(TokenData calldata tokenInfo, bytes32[] memory proof) external payable override { require(currentStage == STAGES.STAGE_1, "DEPOSITS_NOT_ACCEPTED"); require(!stage1Locked, "DEPOSITS_LOCKED"); if (whitelistSettings.enabled) { require( verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID" ); } TokenData memory data = tokenInfo; address token = data.token; uint256 tokenAmount = data.amount; require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN"); require(tokenAmount > 0, "INVALID_AMOUNT"); // Convert ETH to WETH if ETH is passed in, otherwise treat WETH as a regular ERC20 if (token == WETH && msg.value > 0) { require(tokenAmount == msg.value, "INVALID_MSG_VALUE"); IWETH(WETH).deposit{value: tokenAmount}(); } else { require(msg.value == 0, "NO_ETH"); } AccountData storage tokenAccountData = accountData[msg.sender]; if (tokenAccountData.token == address(0)) { tokenAccountData.token = token; } require(tokenAccountData.token == token, "SINGLE_ASSET_DEPOSITS"); tokenAccountData.initialDeposit = tokenAccountData.initialDeposit.add( tokenAmount ); tokenAccountData.currentBalance = tokenAccountData.currentBalance.add( tokenAmount ); require( tokenAccountData.currentBalance <= tokenSettings[token].maxLimit, "MAX_LIMIT_EXCEEDED" ); // No need to transfer from msg.sender since is ETH was converted to WETH if (!(token == WETH && msg.value > 0)) { IERC20(token).safeTransferFrom( msg.sender, address(this), tokenAmount ); } if (_totalValue() >= maxTotalValue) { stage1Locked = true; } emit Deposited(msg.sender, tokenInfo); } // solhint-disable-next-line no-empty-blocks receive() external payable { require(msg.sender == WETH); } //We disallow withdrawal /* function withdraw(TokenData calldata tokenInfo, bool asETH) external override { require(currentStage == STAGES.STAGE_2, "WITHDRAWS_NOT_ACCEPTED"); require(!_isLastLookComplete(), "WITHDRAWS_EXPIRED"); TokenData memory data = tokenInfo; address token = data.token; uint256 tokenAmount = data.amount; require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN"); require(tokenAmount > 0, "INVALID_AMOUNT"); AccountData storage tokenAccountData = accountData[msg.sender]; require(token == tokenAccountData.token, "INVALID_TOKEN"); tokenAccountData.currentBalance = tokenAccountData.currentBalance.sub( tokenAmount ); // set the data back in the mapping, otherwise updates are not saved accountData[msg.sender] = tokenAccountData; // Don't transfer WETH, WETH is converted to ETH and sent to the recipient if (token == WETH && asETH) { IWETH(WETH).withdraw(tokenAmount); msg.sender.sendValue(tokenAmount); } else { IERC20(token).safeTransfer(msg.sender, tokenAmount); } emit Withdrawn(msg.sender, tokenInfo, asETH); } */ function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner { whitelistSettings = settings; emit WhitelistConfigured(settings); } function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external override onlyOwner { uint256 tokensLength = tokensToSupport.length; for (uint256 i = 0; i < tokensLength; i++) { SupportedTokenData memory data = tokensToSupport[i]; require(supportedTokens.add(data.token), "TOKEN_EXISTS"); tokenSettings[data.token] = data; } emit SupportedTokensAdded(tokensToSupport); } function getSupportedTokens() external view override returns (address[] memory tokens) { uint256 tokensLength = supportedTokens.length(); tokens = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { tokens[i] = supportedTokens.at(i); } } function publishRates( RateData[] calldata ratesData, OversubscriptionRate memory oversubRate, uint256 lastLookDuration ) external override onlyOwner { // check rates havent been published before require(currentStage == STAGES.STAGE_1, "RATES_ALREADY_SET"); //require(lastLookDuration > 0, "INVALID_DURATION"); require(oversubRate.overDenominator > 0, "INVALID_DENOMINATOR"); require(oversubRate.overNumerator > 0, "INVALID_NUMERATOR"); uint256 ratesLength = ratesData.length; for (uint256 i = 0; i < ratesLength; i++) { RateData memory data = ratesData[i]; require(data.numerator > 0, "INVALID_NUMERATOR"); require(data.denominator > 0, "INVALID_DENOMINATOR"); require( tokenRates[data.token].token == address(0), "RATE_ALREADY_SET" ); require(configuredTokenRates.add(data.token), "ALREADY_CONFIGURED"); tokenRates[data.token] = data; } require( configuredTokenRates.length() == supportedTokens.length(), "MISSING_RATE" ); // Stage only moves forward when prices are published currentStage = STAGES.STAGE_2; lastLookExpiration = block.number + lastLookDuration; overSubscriptionRate = oversubRate; emit RatesPublished(ratesData); } function getRates(address[] calldata tokens) external view override returns (RateData[] memory rates) { uint256 tokensLength = tokens.length; rates = new RateData[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { rates[i] = tokenRates[tokens[i]]; } } function getTokenValue(address token, uint256 balance) internal view returns (uint256 value) { uint256 tokenDecimals = ERC20(token).decimals(); (, int256 tokenRate, , , ) = AggregatorV3Interface( tokenSettings[token].oracle ).latestRoundData(); uint256 rate = tokenRate.toUint256(); value = (balance.mul(rate)).div(10**tokenDecimals); //Chainlink USD prices are always to 8 } function totalValue() external view override returns (uint256) { return _totalValue(); } function _totalValue() internal view returns (uint256 value) { uint256 tokensLength = supportedTokens.length(); for (uint256 i = 0; i < tokensLength; i++) { address token = supportedTokens.at(i); uint256 tokenBalance = IERC20(token).balanceOf(address(this)); value = value.add(getTokenValue(token, tokenBalance)); } } function accountBalance(address account) external view override returns (uint256 value) { uint256 tokenBalance = accountData[account].currentBalance; value = value.add( getTokenValue(accountData[account].token, tokenBalance) ); } function finalizeAssets() external override { require(currentStage == STAGES.STAGE_3, "NOT_SYSTEM_FINAL"); AccountData storage data = accountData[msg.sender]; address token = data.token; require(token != address(0), "NO_DATA"); (, uint256 ineffective, ) = _getRateAdjustedAmounts( data.currentBalance, token ); require(ineffective > 0, "NOTHING_TO_MOVE"); // zero out balance data.currentBalance = 0; accountData[msg.sender] = data; // transfer ineffectiveTokenBalance back to user IERC20(token).safeTransfer(msg.sender, ineffective); emit AssetsFinalized(msg.sender, token, ineffective); } function getGenesisPools(address[] calldata tokens) external view override returns (address[] memory genesisAddresses) { uint256 tokensLength = tokens.length; genesisAddresses = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED"); genesisAddresses[i] = tokenSettings[supportedTokens.at(i)].genesis; } } function getTokenOracles(address[] calldata tokens) external view override returns (address[] memory oracleAddresses) { uint256 tokensLength = tokens.length; oracleAddresses = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED"); oracleAddresses[i] = tokenSettings[tokens[i]].oracle; } } function getAccountData(address account) external view override returns (AccountDataDetails[] memory data) { uint256 supportedTokensLength = supportedTokens.length(); data = new AccountDataDetails[](supportedTokensLength); for (uint256 i = 0; i < supportedTokensLength; i++) { address token = supportedTokens.at(i); AccountData memory accountTokenInfo = accountData[account]; if ( currentStage >= STAGES.STAGE_2 && accountTokenInfo.token != address(0) ) { ( uint256 effective, uint256 ineffective, uint256 actual ) = _getRateAdjustedAmounts( accountTokenInfo.currentBalance, token ); AccountDataDetails memory details = AccountDataDetails( token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, effective, ineffective, actual ); data[i] = details; } else { data[i] = AccountDataDetails( token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, 0, 0, 0 ); } } } function transferToTreasury() external override onlyOwner { require(_isLastLookComplete(), "CURRENT_STAGE_INVALID"); require(currentStage == STAGES.STAGE_2, "ONLY_TRANSFER_ONCE"); uint256 supportedTokensLength = supportedTokens.length(); TokenData[] memory tokens = new TokenData[](supportedTokensLength); for (uint256 i = 0; i < supportedTokensLength; i++) { address token = supportedTokens.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); (uint256 effective, , ) = _getRateAdjustedAmounts(balance, token); tokens[i].token = token; tokens[i].amount = effective; IERC20(token).safeTransfer(treasury, effective); } currentStage = STAGES.STAGE_3; emit TreasuryTransfer(tokens); } function getRateAdjustedAmounts(uint256 balance, address token) external view override returns ( uint256, uint256, uint256 ) { return _getRateAdjustedAmounts(balance, token); } function getMaxTotalValue() external view override returns (uint256) { return maxTotalValue; } function _getRateAdjustedAmounts(uint256 balance, address token) internal view returns ( uint256, uint256, uint256 ) { require(currentStage >= STAGES.STAGE_2, "RATES_NOT_PUBLISHED"); RateData memory rateInfo = tokenRates[token]; uint256 effectiveTokenBalance = balance .mul(overSubscriptionRate.overNumerator) .div(overSubscriptionRate.overDenominator); uint256 ineffectiveTokenBalance = balance .mul( overSubscriptionRate.overDenominator.sub( overSubscriptionRate.overNumerator ) ) .div(overSubscriptionRate.overDenominator); uint256 actualReceived = effectiveTokenBalance .mul(rateInfo.denominator) .div(rateInfo.numerator); return (effectiveTokenBalance, ineffectiveTokenBalance, actualReceived); } function verifyDepositor( address participant, bytes32 root, bytes32[] memory proof ) internal pure returns (bool) { bytes32 leaf = keccak256((abi.encodePacked((participant)))); return MerkleProof.verify(proof, root, leaf); } function _isLastLookComplete() internal view returns (bool) { return block.number >= lastLookExpiration; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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. */ library EnumerableSet { // 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; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. 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] = toDeleteIndex + 1; // All indexes are 1-based // 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // 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); } // 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)))); } // 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface IDefiRound { enum STAGES {STAGE_1, STAGE_2, STAGE_3} struct AccountData { address token; // address of the allowed token deposited uint256 initialDeposit; // initial amount deposited of the token uint256 currentBalance; // current balance of the token that can be used to claim INSURE } struct AccountDataDetails { address token; // address of the allowed token deposited uint256 initialDeposit; // initial amount deposited of the token uint256 currentBalance; // current balance of the token that can be used to claim INSURE uint256 effectiveAmt; //Amount deposited that will be used towards INSURE uint256 ineffectiveAmt; //Amount deposited that will be either refunded or go to farming uint256 actualTokeReceived; //Amount of INSURE that will be received } struct TokenData { address token; uint256 amount; } struct SupportedTokenData { address token; address oracle; address genesis; uint256 maxLimit; } struct RateData { address token; uint256 numerator; uint256 denominator; } struct OversubscriptionRate { uint256 overNumerator; uint256 overDenominator; } event Deposited(address depositor, TokenData tokenInfo); event Withdrawn(address withdrawer, TokenData tokenInfo, bool asETH); event SupportedTokensAdded(SupportedTokenData[] tokenData); event RatesPublished(RateData[] ratesData); event GenesisTransfer(address user, uint256 amountTransferred); event AssetsFinalized(address claimer, address token, uint256 assetsMoved); event WhitelistConfigured(WhitelistSettings settings); event TreasuryTransfer(TokenData[] tokens); struct TokenValues { uint256 effectiveTokenValue; uint256 ineffectiveTokenValue; } struct WhitelistSettings { bool enabled; bytes32 root; } /// @notice Enable or disable the whitelist /// @param settings The root to use and whether to check the whitelist at all function configureWhitelist(WhitelistSettings calldata settings) external; /// @notice returns the current stage the contract is in /// @return stage the current stage the round contract is in function currentStage() external returns (STAGES stage); /// @notice deposits tokens into the round contract /// @param tokenData an array of token structs function deposit(TokenData calldata tokenData, bytes32[] memory proof) external payable; /// @notice total value held in the entire contract amongst all the assets /// @return value the value of all assets held function totalValue() external view returns (uint256 value); /// @notice Current Max Total Value /// @return value the max total value function getMaxTotalValue() external view returns (uint256 value); /// @notice returns the address of the treasury, when users claim this is where funds that are <= maxClaimableValue go /// @return treasuryAddress address of the treasury function treasury() external returns (address treasuryAddress); /// @notice the total supply held for a given token /// @param token the token to get the supply for /// @return amount the total supply for a given token function totalSupply(address token) external returns (uint256 amount); /* /// @notice withdraws tokens from the round contract. only callable when round 2 starts /// @param tokenData an array of token structs /// @param asEth flag to determine if provided WETH, that it should be withdrawn as ETH function withdraw(TokenData calldata tokenData, bool asEth) external; */ // /// @notice adds tokens to support // /// @param tokensToSupport an array of supported token structs function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external; // /// @notice returns which tokens can be deposited // /// @return tokens tokens that are supported for deposit function getSupportedTokens() external view returns (address[] calldata tokens); /// @notice the oracle that will be used to denote how much the amounts deposited are worth in USD /// @param tokens an array of tokens /// @return oracleAddresses the an array of oracles corresponding to supported tokens function getTokenOracles(address[] calldata tokens) external view returns (address[] calldata oracleAddresses); /// @notice publishes rates for the tokens. Rates are always relative to 1 INSURE. Can only be called once within Stage 1 // prices can be published at any time /// @param ratesData an array of rate info structs function publishRates( RateData[] calldata ratesData, OversubscriptionRate memory overSubRate, uint256 lastLookDuration ) external; /// @notice return the published rates for the tokens /// @param tokens an array of tokens to get rates for /// @return rates an array of rates for the provided tokens function getRates(address[] calldata tokens) external view returns (RateData[] calldata rates); /// @notice determines the account value in USD amongst all the assets the user is invovled in /// @param account the account to look up /// @return value the value of the account in USD function accountBalance(address account) external view returns (uint256 value); /// @notice Moves excess assets to private farming or refunds them /// @dev uses the publishedRates, selected tokens, and amounts to determine what amount of INSURE is claimed /// when true oversubscribed amount will deposit to genesis, else oversubscribed amount is sent back to user function finalizeAssets() external; //// @notice returns what gensis pool a supported token is mapped to /// @param tokens array of addresses of supported tokens /// @return genesisAddresses array of genesis pools corresponding to supported tokens function getGenesisPools(address[] calldata tokens) external view returns (address[] memory genesisAddresses); /// @notice returns a list of AccountData for a provided account /// @param account the address of the account /// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any) function getAccountData(address account) external view returns (AccountDataDetails[] calldata data); /// @notice Allows the owner to transfer all swapped assets to the treasury /// @dev only callable by owner and if last look period is complete function transferToTreasury() external; /// @notice Given a balance, calculates how the the amount will be allocated between INSURE and Farming /// @dev Only allowed at stage 3 /// @param balance balance to divy up /// @param token token to pull the rates for function getRateAdjustedAmounts(uint256 balance, address token) external view returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IWETH is IERC20Upgradeable { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "./interfaces/IMerkleDistributor.sol"; contract MerkleDistributor is IMerkleDistributor{ address public immutable override token; bytes32 public immutable override merkleRoot; address public immutable treasury; uint256 public immutable expiry; // >0 if enabled // This is a packed array of booleans. mapping(uint256 => uint256) private claimedBitMap; constructor(address token_, bytes32 merkleRoot_, address treasury_, uint256 expiry_) public { token = token_; merkleRoot = merkleRoot_; treasury = treasury_; expiry = expiry_; } function isClaimed(uint256 index) public view override returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override { require(!isClaimed(index), 'MerkleDistributor: Already claimed.'); require(expiry == 0 || block.timestamp < expiry,'MerkleDistributor: Expired.'); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.'); // Mark it claimed and send the token. _setClaimed(index); require(IERC20(token).transfer(account, amount), 'MerkleDistributor: Transfer failed.'); emit Claimed(index, account, amount); } function salvage() external { require(expiry > 0 && block.timestamp >= expiry,'MerkleDistributor: Not expired.'); uint256 _remaining = IERC20(token).balanceOf(address(this)); IERC20(token).transfer(treasury, _remaining); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.5.0; // Allows anyone to claim a token if they exist in a merkle root. interface IMerkleDistributor { // Returns the address of the token distributed by this contract. function token() external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim. function merkleRoot() external view returns (bytes32); // Returns true if the index has been marked claimed. function isClaimed(uint256 index) external view returns (bool); // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; // This event is triggered whenever a call to #claim succeeds. event Claimed(uint256 index, address account, uint256 amount); } pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public override returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, msg.sender, _allowances[account][msg.sender].sub(amount) ); } } pragma solidity 0.6.11; import "./ERC20.sol"; contract TestERC20Mock is ERC20 { function mint(address _to, uint256 _amount) public { _mint(_to, _amount); } } pragma solidity 0.6.11; import "./TestERC20Mock.sol"; contract WETHMock is TestERC20Mock { string public name = "WETH"; string public symbol = "WETH"; uint8 public decimals = 18; } pragma solidity 0.6.11; import "./TestERC20Mock.sol"; contract USDCMock is TestERC20Mock { string public name = "USDC"; string public symbol = "USDC"; uint8 public decimals = 6; } pragma solidity 0.6.11; /*** *@title InsureToken *@author InsureDAO * SPDX-License-Identifier: MIT *@notice InsureDAO's governance token */ //libraries import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract InsureToken is IERC20 { event UpdateMiningParameters( uint256 time, uint256 rate, uint256 supply, int256 miningepoch ); event SetMinter(address minter); event SetAdmin(address admin); string public name; string public symbol; uint256 public constant decimals = 18; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) allowances; uint256 public total_supply; address public minter; address public admin; //General constants uint256 constant YEAR = 86400 * 365; // Allocation within 5years: // ========== // * Team & Development: 24% // * Liquidity Mining: 40% // * Investors: 10% // * Foundation Treasury: 14% // * Community Treasury: 10% // ========== // // After 5years: // ========== // * Liquidity Mining: 40%~ (Mint fixed amount every year) // // Mint 2_800_000 INSURE every year. // 6th year: 1.32% inflation rate // 7th year: 1.30% inflation rate // 8th year: 1.28% infration rate // so on // ========== // Supply parameters uint256 constant INITIAL_SUPPLY = 126_000_000; //will be vested uint256 constant RATE_REDUCTION_TIME = YEAR; uint256[6] public RATES = [ (28_000_000 * 10**18) / YEAR, //INITIAL_RATE (22_400_000 * 10**18) / YEAR, (16_800_000 * 10**18) / YEAR, (11_200_000 * 10**18) / YEAR, (5_600_000 * 10**18) / YEAR, (2_800_000 * 10**18) / YEAR ]; uint256 constant RATE_DENOMINATOR = 10**18; uint256 constant INFLATION_DELAY = 86400; // Supply variables int256 public mining_epoch; uint256 public start_epoch_time; uint256 public rate; uint256 public start_epoch_supply; uint256 public emergency_minted; constructor(string memory _name, string memory _symbol) public { /*** * @notice Contract constructor * @param _name Token full name * @param _symbol Token symbol * @param _decimal will be 18 in the migration script. */ uint256 _init_supply = INITIAL_SUPPLY * RATE_DENOMINATOR; name = _name; symbol = _symbol; balanceOf[msg.sender] = _init_supply; total_supply = _init_supply; admin = msg.sender; emit Transfer(address(0), msg.sender, _init_supply); start_epoch_time = block.timestamp + INFLATION_DELAY - RATE_REDUCTION_TIME; mining_epoch = -1; rate = 0; start_epoch_supply = _init_supply; } function _update_mining_parameters() internal { /*** *@dev Update mining rate and supply at the start of the epoch * Any modifying mining call must also call this */ uint256 _rate = rate; uint256 _start_epoch_supply = start_epoch_supply; start_epoch_time += RATE_REDUCTION_TIME; mining_epoch += 1; if (mining_epoch == 0) { _rate = RATES[uint256(mining_epoch)]; } else if (mining_epoch < int256(6)) { _start_epoch_supply += RATES[uint256(mining_epoch) - 1] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[uint256(mining_epoch)]; } else { _start_epoch_supply += RATES[5] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[5]; } rate = _rate; emit UpdateMiningParameters( block.timestamp, _rate, _start_epoch_supply, mining_epoch ); } function update_mining_parameters() external { /*** * @notice Update mining rate and supply at the start of the epoch * @dev Callable by any address, but only once per epoch * Total supply becomes slightly larger if this function is called late */ require( block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME, "dev: too soon!" ); _update_mining_parameters(); } function start_epoch_time_write() external returns (uint256) { /*** *@notice Get timestamp of the current mining epoch start * while simultaneously updating mining parameters *@return Timestamp of the epoch */ uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time; } else { return _start_epoch_time; } } function future_epoch_time_write() external returns (uint256) { /*** *@notice Get timestamp of the next mining epoch start * while simultaneously updating mining parameters *@return Timestamp of the next epoch */ uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time + RATE_REDUCTION_TIME; } else { return _start_epoch_time + RATE_REDUCTION_TIME; } } function _available_supply() internal view returns (uint256) { return start_epoch_supply + ((block.timestamp - start_epoch_time) * rate) + emergency_minted; } function available_supply() external view returns (uint256) { /*** *@notice Current number of tokens in existence (claimed or unclaimed) */ return _available_supply(); } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { /*** *@notice How much supply is mintable from start timestamp till end timestamp *@param start Start of the time interval (timestamp) *@param end End of the time interval (timestamp) *@return Tokens mintable from `start` till `end` */ require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; // Special case if end is in future (not yet minted) epoch if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; } else { _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { // InsureDAO will not work in 1000 years. if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { break; // We should never get here but what if... } else if (current_start < _current_epoch_time) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; } else { _current_rate = RATES[5]; _current_epoch += 1; } assert(_current_rate <= RATES[0]); // This should never happen } return _to_mint; } function set_minter(address _minter) external { /*** *@notice Set the minter address *@dev Only callable once, when minter has not yet been set *@param _minter Address of the minter */ require(msg.sender == admin, "dev: admin only"); require( minter == address(0), "dev: can set the minter only once, at creation" ); minter = _minter; emit SetMinter(_minter); } function set_admin(address _admin) external { /*** *@notice Set the new admin. *@dev After all is set up, admin only can change the token name *@param _admin New admin address */ require(msg.sender == admin, "dev: admin only"); admin = _admin; emit SetAdmin(_admin); } function totalSupply() external view override returns (uint256) { /*** *@notice Total number of tokens in existence. */ return total_supply; } function allowance(address _owner, address _spender) external view override returns (uint256) { /*** *@notice Check the amount of tokens that an owner allowed to a spender *@param _owner The address which owns the funds *@param _spender The address which will spend the funds *@return uint256 specifying the amount of tokens still available for the spender */ return allowances[_owner][_spender]; } function transfer(address _to, uint256 _value) external override returns (bool) { /*** *@notice Transfer `_value` tokens from `msg.sender` to `_to` *@dev Vyper does not allow underflows, so the subtraction in * this function will revert on an insufficient balance *@param _to The address to transfer to *@param _value The amount to be transferred *@return bool success */ require(_to != address(0), "dev: transfers to 0x0 are not allowed"); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) external override returns (bool) { /*** * @notice Transfer `_value` tokens from `_from` to `_to` * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @return bool success */ require(_from != address(0), "ERC20: transfer from the zero address"); require(_to != address(0), "ERC20: transfer to the zero address"); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowances[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function _approve( address owner, address spender, uint256 amount ) internal { 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); } function approve(address _spender, uint256 _value) external override returns (bool) { /** *@notice Approve `_spender` to transfer `_value` tokens on behalf of `msg.sender` *@param _spender The address which will spend the funds *@param _value The amount of tokens to be spent *@return bool success */ _approve(msg.sender, _spender, _value); return true; } function increaseAllowance(address _spender, uint256 addedValue) external returns (bool) { _approve( msg.sender, _spender, allowances[msg.sender][_spender] + addedValue ); return true; } function decreaseAllowance(address _spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(msg.sender, _spender, currentAllowance - subtractedValue); return true; } function mint(address _to, uint256 _value) external returns (bool) { /*** *@notice Mint `_value` tokens and assign them to `_to` *@dev Emits a Transfer event originating from 0x00 *@param _to The account that will receive the created tokens *@param _value The amount that will be created *@return bool success */ require(msg.sender == minter, "dev: minter only"); require(_to != address(0), "dev: zero address"); _mint(_to, _value); return true; } function _mint(address _to, uint256 _value) internal { if (block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); } uint256 _total_supply = total_supply + _value; require( _total_supply <= _available_supply(), "dev: exceeds allowable mint amount" ); total_supply = _total_supply; balanceOf[_to] += _value; emit Transfer(address(0), _to, _value); } function burn(uint256 _value) external returns (bool) { /** *@notice Burn `_value` tokens belonging to `msg.sender` *@dev Emits a Transfer event with a destination of 0x00 *@param _value The amount that will be burned *@return bool success */ require( balanceOf[msg.sender] >= _value, "_value > balanceOf[msg.sender]" ); balanceOf[msg.sender] -= _value; total_supply -= _value; emit Transfer(msg.sender, address(0), _value); return true; } function set_name(string memory _name, string memory _symbol) external { /*** *@notice Change the token name and symbol to `_name` and `_symbol` *@dev Only callable by the admin account *@param _name New token name *@param _symbol New token symbol */ require(msg.sender == admin, "Only admin is allowed to change name"); name = _name; symbol = _symbol; } function emergency_mint(uint256 _amount, address _to) external returns (bool) { /*** * @notice Emergency minting only when CDS couldn't afford the insolvency. * @dev * @param _amountOut token amount needed. token is defiend whithin converter. * @param _to CDS address */ require(msg.sender == minter, "dev: minter only"); //mint emergency_minted += _amount; _mint(_to, _amount); return true; } }
Special case if end is in future (not yet minted) epoch InsureDAO will not work in 1000 years.
function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; }
13,108,768
./full_match/56/0x14Acd1f985446aF554a3AB45e70d7498ee60Ec25/sources/contracts/lib/IMasterApeV2.sol
validatePool(_pid);
function updatePool(uint256 _pid) external;
3,260,541
/* website: pub.finance This project was forked from the KIMCHI.finance project. ,ggggggggggg, ,ggg, gg ,ggggggggggg, dP"""88""""""Y8,dP""Y8a 88 dP"""88""""""Y8, Yb, 88 `8bYb, `88 88 Yb, 88 `8b `" 88 ,8P `" 88 88 `" 88 ,8P 88aaaad8P" 88 88 88aaaad8P" 88""""" 88 88 88""""Y8ba 88 88 88 88 `8b 88 88 88 88 ,8P 88 Y8b,____,d88, 88_____,d8' 88 "Y888888P"Y8 88888888P" */ pragma solidity ^0.6.12; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * after an initial amount of tokens are minted when the token is created, * the _mint() function will be locked until this time (set upon creation). */ // uint private _mintLockedUntilTimestamp; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ // constructor (string memory name, string memory symbol, uint256 amountToMintOnCreation, uint256 mintLockedDays) public { constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; // // // mint to creator // _mint(msg.sender, amountToMintOnCreation); // // // now lock minting for X days, // // by setting `_mintLockedUntilTimestamp` to prevent _mint()'ing until future time // _mintLockedUntilTimestamp = now.add(mintLockedDays.mul(1 days)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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 SafeMath for uint256; 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' // solhint-disable-next-line max-line-length 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // PubToken contract PubToken is ERC20("PUB.finance","PUB"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Bartender). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } contract Bartender is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PUBs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPubPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPubPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. PUBs to distribute per block. uint256 lastRewardBlock; // Last block number that PUBs distribution occurs. uint256 accPubPerShare; // Accumulated PUBs per share, times 1e12. See below. } // The PUB TOKEN! PubToken public pub; // Block number when bonus PUB period ends. uint256 public bonusEndBlock; // PUB tokens created per block. uint256 public pubPerBlock; // Bonus multiplier for early pub makers. uint256 public constant BONUS_MULTIPLIER = 1; // no bonus // numerator of the owner fee uint256 public constant OWNER_FEE_NUMERATOR = 5; // denominator of the owner fee uint256 public constant OWNER_FEE_DENOMINATOR = 1000; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when PUB mining starts. uint256 public startBlock; // on creation, set to _bonusEndBlock, so set to 99999999, far in the future. event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( //uint256 _pubPerBlock, uint256 _bonusEndBlock, uint256 _startBlock ) public { // we are going to deploy the token from within this // contructor to grant onlyOwner just to this contract. // mint a couple tokens for the express purpose of creating the Uniswap LPs pub = new PubToken(); pubPerBlock = 0; // initial value bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // get the number of farms function poolLength() external view returns (uint256) { return poolInfo.length; } // get the owner of the PUB token (should be this contract) function pubOwner() external view returns (address) { return pub.owner(); } // get the PUB balance of the caller function myPubTokenBalance() external view returns (uint256) { return pub.balanceOf(msg.sender); } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPubPerShare: 0 })); } // get the current number of PUB per block function getPubPerBlock() public view returns (uint256){ return pubPerBlock; } // update the number of PUB per block, with a value in wei function setPubPerBlock(uint256 _pubPerBlock) public onlyOwner { require(_pubPerBlock > 0, "_pubPerBlock must be non-zero"); // update all pools prior to changing the block rewards massUpdatePools(); // update the block rewards pubPerBlock = _pubPerBlock; } // Update the given pool's PUB allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending PUBs on frontend. function pendingPubs(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPubPerShare = pool.accPubPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pubReward = multiplier.mul(pubPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accPubPerShare = accPubPerShare.add(pubReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accPubPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. // updates starting with the 0 index function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pubReward = multiplier.mul(pubPerBlock).mul(pool.allocPoint).div(totalAllocPoint); if(pubReward > 0){ pub.mint(address(this), pubReward); } pool.accPubPerShare = pool.accPubPerShare.add(pubReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Bartender for PUB allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accPubPerShare).div(1e12).sub(user.rewardDebt); safePubTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accPubPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from Bartender. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accPubPerShare).div(1e12).sub(user.rewardDebt); safePubTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accPubPerShare).div(1e12); if(msg.sender != owner()){ // transfer the 0.5% fee to owner uint256 feeAmount = _amount.mul(OWNER_FEE_NUMERATOR).div(OWNER_FEE_DENOMINATOR); _amount = _amount.sub(feeAmount); // transfer the feeAmount to the owner using deposit pool.lpToken.safeTransfer(address(owner()), feeAmount); } // withdraw, using safeTransfer pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; if(msg.sender != owner()){ // transfer the 0.5% fee to owner uint256 feeAmount = amount.mul(OWNER_FEE_NUMERATOR).div(OWNER_FEE_DENOMINATOR); amount = amount.sub(feeAmount); // transfer the feeAmount to the owner using deposit pool.lpToken.safeTransfer(address(owner()), feeAmount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); user.amount = 0; user.rewardDebt = 0; } // Safe pub transfer function, just in case if rounding error causes pool to not have enough PUBs. function safePubTransfer(address _to, uint256 _amount) internal { uint256 pubBal = pub.balanceOf(address(this)); if (_amount > pubBal) { pub.transfer(_to, pubBal); } else { pub.transfer(_to, _amount); } } }
Withdraw without caring about rewards. EMERGENCY ONLY. transfer the 0.5% fee to owner transfer the feeAmount to the owner using deposit
function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; if(msg.sender != owner()){ uint256 feeAmount = amount.mul(OWNER_FEE_NUMERATOR).div(OWNER_FEE_DENOMINATOR); amount = amount.sub(feeAmount); pool.lpToken.safeTransfer(address(owner()), feeAmount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); user.amount = 0; user.rewardDebt = 0; }
10,361,852
./partial_match/1/0x52600AaF44d81E690Ee41e7C0b96a94d40c6eA30/sources/BaseWallet.sol
Sets a new owner for the wallet. _newOwner The new owner./
function setOwner(address _newOwner) external moduleOnly { require(_newOwner != address(0), "BW: address cannot be null"); owner = _newOwner; emit OwnerChanged(_newOwner); }
3,605,560
./partial_match/1/0x5684d5566bb438D8Ef7B3C1E5da9450cD19C1b9f/sources/FraxUnifiedFarm_ERC20_Convex_FRAXBP_Stable.sol
File contracts/Misc_AMOs/convex/IConvexStakingWrapperFrax.sol
interface IConvexStakingWrapperFrax { function addRewards ( ) external; function addTokenReward ( address _token ) external; function allowance ( address owner, address spender ) external view returns ( uint256 ); function approve ( address spender, uint256 amount ) external returns ( bool ); function balanceOf ( address account ) external view returns ( uint256 ); function collateralVault ( ) external view returns ( address ); function convexBooster ( ) external view returns ( address ); function convexPool ( ) external view returns ( address ); function convexPoolId ( ) external view returns ( uint256 ); function convexToken ( ) external view returns ( address ); function crv ( ) external view returns ( address ); function curveToken ( ) external view returns ( address ); function cvx ( ) external view returns ( address ); function decimals ( ) external view returns ( uint8 ); function decreaseAllowance ( address spender, uint256 subtractedValue ) external returns ( bool ); function deposit ( uint256 _amount, address _to ) external; function distroContract ( ) external view returns ( address ); function distroImplementation ( ) external view returns ( address ); function distroSealed ( ) external view returns ( bool ); function earmarkRewards ( ) external returns ( bool ); function factory ( ) external view returns ( address ); function getReward ( address _account, address _forwardTo ) external; function getReward ( address _account ) external; function increaseAllowance ( address spender, uint256 addedValue ) external returns ( bool ); function initialize ( uint256 _poolId ) external; function invalidateReward ( address _token ) external; function isInit ( ) external view returns ( bool ); function isShutdown ( ) external view returns ( bool ); function name ( ) external view returns ( string memory ); function owner ( ) external view returns ( address ); function proxyFactory ( ) external view returns ( address ); function registeredRewards ( address ) external view returns ( uint256 ); function renounceOwnership ( ) external; function rewardHook ( ) external view returns ( address ); function rewardLength ( ) external view returns ( uint256 ); function rewardRedirect ( address ) external view returns ( address ); function rewards ( uint256 ) external view returns ( address reward_token, address reward_pool, uint256 reward_integral, uint256 reward_remaining ); function sealDistributor ( ) external; function setApprovals ( ) external; function setDistributor ( address _distro ) external; function setHook ( address _hook ) external; function setRewardRedirect ( address _to ) external; function setVault ( address _vault ) external; function shutdown ( ) external; function stake ( uint256 _amount, address _to ) external; function symbol ( ) external view returns ( string memory ); function totalBalanceOf ( address _account ) external view returns ( uint256 ); function totalSupply ( ) external view returns ( uint256 ); function transfer ( address recipient, uint256 amount ) external returns ( bool ); function transferFrom ( address sender, address recipient, uint256 amount ) external returns ( bool ); function transferOwnership ( address newOwner ) external; function user_checkpoint ( address _account ) external returns ( bool ); function withdraw ( uint256 _amount ) external; function withdrawAndUnwrap ( uint256 _amount ) external; }
4,115,829
./full_match/5/0x631CadF9267a7784D690AFa0Bd9128760CF555Cf/sources/contracts/libraries/Token.sol
Transfer assets from current address to `_to` address./
function transfer( Info memory _info, address _to, address _token ) internal { bool _success; if (_info.erc == Standard.ERC20) { _success = tryTransferERC20(_token, _to, _info.quantity); _success = tryTransferERC721(_token, _to, _info.id); revert("Token: unsupported token standard"); } if (!_success) { revert( string( abi.encodePacked( "Token: could not transfer ", toString(_info), " to ", Strings.toHexString(uint160(_to), 20), " token ", Strings.toHexString(uint160(_token), 20) ) ) ); } }
1,908,471
./full_match/5/0x0000D22bab9d6AF0104FDd6b05bF3e179b06A282/sources/project_/contracts/NewDawnPaymentForwarder.sol
switch for trading toggle
function toggleTrading() external onlyAdmin { tradingToggle = !tradingToggle; emit UpdatedTradingStatus(tradingToggle); }
1,912,635
pragma solidity ^0.5.16; // Inheritance import "./BaseSynthetix.sol"; // https://docs.synthetix.io/contracts/source/contracts/mintablesynthetix contract MintableSynthetix is BaseSynthetix { bytes32 private constant CONTRACT_SYNTHETIX_BRIDGE = "SynthetixBridgeToBase"; constructor( address payable _proxy, TokenState _tokenState, address _owner, uint _totalSupply, address _resolver ) public BaseSynthetix(_proxy, _tokenState, _owner, _totalSupply, _resolver) {} /* ========== INTERNALS =================== */ function _mintSecondary(address account, uint amount) internal { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); emitTransfer(address(this), account, amount); totalSupply = totalSupply.add(amount); } function onlyAllowFromBridge() internal view { require(msg.sender == synthetixBridge(), "Can only be invoked by bridge"); } /* ========== MODIFIERS =================== */ modifier onlyBridge() { onlyAllowFromBridge(); _; } /* ========== VIEWS ======================= */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = BaseSynthetix.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](1); newAddresses[0] = CONTRACT_SYNTHETIX_BRIDGE; addresses = combineArrays(existingAddresses, newAddresses); } function synthetixBridge() internal view returns (address) { return requireAndGetAddress(CONTRACT_SYNTHETIX_BRIDGE); } /* ========== RESTRICTED FUNCTIONS ========== */ function mintSecondary(address account, uint amount) external onlyBridge { _mintSecondary(account, amount); } function mintSecondaryRewards(uint amount) external onlyBridge { IRewardsDistribution _rewardsDistribution = rewardsDistribution(); _mintSecondary(address(_rewardsDistribution), amount); _rewardsDistribution.distributeRewards(amount); } function burnSecondary(address account, uint amount) external onlyBridge systemActive { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); emitTransfer(account, address(0), amount); totalSupply = totalSupply.sub(amount); } }
========== INTERNALS =================== /
function _mintSecondary(address account, uint amount) internal { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); emitTransfer(address(this), account, amount); totalSupply = totalSupply.add(amount); }
6,353,486
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } } /* Required code start */ contract MarketplaceProxy { function calculatePlatformCommission(uint256 weiAmount) public view returns (uint256); function payPlatformIncomingTransactionCommission(address clientAddress) public payable; function payPlatformOutgoingTransactionCommission() public payable; function isUserBlockedByContract(address contractAddress) public view returns (bool); } /* Required code end */ contract Deposit is Ownable { using SafeMath for uint256; struct ClientDeposit { uint256 balance; // We should reject incoming transactions on payable // methods that not equals this variable uint256 nextPaymentTotalAmount; uint256 nextPaymentDepositCommission; // deposit commission stored on contract uint256 nextPaymentPlatformCommission; bool exists; bool isBlocked; } mapping(address => ClientDeposit) public depositsMap; /* Required code start */ MarketplaceProxy public mp; event PlatformIncomingTransactionCommission(uint256 amount, address clientAddress); event PlatformOutgoingTransactionCommission(uint256 amount); event Blocked(); /* Required code end */ event DepositCommission(uint256 amount, address clientAddress); constructor () public { /* Required code start */ // NOTE: CHANGE ADDRESS ON PRODUCTION mp = MarketplaceProxy(0x17b38d3779debcf1079506522e10284d3c6b0fef); /* Required code end */ } /** * @dev Handles direct clients transactions */ function () public payable { handleIncomingPayment(msg.sender, msg.value); } /** * @dev Handles payment gateway transactions * @param clientAddress when payment method is fiat money */ function fromPaymentGateway(address clientAddress) public payable { handleIncomingPayment(clientAddress, msg.value); } /** * @dev Send commission to marketplace and increases client balance * @param clientAddress client wallet for deposit * @param amount transaction value (msg.value) */ function handleIncomingPayment(address clientAddress, uint256 amount) private { ClientDeposit storage clientDeposit = depositsMap[clientAddress]; require(clientDeposit.exists); require(clientDeposit.nextPaymentTotalAmount == amount); /* Required code start */ // Send all incoming eth if user blocked if (mp.isUserBlockedByContract(address(this))) { mp.payPlatformIncomingTransactionCommission.value(amount)(clientAddress); emit Blocked(); } else { mp.payPlatformIncomingTransactionCommission.value(clientDeposit.nextPaymentPlatformCommission)(clientAddress); emit PlatformIncomingTransactionCommission(clientDeposit.nextPaymentPlatformCommission, clientAddress); } /* Required code end */ // Virtually add ETH to client deposit (sended ETH subtract platform and deposit commissions) clientDeposit.balance += amount.sub(clientDeposit.nextPaymentPlatformCommission).sub(clientDeposit.nextPaymentDepositCommission); emit DepositCommission(clientDeposit.nextPaymentDepositCommission, clientAddress); } /** * @dev Owner can add ETH to contract without commission */ function addEth() public payable onlyOwner { } /** * @dev Owner can transfer ETH from contract to address * @param to address * @param amount 18 decimals (wei) */ function transferEthTo(address to, uint256 amount) public onlyOwner { require(address(this).balance > amount); /* Required code start */ // Get commission amount from marketplace uint256 commission = mp.calculatePlatformCommission(amount); require(address(this).balance > amount.add(commission)); // Send commission to marketplace mp.payPlatformOutgoingTransactionCommission.value(commission)(); emit PlatformOutgoingTransactionCommission(commission); /* Required code end */ to.transfer(amount); } /** * @dev Send client's balance to some address on claim * @param from client address * @param to send ETH on this address * @param amount 18 decimals (wei) */ function claim(address from, address to, uint256 amount) public onlyOwner{ require(depositsMap[from].exists); /* Required code start */ // Get commission amount from marketplace uint256 commission = mp.calculatePlatformCommission(amount); require(address(this).balance > amount.add(commission)); require(depositsMap[from].balance > amount); // Send commission to marketplace mp.payPlatformOutgoingTransactionCommission.value(commission)(); emit PlatformOutgoingTransactionCommission(commission); /* Required code end */ // Virtually subtract amount from client deposit depositsMap[from].balance -= amount; to.transfer(amount); } /** * @return bool, client exist or not */ function isClient(address clientAddress) public view onlyOwner returns(bool) { return depositsMap[clientAddress].exists; } /** * @dev Add new client to structure * @param clientAddress wallet * @param _nextPaymentTotalAmount reject next incoming payable transaction if it's amount not equal to this variable * @param _nextPaymentDepositCommission deposit commission stored on contract * @param _nextPaymentPlatformCommission marketplace commission to send */ function addClient(address clientAddress, uint256 _nextPaymentTotalAmount, uint256 _nextPaymentDepositCommission, uint256 _nextPaymentPlatformCommission) public onlyOwner { require( (clientAddress != address(0))); // Can be called only once for address require(!depositsMap[clientAddress].exists); // Add new element to structure depositsMap[clientAddress] = ClientDeposit( 0, // balance _nextPaymentTotalAmount, // nextPaymentTotalAmount _nextPaymentDepositCommission, // nextPaymentDepositCommission _nextPaymentPlatformCommission, // nextPaymentPlatformCommission true, // exists false // isBlocked ); } /** * @return uint256 client balance */ function getClientBalance(address clientAddress) public view returns(uint256) { return depositsMap[clientAddress].balance; } /** * @dev Update client payment details * @param clientAddress wallet * @param _nextPaymentTotalAmount reject next incoming payable transaction if it's amount not equal to this variable * @param _nextPaymentDepositCommission deposit commission stored on contract * @param _nextPaymentPlatformCommission marketplace commission to send */ function repeatedPayment(address clientAddress, uint256 _nextPaymentTotalAmount, uint256 _nextPaymentDepositCommission, uint256 _nextPaymentPlatformCommission) public onlyOwner { ClientDeposit storage clientDeposit = depositsMap[clientAddress]; require(clientAddress != address(0)); require(clientDeposit.exists); clientDeposit.nextPaymentTotalAmount = _nextPaymentTotalAmount; clientDeposit.nextPaymentDepositCommission = _nextPaymentDepositCommission; clientDeposit.nextPaymentPlatformCommission = _nextPaymentPlatformCommission; } }
Add new client to structure clientAddress wallet _nextPaymentTotalAmount reject next incoming payable transaction if it's amount not equal to this variable _nextPaymentDepositCommission deposit commission stored on contract _nextPaymentPlatformCommission marketplace commission to send/ Can be called only once for address Add new element to structure
function addClient(address clientAddress, uint256 _nextPaymentTotalAmount, uint256 _nextPaymentDepositCommission, uint256 _nextPaymentPlatformCommission) public onlyOwner { require( (clientAddress != address(0))); require(!depositsMap[clientAddress].exists); depositsMap[clientAddress] = ClientDeposit( ); }
12,808,420
pragma ton-solidity >= 0.53.0; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; pragma ignoreIntOverflow; pragma msgValue 1e10; //import './import.sol'; library MathHelper { // State variables are forbidden in library but constants are not uint constant MAX_VALUE = 300; uint t = now; uint a = 100000000000000_000; // Library function function sum(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c < MAX_VALUE); return c; } } interface TestInterface {} contract Test { enum testEnum {item1, item2} event name(address addr); mapping (uint=>string) testMapping; uint static a; // ok uint public static b; struct Name { uint b; } constructor(uint a) public {} function testFunc1(uint b) public { for (uint256 index = 0; index > 100; index++) {} if (true) { } else { } //Name.unpack(); uint[] arr; require(arr.empty()); arr.push(); require(!arr.empty()); } modifier testModifier() { _; } function fview(uint b) view public returns (uint) { repeat(10) { } for ((uint256 key, string value) : testMapping) { // iteration over mapping } bytes byteArray = "Hello!"; for (byte d : byteArray) { } return b; } function fret(uint c) internal returns (uint) { return c; } TvmCell tcellvar; uint32 key; uint256 value; function tvmcellfunc() public { tcellvar.depth(); tcellvar.dataSize(10); tcellvar.dataSizeQ(1); tcellvar.toSlice(); } function optTest() public { optional(uint) opt; opt.set(11); opt = 22; opt.get() = 33; opt.reset(); optional(uint) x = 123; opt.hasValue(); } function vectorTest() public { vector(uint) vect; uint a = 11; vect.push(a); vect.push(111); vect.pop(); vect.length(); vect.empty(); } function tonUnits() public { require(1 nano == 1); require(1 nanoton == 1); require(1 nTon == 1); require(1 ton == 1e9 nanoton); require(1 Ton == 1e9 nanoton); require(1 micro == 1e-6 ton); require(1 microton == 1e-6 ton); require(1 milli == 1e-3 ton); require(1 milliton == 1e-3 ton); require(1 kiloton == 1e3 ton); require(1 kTon == 1e3 ton); require(1 megaton == 1e6 ton); require(1 MTon == 1e6 ton); require(1 gigaton == 1e9 ton); require(1 GTon == 1e9 ton); require(1 nanoever == 1); require(1 ever == 1e9 nanoever); require(1 Ever == 1e9 nanoever); require(1 microever == 1e-6 ever); require(1 milliever == 1e-3 ever); require(1 kiloever == 1e3 ton); require(1 kEver == 1e3 ton); require(1 megaever == 1e6 ton); require(1 MEver == 1e6 ton); require(1 gigaever == 1e9 ton); require(1 GEver == 1e9 ton); } function dst(TvmCell message, uint n, uint16 u16, uint8 u8) public { message.depth(); message.dataSize(n); message.dataSizeQ(n); TvmSlice s = message.toSlice(); s.empty(); s.size(); s.bits(); s.refs(); s.dataSize(n); s.dataSizeQ(n); s.depth(); s.hasNBits(u16); s.hasNRefs(u8); s.hasNBitsAndRefs(u16, u8); s.compare(s); s.decode(uint8, uint16); s.loadRef(); s.loadRefAsSlice(); s.loadSigned(u16); s.loadUnsigned(u16); s.loadTons(); s.loadSlice(n); s.decodeFunctionParams(dst); s.skip(n,n); TvmBuilder builder; builder.toSlice(); builder.toCell(); //builder.size(); builder.bits(); builder.refs(); builder.remBits(); builder.remRefs(); builder.remBitsAndRefs(); builder.depth(); builder.store(message, n, u16, u8); builder.storeOnes(n); //builder.storeZeroes(0); builder.storeSigned(int(-109), u16); builder.storeUnsigned(u8,u16); builder.storeRef(message); builder.storeTons(uint128(10)); ExtraCurrencyCollection curCol; optional(uint32, uint256) res = curCol.min(); res = curCol.next(1); res = curCol.prev(1); res = curCol.nextOrEq(1); res = curCol.prevOrEq(1); res = curCol.delMin(); res = curCol.delMax(); //res = curCol.fetch(k); bool exists = curCol.exists(key); bool isEmpty = curCol.empty(); bool success = curCol.replace(key, value); success = curCol.add(key, value); bool index; //success = curCol[index]; } function other(string s, bytes b, uint i) public { tvm.setGasLimit(100000); b.empty(); bytes byteArray = "abba"; int index = 0; byte a0 = byteArray[i]; byteArray = "01234567890123456789"; bytes slice = byteArray[5:10]; bytes etalon = "56789"; require(slice == etalon); slice = byteArray[10:]; etalon = "0123456789"; require(slice == etalon); slice = byteArray[:10]; require(slice == etalon); slice = byteArray[:]; require(slice == byteArray); require(byteArray[:10] == etalon); require(etalon == byteArray[:10]); b.dataSize(i); b.dataSizeQ(i); b.append(b); byteArray = "1234"; //bytes4 bb = byteArray; s.byteLength(); s.substr(i); //s.find(s); //s.findLast(s); string str = format("Hello {} 0x{:X} {} {}.{} tons", 123, 255, address.makeAddrStd(-33,0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF123456789ABCDE), 100500, 32); require(str == "Hello 123 0xFF -21:7fffffffffffffffffffffffffffffffffffffffffffffffff123456789abcde 100500.32 tons", 101); require(format("Hello {}", 123) == "Hello 123", 102); require(format("Hello 0x{:X}", 123) == "Hello 0x7B", 103); require(format("{}", -123) == "-123", 103); require(format("{}", address.makeAddrStd(127,0)) == "7f:0000000000000000000000000000000000000000000000000000000000000000", 104); require(format("{}", address.makeAddrStd(-128,0)) == "-80:0000000000000000000000000000000000000000000000000000000000000000", 105); require(format("{:6}", 123) == " 123", 106); require(format("{:06}", 123) == "000123", 107); require(format("{:06d}", 123) == "000123", 108); require(format("{:06X}", 123) == "00007B", 109); require(format("{:6x}", 123) == " 7b", 110); uint128 a = 1 ton; require(format("{:t}", a) == "1.000000000", 101); a = 123; require(format("{:t}", a) == "0.000000123", 103); fixed32x3 v = 1.5; require(format("{}", v) == "1.500", 106); fixed256x10 vv = -987123.4567890321; require(format("{}", vv) == "-987123.4567890321", 108); uint res; bool status; (res, status) = stoi("123"); require(status, 111); require(res == 123, 101); string hexstr = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF123456789ABCDE"; uint num = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF123456789ABCDE; (res, status) = stoi(hexstr); require(status, 112); require(res == num, 102); (res, status) = stoi("0xag"); require(!status, 116); uint address_value; address addrStd = address(address_value); int8 wid; uint addr; address addrr = address.makeAddrStd(wid, addr); address addrNone = address.makeAddrNone(); uint addrNumber; uint bitCnt; address addrExtern = address.makeAddrExtern(addrNumber, bitCnt); //addrr.wid(); address(this).currencies; address(this).balance; address(this).getType(); address dest = address(0); uint128 m = 100000; bool bounce = true; uint16 flag = 2; TvmCell body; ExtraCurrencyCollection c; TvmCell stateInit; // sequential order of parameters dest.transfer(m); dest.transfer(m, bounce); dest.transfer(m, bounce, flag); dest.transfer(m, bounce, flag, body); dest.transfer(m, bounce, flag, body, c); // using named parameters dest.transfer({value: m, bounce: false, flag: 128, body: body, currencies: c}); dest.transfer({bounce: false, value: 1 ton, flag: 128, body: body}); dest.transfer({value: 1 ton, bounce: false}); testMapping.min(); testMapping.max(); testMapping.next(1); testMapping.prev(1); testMapping.nextOrEq(1); testMapping.prevOrEq(1); testMapping.fetch(1); testMapping.exists(1); testMapping.empty(); testMapping.replace(1,'2'); testMapping.add(1,'2'); testMapping.getSet(1,'2'); testMapping.getAdd(1,'2'); testMapping.getReplace(1,'2'); } function getSum(int a, int b) internal pure returns (int) { return a + b; } function getSub(int a, int b) internal pure returns (int) { return a - b; } function process(int a, int b, uint8 mode) public returns (int) { function (int, int) returns (int) fun; if (mode == 0) { fun = getSum; } else if (mode == 1) { fun = getSub; } return fun(a, b); // if `fun` isn't initialized then exception is thrown } function re() public { uint a = 5; TvmCell m_cell; require(a == 5); // ok require(a == 6); // throws an exception with code 100 require(a == 6, 101); // throws an exception with code 101 require(a == 6, 101, "a is not equal to six"); // throws an exception with code 101 and string require(a == 6, 101, a); // throws an exception with code 101 and number a a = 5; revert(); // throw exception 100 revert(101); // throw exception 101 revert(102, "We have a some problem"); // throw exception 102 and string revert(101, a); // throw exception 101 and number a msg.sender; msg.value; msg.currencies; msg.pubkey(); msg.isExternal; msg.isInternal; msg.createdAt; msg.data; tvm.accept(); tvm.commit(); tvm.rawCommit(); //tvm.getData(); TvmCell c; tvm.setData(c); tvm.log('log'); TvmBuilder bld; bld.storeUnsigned(0x9876543210, 40); c = bld.toCell(); tvm.hexdump(a); tvm.bindump(c); a = 123; tvm.hexdump(a); tvm.bindump(a); int b = -333; tvm.hexdump(b); tvm.bindump(b); tvm.setcode(c); tvm.configParam(a); tvm.rawReserve(1, 2); tvm.hash('string'); tvm.insertPubkey(c, msg.pubkey()); tvm.buildStateInit(c,c); tvm.stateInitHash(256, 256, 256, 16); tvm.buildEmptyData(msg.pubkey()); TvmCell code = tvm.code(); tvm.codeSalt(code); TvmCell salt; tvm.setCodeSalt(code, salt); tvm.pubkey(); tvm.setPubkey(msg.pubkey()); tvm.setCurrentCode(code); tvm.resetStorage(); tvm.functionId(dst); tvm.encodeBody(dst,dst, a); tvm.exit(); tvm.exit1(); uint8 flag; TvmCell msg; tvm.sendrawmsg(msg, flag); uint a = 1; uint b = 2; math.min(a, b); math.max(a, b); math.minmax(a, b); math.abs(a); math.modpow2(a, b); math.divc(a, b); math.divr(a, b); math.muldiv(a, b); math.muldivc(a, b); math.muldivmod(a, b); math.divmod(a, b); tx.timestamp; //block.timestamp; rnd.next(10); rnd.getSeed(); rnd.setSeed(a); rnd.shuffle(); uint b = 3; uint32 p = 4; uint res = b ** p; require(res == 81); selfdestruct(address(0)); TvmSlice s; sha256(s); gasToValue(1000, 0); valueToGas(10000, 0); tvm.buildExtMsg({ dest: address, time:uint64, expire:uint64, call:{f1}, sign:bool, pubkey:optional(uint256), abiVer:uint8, callbackId:uint32, onErrorId:uint32, stateInit:TvmCell, signBoxHandle:optional(uint32) }); tvm.buildIntMsg({ dest:address, value:uint128, call:{f1}, bounce:bool, currencies:ExtraCurrencyCollection }); } fallback() external { } onBounce(TvmSlice body) external { /*...*/ } onTickTock(bool isTock) external { /*...*/ } function onCodeUpgrade() private{ /*...*/ } function f1() public pure functionID(123) { /*...*/ } function f2() public externalMsg { // this function receives only external messages /*...*/ } function test(uint b) public { Foo(address(this)).bar{expire: 0x12345, time: 0x123}(123, 45).extMsg; f1(); } }
bytes4 bb = byteArray;s.find(s);s.findLast(s);addrr.wid(); sequential order of parameters using named parameters
function other(string s, bytes b, uint i) public { tvm.setGasLimit(100000); b.empty(); bytes byteArray = "abba"; int index = 0; byte a0 = byteArray[i]; byteArray = "01234567890123456789"; bytes slice = byteArray[5:10]; bytes etalon = "56789"; require(slice == etalon); slice = byteArray[10:]; etalon = "0123456789"; require(slice == etalon); slice = byteArray[:10]; require(slice == etalon); slice = byteArray[:]; require(slice == byteArray); require(byteArray[:10] == etalon); require(etalon == byteArray[:10]); b.dataSize(i); b.dataSizeQ(i); b.append(b); byteArray = "1234"; s.byteLength(); s.substr(i); require(str == "Hello 123 0xFF -21:7fffffffffffffffffffffffffffffffffffffffffffffffff123456789abcde 100500.32 tons", 101); uint128 a = 1 ton; a = 123; fixed32x3 v = 1.5; fixed256x10 vv = -987123.4567890321; uint res; bool status; (res, status) = stoi("123"); require(status, 111); require(res == 123, 101); string hexstr = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF123456789ABCDE"; uint num = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF123456789ABCDE; (res, status) = stoi(hexstr); require(status, 112); require(res == num, 102); (res, status) = stoi("0xag"); require(!status, 116); uint address_value; address addrStd = address(address_value); int8 wid; uint addr; address addrr = address.makeAddrStd(wid, addr); address addrNone = address.makeAddrNone(); uint addrNumber; uint bitCnt; address addrExtern = address.makeAddrExtern(addrNumber, bitCnt); address(this).currencies; address(this).balance; address(this).getType(); address dest = address(0); uint128 m = 100000; bool bounce = true; uint16 flag = 2; TvmCell body; ExtraCurrencyCollection c; TvmCell stateInit; dest.transfer(m); dest.transfer(m, bounce); dest.transfer(m, bounce, flag); dest.transfer(m, bounce, flag, body); dest.transfer(m, bounce, flag, body, c); testMapping.min(); testMapping.max(); testMapping.next(1); testMapping.prev(1); testMapping.nextOrEq(1); testMapping.prevOrEq(1); testMapping.fetch(1); testMapping.exists(1); testMapping.empty(); testMapping.replace(1,'2'); testMapping.add(1,'2'); testMapping.getSet(1,'2'); testMapping.getAdd(1,'2'); testMapping.getReplace(1,'2'); string str = format("Hello {} 0x{:X} {} {}.{} tons", 123, 255, address.makeAddrStd(-33,0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF123456789ABCDE), 100500, 32); require(format("Hello {}", 123) == "Hello 123", 102); require(format("Hello 0x{:X}", 123) == "Hello 0x7B", 103); require(format("{}", -123) == "-123", 103); require(format("{}", address.makeAddrStd(127,0)) == "7f:0000000000000000000000000000000000000000000000000000000000000000", 104); require(format("{}", address.makeAddrStd(-128,0)) == "-80:0000000000000000000000000000000000000000000000000000000000000000", 105); require(format("{:6}", 123) == " 123", 106); require(format("{:06}", 123) == "000123", 107); require(format("{:06d}", 123) == "000123", 108); require(format("{:06X}", 123) == "00007B", 109); require(format("{:6x}", 123) == " 7b", 110); require(format("{:t}", a) == "1.000000000", 101); require(format("{:t}", a) == "0.000000123", 103); require(format("{}", v) == "1.500", 106); require(format("{}", vv) == "-987123.4567890321", 108); dest.transfer({value: m, bounce: false, flag: 128, body: body, currencies: c}); dest.transfer({bounce: false, value: 1 ton, flag: 128, body: body}); dest.transfer({value: 1 ton, bounce: false}); }
1,050,102