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: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./WSSLPUserProxy.sol"; import "../../helpers/ReentrancyGuard.sol"; import "../../helpers/TransferHelper.sol"; import "../../Auth2.sol"; import "../../interfaces/IVault.sol"; import "../../interfaces/IERC20WithOptional.sol"; import "../../interfaces/wrapped-assets/IWrappedAsset.sol"; import "../../interfaces/wrapped-assets/ITopDog.sol"; import "../../interfaces/wrapped-assets/ISushiSwapLpToken.sol"; /** * @title ShibaSwapWrappedLp **/ contract WrappedShibaSwapLp is IWrappedAsset, Auth2, ERC20, ReentrancyGuard { using SafeMath for uint256; bytes32 public constant override isUnitProtocolWrappedAsset = keccak256("UnitProtocolWrappedAsset"); IVault public immutable vault; ITopDog public immutable topDog; uint256 public immutable topDogPoolId; IERC20 public immutable boneToken; address public immutable userProxyImplementation; mapping(address => WSSLPUserProxy) public usersProxies; mapping (address => mapping (bytes4 => bool)) allowedBoneLockersSelectors; address public feeReceiver; uint8 public feePercent = 10; constructor( address _vaultParameters, ITopDog _topDog, uint256 _topDogPoolId, address _feeReceiver ) Auth2(_vaultParameters) ERC20( string( abi.encodePacked( "Wrapped by Unit ", getSsLpTokenName(_topDog, _topDogPoolId), " ", getSsLpTokenToken0Symbol(_topDog, _topDogPoolId), "-", getSsLpTokenToken1Symbol(_topDog, _topDogPoolId) ) ), string( abi.encodePacked( "wu", getSsLpTokenSymbol(_topDog, _topDogPoolId), getSsLpTokenToken0Symbol(_topDog, _topDogPoolId), getSsLpTokenToken1Symbol(_topDog, _topDogPoolId) ) ) ) { boneToken = _topDog.bone(); topDog = _topDog; topDogPoolId = _topDogPoolId; vault = IVault(VaultParameters(_vaultParameters).vault()); _setupDecimals(IERC20WithOptional(getSsLpToken(_topDog, _topDogPoolId)).decimals()); feeReceiver = _feeReceiver; userProxyImplementation = address(new WSSLPUserProxy(_topDog, _topDogPoolId)); } function setFeeReceiver(address _feeReceiver) public onlyManager { feeReceiver = _feeReceiver; emit FeeReceiverChanged(_feeReceiver); } function setFee(uint8 _feePercent) public onlyManager { require(_feePercent <= 50, "Unit Protocol Wrapped Assets: INVALID_FEE"); feePercent = _feePercent; emit FeeChanged(_feePercent); } /** * @dev in case of change bone locker to unsupported by current methods one */ function setAllowedBoneLockerSelector(address _boneLocker, bytes4 _selector, bool _isAllowed) public onlyManager { allowedBoneLockersSelectors[_boneLocker][_selector] = _isAllowed; if (_isAllowed) { emit AllowedBoneLockerSelectorAdded(_boneLocker, _selector); } else { emit AllowedBoneLockerSelectorRemoved(_boneLocker, _selector); } } /** * @notice Approve sslp token to spend from user proxy (in case of change sslp) */ function approveSslpToTopDog() public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); IERC20 sslpToken = getUnderlyingToken(); userProxy.approveSslpToTopDog(sslpToken); } /** * @notice Get tokens from user, send them to TopDog, sent to user wrapped tokens * @dev only user or CDPManager could call this method */ function deposit(address _user, uint256 _amount) public override nonReentrant { require(_amount > 0, "Unit Protocol Wrapped Assets: INVALID_AMOUNT"); require(msg.sender == _user || vaultParameters.canModifyVault(msg.sender), "Unit Protocol Wrapped Assets: AUTH_FAILED"); IERC20 sslpToken = getUnderlyingToken(); WSSLPUserProxy userProxy = _getOrCreateUserProxy(_user, sslpToken); // get tokens from user, need approve of sslp tokens to pool TransferHelper.safeTransferFrom(address(sslpToken), _user, address(userProxy), _amount); // deposit them to TopDog userProxy.deposit(_amount); // wrapped tokens to user _mint(_user, _amount); emit Deposit(_user, _amount); } /** * @notice Unwrap tokens, withdraw from TopDog and send them to user * @dev only user or CDPManager could call this method */ function withdraw(address _user, uint256 _amount) public override nonReentrant { require(_amount > 0, "Unit Protocol Wrapped Assets: INVALID_AMOUNT"); require(msg.sender == _user || vaultParameters.canModifyVault(msg.sender), "Unit Protocol Wrapped Assets: AUTH_FAILED"); IERC20 sslpToken = getUnderlyingToken(); WSSLPUserProxy userProxy = _requireUserProxy(_user); // get wrapped tokens from user _burn(_user, _amount); // withdraw funds from TopDog userProxy.withdraw(sslpToken, _amount, _user); emit Withdraw(_user, _amount); } /** * @notice Manually move position (or its part) to another user (for example in case of liquidation) * @dev Important! Use only with additional token transferring outside this function (example: liquidation - tokens are in vault and transferred by vault) * @dev only CDPManager could call this method */ function movePosition(address _userFrom, address _userTo, uint256 _amount) public override nonReentrant hasVaultAccess { require(_userFrom != address(vault) && _userTo != address(vault), "Unit Protocol Wrapped Assets: NOT_ALLOWED_FOR_VAULT"); if (_userFrom == _userTo || _amount == 0) { return; } IERC20 sslpToken = getUnderlyingToken(); WSSLPUserProxy userFromProxy = _requireUserProxy(_userFrom); WSSLPUserProxy userToProxy = _getOrCreateUserProxy(_userTo, sslpToken); userFromProxy.withdraw(sslpToken, _amount, address(userToProxy)); userToProxy.deposit(_amount); emit Withdraw(_userFrom, _amount); emit Deposit(_userTo, _amount); emit PositionMoved(_userFrom, _userTo, _amount); } /** * @notice Calculates pending reward for user. Not taken into account unclaimed reward from BoneLockers. * @notice Use getClaimableRewardFromBoneLocker to calculate unclaimed reward from BoneLockers */ function pendingReward(address _user) public override view returns (uint256) { WSSLPUserProxy userProxy = usersProxies[_user]; if (address(userProxy) == address(0)) { return 0; } return userProxy.pendingReward(feeReceiver, feePercent); } /** * @notice Claim pending direct reward for user. * @notice Use claimRewardFromBoneLockers claim reward from BoneLockers */ function claimReward(address _user) public override nonReentrant { require(_user == msg.sender, "Unit Protocol Wrapped Assets: AUTH_FAILED"); WSSLPUserProxy userProxy = _requireUserProxy(_user); userProxy.claimReward(_user, feeReceiver, feePercent); } /** * @notice Get claimable amount from BoneLocker * @param _user user address * @param _boneLocker BoneLocker to check, pass zero address to check current */ function getClaimableRewardFromBoneLocker(address _user, IBoneLocker _boneLocker) public view returns (uint256) { WSSLPUserProxy userProxy = usersProxies[_user]; if (address(userProxy) == address(0)) { return 0; } return userProxy.getClaimableRewardFromBoneLocker(_boneLocker, feeReceiver, feePercent); } /** * @notice Claim bones from BoneLockers * @notice Since it could be a lot of pending rewards items parameters are used limit tx size * @param _boneLocker BoneLocker to claim, pass zero address to claim from current * @param _maxBoneLockerRewardsAtOneClaim max amount of rewards items to claim from BoneLocker, pass 0 to claim all rewards */ function claimRewardFromBoneLocker(IBoneLocker _boneLocker, uint256 _maxBoneLockerRewardsAtOneClaim) public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); userProxy.claimRewardFromBoneLocker(msg.sender, _boneLocker, _maxBoneLockerRewardsAtOneClaim, feeReceiver, feePercent); } /** * @notice get SSLP token * @dev not immutable since it could be changed in TopDog */ function getUnderlyingToken() public override view returns (IERC20) { (IERC20 _sslpToken,,,) = topDog.poolInfo(topDogPoolId); return _sslpToken; } /** * @notice Withdraw tokens from topdog to user proxy without caring about rewards. EMERGENCY ONLY. * @notice To withdraw tokens from user proxy to user use `withdrawToken` */ function emergencyWithdraw() public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); uint amount = userProxy.getDepositedAmount(); _burn(msg.sender, amount); assert(balanceOf(msg.sender) == 0); userProxy.emergencyWithdraw(); emit EmergencyWithdraw(msg.sender, amount); } function withdrawToken(address _token, uint _amount) public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); userProxy.withdrawToken(_token, msg.sender, _amount, feeReceiver, feePercent); emit TokenWithdraw(msg.sender, _token, _amount); } function readBoneLocker(address _user, address _boneLocker, bytes calldata _callData) public view returns (bool success, bytes memory data) { WSSLPUserProxy userProxy = _requireUserProxy(_user); (success, data) = userProxy.readBoneLocker(_boneLocker, _callData); } function callBoneLocker(address _boneLocker, bytes calldata _callData) public nonReentrant returns (bool success, bytes memory data) { bytes4 selector; assembly { selector := calldataload(_callData.offset) } require(allowedBoneLockersSelectors[_boneLocker][selector], "Unit Protocol Wrapped Assets: UNSUPPORTED_SELECTOR"); WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); (success, data) = userProxy.callBoneLocker(_boneLocker, _callData); } /** * @dev Get sslp token for using in constructor */ function getSsLpToken(ITopDog _topDog, uint256 _topDogPoolId) private view returns (address) { (IERC20 _sslpToken,,,) = _topDog.poolInfo(_topDogPoolId); return address(_sslpToken); } /** * @dev Get symbol of sslp token for using in constructor */ function getSsLpTokenSymbol(ITopDog _topDog, uint256 _topDogPoolId) private view returns (string memory) { return IERC20WithOptional(getSsLpToken(_topDog, _topDogPoolId)).symbol(); } /** * @dev Get name of sslp token for using in constructor */ function getSsLpTokenName(ITopDog _topDog, uint256 _topDogPoolId) private view returns (string memory) { return IERC20WithOptional(getSsLpToken(_topDog, _topDogPoolId)).name(); } /** * @dev Get token0 symbol of sslp token for using in constructor */ function getSsLpTokenToken0Symbol(ITopDog _topDog, uint256 _topDogPoolId) private view returns (string memory) { return IERC20WithOptional(address(ISushiSwapLpToken(getSsLpToken(_topDog, _topDogPoolId)).token0())).symbol(); } /** * @dev Get token1 symbol of sslp token for using in constructor */ function getSsLpTokenToken1Symbol(ITopDog _topDog, uint256 _topDogPoolId) private view returns (string memory) { return IERC20WithOptional(address(ISushiSwapLpToken(getSsLpToken(_topDog, _topDogPoolId)).token1())).symbol(); } /** * @dev No direct transfers between users allowed since we store positions info in userInfo. */ function _transfer(address sender, address recipient, uint256 amount) internal override onlyVault { require(sender == address(vault) || recipient == address(vault), "Unit Protocol Wrapped Assets: AUTH_FAILED"); super._transfer(sender, recipient, amount); } function _requireUserProxy(address _user) internal view returns (WSSLPUserProxy userProxy) { userProxy = usersProxies[_user]; require(address(userProxy) != address(0), "Unit Protocol Wrapped Assets: NO_DEPOSIT"); } function _getOrCreateUserProxy(address _user, IERC20 sslpToken) internal returns (WSSLPUserProxy userProxy) { userProxy = usersProxies[_user]; if (address(userProxy) == address(0)) { // create new userProxy = WSSLPUserProxy(createClone(userProxyImplementation)); userProxy.approveSslpToTopDog(sslpToken); usersProxies[_user] = userProxy; } } /** * @dev see https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol */ function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } } // 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 "../../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: bsl-1.1 /* Copyright 2022 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; // have to use OZ safemath since it is used in WSSLP import "../../interfaces/wrapped-assets/ITopDog.sol"; import "../../helpers/TransferHelper.sol"; /** * @title WSSLPUserProxy **/ contract WSSLPUserProxy { using SafeMath for uint256; address public immutable manager; ITopDog public immutable topDog; uint256 public immutable topDogPoolId; IERC20 public immutable boneToken; modifier onlyManager() { require(msg.sender == manager, "Unit Protocol Wrapped Assets: AUTH_FAILED"); _; } constructor(ITopDog _topDog, uint256 _topDogPoolId) { manager = msg.sender; topDog = _topDog; topDogPoolId = _topDogPoolId; boneToken = _topDog.bone(); } /** * @dev in case of change sslp */ function approveSslpToTopDog(IERC20 _sslpToken) public onlyManager { TransferHelper.safeApprove(address(_sslpToken), address(topDog), type(uint256).max); } function deposit(uint256 _amount) public onlyManager { topDog.deposit(topDogPoolId, _amount); } function withdraw(IERC20 _sslpToken, uint256 _amount, address _sentTokensTo) public onlyManager { topDog.withdraw(topDogPoolId, _amount); TransferHelper.safeTransfer(address(_sslpToken), _sentTokensTo, _amount); } function pendingReward(address _feeReceiver, uint8 _feePercent) public view returns (uint) { uint balance = boneToken.balanceOf(address(this)); uint pending = topDog.pendingBone(topDogPoolId, address(this)).mul(topDog.rewardMintPercent()).div(100); (uint amountWithoutFee, ) = _calcFee(balance.add(pending), _feeReceiver, _feePercent); return amountWithoutFee; } function claimReward(address _user, address _feeReceiver, uint8 _feePercent) public onlyManager { topDog.deposit(topDogPoolId, 0); // get current reward (no separate methods) _sendAllBonesToUser(_user, _feeReceiver, _feePercent); } function _calcFee(uint _amount, address _feeReceiver, uint8 _feePercent) internal pure returns (uint amountWithoutFee, uint fee) { if (_feePercent == 0 || _feeReceiver == address(0)) { return (_amount, 0); } fee = _amount.mul(_feePercent).div(100); return (_amount.sub(fee), fee); } function _sendAllBonesToUser(address _user, address _feeReceiver, uint8 _feePercent) internal { uint balance = boneToken.balanceOf(address(this)); _sendBonesToUser(_user, balance, _feeReceiver, _feePercent); } function _sendBonesToUser(address _user, uint _amount, address _feeReceiver, uint8 _feePercent) internal { (uint amountWithoutFee, uint fee) = _calcFee(_amount, _feeReceiver, _feePercent); if (fee > 0) { TransferHelper.safeTransfer(address(boneToken), _feeReceiver, fee); } TransferHelper.safeTransfer(address(boneToken), _user, amountWithoutFee); } function getClaimableRewardFromBoneLocker(IBoneLocker _boneLocker, address _feeReceiver, uint8 _feePercent) public view returns (uint) { if (address(_boneLocker) == address(0)) { _boneLocker = topDog.boneLocker(); } (uint amountWithoutFee, ) = _calcFee(_boneLocker.getClaimableAmount(address(this)), _feeReceiver, _feePercent); return amountWithoutFee; } function claimRewardFromBoneLocker(address _user, IBoneLocker _boneLocker, uint256 _maxBoneLockerRewardsAtOneClaim, address _feeReceiver, uint8 _feePercent) public onlyManager { if (address(_boneLocker) == address(0)) { _boneLocker = topDog.boneLocker(); } (uint256 left, uint256 right) = _boneLocker.getLeftRightCounters(address(this)); if (right <= left) { return; } if (_maxBoneLockerRewardsAtOneClaim > 0 && right - left > _maxBoneLockerRewardsAtOneClaim) { right = left + _maxBoneLockerRewardsAtOneClaim; } _boneLocker.claimAll(right); _sendAllBonesToUser(_user, _feeReceiver, _feePercent); } function emergencyWithdraw() public onlyManager { topDog.emergencyWithdraw(topDogPoolId); } function withdrawToken(address _token, address _user, uint _amount, address _feeReceiver, uint8 _feePercent) public onlyManager { if (_token == address(boneToken)) { _sendBonesToUser(_user, _amount, _feeReceiver, _feePercent); } else { TransferHelper.safeTransfer(_token, _user, _amount); } } function readBoneLocker(address _boneLocker, bytes calldata _callData) public view returns (bool success, bytes memory data) { (success, data) = _boneLocker.staticcall(_callData); } function callBoneLocker(address _boneLocker, bytes calldata _callData) public onlyManager returns (bool success, bytes memory data) { (success, data) = _boneLocker.call(_callData); } function getDepositedAmount() public view returns (uint amount) { (amount, ) = topDog.userInfo(topDogPoolId, address (this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @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 () { _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: GPL-3.0-or-later /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; // 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'); } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "./VaultParameters.sol"; /** * @title Auth2 * @dev Manages USDP's system access * @dev copy of Auth from VaultParameters.sol but with immutable vaultParameters for saving gas **/ contract Auth2 { // address of the the contract with vault parameters VaultParameters public immutable vaultParameters; constructor(address _parameters) { require(_parameters != address(0), "Unit Protocol: ZERO_ADDRESS"); 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"); _; } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVault { function DENOMINATOR_1E2 ( ) external view returns ( uint256 ); function DENOMINATOR_1E5 ( ) external view returns ( uint256 ); function borrow ( address asset, address user, uint256 amount ) external returns ( uint256 ); function calculateFee ( address asset, address user, uint256 amount ) external view returns ( uint256 ); function changeOracleType ( address asset, address user, uint256 newOracleType ) external; function chargeFee ( address asset, address user, uint256 amount ) external; function col ( ) external view returns ( address ); function colToken ( address, address ) external view returns ( uint256 ); function collaterals ( address, address ) external view returns ( uint256 ); function debts ( address, address ) external view returns ( uint256 ); function depositCol ( address asset, address user, uint256 amount ) external; function depositEth ( address user ) external payable; function depositMain ( address asset, address user, uint256 amount ) external; function destroy ( address asset, address user ) external; function getTotalDebt ( address asset, address user ) external view returns ( uint256 ); function lastUpdate ( address, address ) external view returns ( uint256 ); function liquidate ( address asset, address positionOwner, uint256 mainAssetToLiquidator, uint256 colToLiquidator, uint256 mainAssetToPositionOwner, uint256 colToPositionOwner, uint256 repayment, uint256 penalty, address liquidator ) external; function liquidationBlock ( address, address ) external view returns ( uint256 ); function liquidationFee ( address, address ) external view returns ( uint256 ); function liquidationPrice ( address, address ) external view returns ( uint256 ); function oracleType ( address, address ) external view returns ( uint256 ); function repay ( address asset, address user, uint256 amount ) external returns ( uint256 ); function spawn ( address asset, address user, uint256 _oracleType ) external; function stabilityFee ( address, address ) external view returns ( uint256 ); function tokenDebts ( address ) external view returns ( uint256 ); function triggerLiquidation ( address asset, address positionOwner, uint256 initialPrice ) external; function update ( address asset, address user ) external; function usdp ( ) external view returns ( address ); function vaultParameters ( ) external view returns ( address ); function weth ( ) external view returns ( address payable ); function withdrawCol ( address asset, address user, uint256 amount ) external; function withdrawEth ( address user, uint256 amount ) external; function withdrawMain ( address asset, address user, uint256 amount ) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20WithOptional is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWrappedAsset is IERC20 /* IERC20WithOptional */ { event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event PositionMoved(address indexed userFrom, address indexed userTo, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event TokenWithdraw(address indexed user, address token, uint256 amount); event FeeChanged(uint256 newFeePercent); event FeeReceiverChanged(address newFeeReceiver); event AllowedBoneLockerSelectorAdded(address boneLocker, bytes4 selector); event AllowedBoneLockerSelectorRemoved(address boneLocker, bytes4 selector); /** * @notice Get underlying token */ function getUnderlyingToken() external view returns (IERC20); /** * @notice deposit underlying token and send wrapped token to user * @dev Important! Only user or trusted contracts must be able to call this method */ function deposit(address _userAddr, uint256 _amount) external; /** * @notice get wrapped token and return underlying * @dev Important! Only user or trusted contracts must be able to call this method */ function withdraw(address _userAddr, uint256 _amount) external; /** * @notice get pending reward amount for user if reward is supported */ function pendingReward(address _userAddr) external view returns (uint256); /** * @notice claim pending reward for user if reward is supported */ function claimReward(address _userAddr) external; /** * @notice Manually move position (or its part) to another user (for example in case of liquidation) * @dev Important! Only trusted contracts must be able to call this method */ function movePosition(address _userAddrFrom, address _userAddrTo, uint256 _amount) external; /** * @dev function for checks that asset is unitprotocol wrapped asset. * @dev For wrapped assets must return keccak256("UnitProtocolWrappedAsset") */ function isUnitProtocolWrappedAsset() external view returns (bytes32); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IBoneLocker.sol"; import "./IBoneToken.sol"; /** * See https://etherscan.io/address/0x94235659cf8b805b2c658f9ea2d6d6ddbb17c8d7#code */ interface ITopDog { function bone() external view returns (IBoneToken); function boneLocker() external view returns (IBoneLocker); function poolInfo(uint256) external view returns (IERC20, uint256, uint256, uint256); function poolLength() external view returns (uint256); function userInfo(uint256, address) external view returns (uint256, uint256); function rewardMintPercent() external view returns (uint256); function pendingBone(uint256 _pid, address _user) external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ISushiSwapLpToken is IERC20 /* IERC20WithOptional */ { function token0() external view returns (address); function token1() external view returns (address); } // 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: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; /** * @dev BoneToken locker contract interface */ interface IBoneLocker { function lockInfoByUser(address, uint256) external view returns (uint256, uint256, bool); function lockingPeriod() external view returns (uint256); // function to claim all the tokens locked for a user, after the locking period function claimAllForUser(uint256 r, address user) external; // function to claim all the tokens locked by user, after the locking period function claimAll(uint256 r) external; // function to get claimable amount for any user function getClaimableAmount(address _user) external view returns(uint256); // get the left and right headers for a user, left header is the index counter till which we have already iterated, right header is basically the length of user's lockInfo array function getLeftRightCounters(address _user) external view returns(uint256, uint256); function lock(address _holder, uint256 _amount, bool _isDev) external; function setLockingPeriod(uint256 _newLockingPeriod, uint256 _newDevLockingPeriod) external; function emergencyWithdrawOwner(address _to) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IBoneToken is IERC20 { function mint(address _to, uint256 _amount) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; /** * @title Auth * @dev Manages USDP's system access **/ contract Auth { // address of the the contract with vault parameters VaultParameters public vaultParameters; constructor(address _parameters) { 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 **/ 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) 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; } }
Get tokens from user, send them to TopDog, sent to user wrapped tokens only user or CDPManager could call this method/ get tokens from user, need approve of sslp tokens to pool deposit them to TopDog wrapped tokens to user
function deposit(address _user, uint256 _amount) public override nonReentrant { require(_amount > 0, "Unit Protocol Wrapped Assets: INVALID_AMOUNT"); require(msg.sender == _user || vaultParameters.canModifyVault(msg.sender), "Unit Protocol Wrapped Assets: AUTH_FAILED"); IERC20 sslpToken = getUnderlyingToken(); WSSLPUserProxy userProxy = _getOrCreateUserProxy(_user, sslpToken); TransferHelper.safeTransferFrom(address(sslpToken), _user, address(userProxy), _amount); userProxy.deposit(_amount); _mint(_user, _amount); emit Deposit(_user, _amount); }
1,248,800
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/ownership/Ownable.sol"; import { IAutoTrader } from "../../protocol/interfaces/IAutoTrader.sol"; import { ICallee } from "../../protocol/interfaces/ICallee.sol"; import { Account } from "../../protocol/lib/Account.sol"; import { Decimal } from "../../protocol/lib/Decimal.sol"; import { Math } from "../../protocol/lib/Math.sol"; import { Monetary } from "../../protocol/lib/Monetary.sol"; import { Require } from "../../protocol/lib/Require.sol"; import { Time } from "../../protocol/lib/Time.sol"; import { Types } from "../../protocol/lib/Types.sol"; import { OnlyDolomiteMargin } from "../helpers/OnlyDolomiteMargin.sol"; import { IExpiry } from "../interfaces/IExpiry.sol"; /** * @title Expiry * @author dYdX * * Expiry contract that also allows approved senders to set expiry to be 28 days in the future. */ contract Expiry is Ownable, OnlyDolomiteMargin, IExpiry, ICallee, IAutoTrader { using Math for uint256; using SafeMath for uint32; using SafeMath for uint256; using Types for Types.Par; using Types for Types.Wei; // ============ Constants ============ bytes32 constant FILE = "Expiry"; // ============ Events ============ event ExpirySet( address owner, uint256 number, uint256 marketId, uint32 time ); event LogExpiryRampTimeSet( uint256 expiryRampTime ); event LogSenderApproved( address approver, address sender, uint32 minTimeDelta ); // ============ Storage ============ // owner => number => market => time mapping (address => mapping (uint256 => mapping (uint256 => uint32))) g_expiries; // owner => sender => minimum time delta mapping (address => mapping (address => uint32)) public g_approvedSender; // time over which the liquidation ratio goes from zero to maximum uint256 public g_expiryRampTime; // ============ Constructor ============ constructor ( address dolomiteMargin, uint256 expiryRampTime ) public OnlyDolomiteMargin(dolomiteMargin) { g_expiryRampTime = expiryRampTime; } // ============ Admin Functions ============ function ownerSetExpiryRampTime( uint256 newExpiryRampTime ) external onlyOwner { emit LogExpiryRampTimeSet(newExpiryRampTime); g_expiryRampTime = newExpiryRampTime; } // ============ Approval Functions ============ function approveSender( address sender, uint32 minTimeDelta ) external { setApproval(msg.sender, sender, minTimeDelta); } // ============ Only-DolomiteMargin Functions ============ function callFunction( address /* sender */, Account.Info memory account, bytes memory data ) public onlyDolomiteMargin(msg.sender) { CallFunctionType callType = abi.decode(data, (CallFunctionType)); if (callType == CallFunctionType.SetExpiry) { callFunctionSetExpiry(account.owner, data); } else { callFunctionSetApproval(account.owner, data); } } function getTradeCost( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory makerAccount, Account.Info memory /* takerAccount */, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, bytes memory data ) public onlyDolomiteMargin(msg.sender) returns (Types.AssetAmount memory) { // return zero if input amount is zero if (inputWei.isZero()) { return Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Par, ref: Types.AssetReference.Delta, value: 0 }); } (uint256 owedMarketId, uint32 maxExpiry) = abi.decode(data, (uint256, uint32)); uint32 expiry = getExpiry(makerAccount, owedMarketId); // validate expiry Require.that( expiry != 0, FILE, "Expiry not set", makerAccount.owner, makerAccount.number, owedMarketId ); Require.that( expiry <= Time.currentTime(), FILE, "Borrow not yet expired", expiry ); Require.that( expiry <= maxExpiry, FILE, "Expiry past maxExpiry", expiry ); return getTradeCostInternal( inputMarketId, outputMarketId, makerAccount, oldInputPar, newInputPar, inputWei, owedMarketId, expiry ); } // ============ Getters ============ function getExpiry( Account.Info memory account, uint256 marketId ) public view returns (uint32) { return g_expiries[account.owner][account.number][marketId]; } function getSpreadAdjustedPrices( uint256 heldMarketId, uint256 owedMarketId, uint32 expiry ) public view returns ( Monetary.Price memory, Monetary.Price memory ) { Decimal.D256 memory spread = DOLOMITE_MARGIN.getLiquidationSpreadForPair( heldMarketId, owedMarketId ); uint256 expiryAge = Time.currentTime().sub(expiry); if (expiryAge < g_expiryRampTime) { spread.value = Math.getPartial(spread.value, expiryAge, g_expiryRampTime); } Monetary.Price memory heldPrice = DOLOMITE_MARGIN.getMarketPrice(heldMarketId); Monetary.Price memory owedPrice = DOLOMITE_MARGIN.getMarketPrice(owedMarketId); owedPrice.value = owedPrice.value.add(Decimal.mul(owedPrice.value, spread)); return (heldPrice, owedPrice); } // ============ Private Functions ============ function callFunctionSetExpiry( address sender, bytes memory data ) private { ( CallFunctionType callType, SetExpiryArg[] memory expiries ) = abi.decode(data, (CallFunctionType, SetExpiryArg[])); assert(callType == CallFunctionType.SetExpiry); for (uint256 i = 0; i < expiries.length; i++) { SetExpiryArg memory exp = expiries[i]; if (exp.account.owner != sender) { // don't do anything if sender is not approved for this action uint32 minApprovedTimeDelta = g_approvedSender[exp.account.owner][sender]; if (minApprovedTimeDelta == 0 || exp.timeDelta < minApprovedTimeDelta) { continue; } } // if timeDelta is zero, interpret it as unset expiry if ( exp.timeDelta != 0 && DOLOMITE_MARGIN.getAccountPar(exp.account, exp.marketId).isNegative() ) { // only change non-zero values if forceUpdate is true if (exp.forceUpdate || getExpiry(exp.account, exp.marketId) == 0) { uint32 newExpiryTime = Time.currentTime().add(exp.timeDelta).to32(); setExpiry(exp.account, exp.marketId, newExpiryTime); } } else { // timeDelta is zero or account has non-negative balance setExpiry(exp.account, exp.marketId, 0); } } } function callFunctionSetApproval( address sender, bytes memory data ) private { ( CallFunctionType callType, SetApprovalArg memory approvalArg ) = abi.decode(data, (CallFunctionType, SetApprovalArg)); assert(callType == CallFunctionType.SetApproval); setApproval(sender, approvalArg.sender, approvalArg.minTimeDelta); } function getTradeCostInternal( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory makerAccount, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, uint256 owedMarketId, uint32 expiry ) private returns (Types.AssetAmount memory) { Types.AssetAmount memory output; Types.Wei memory maxOutputWei = DOLOMITE_MARGIN.getAccountWei(makerAccount, outputMarketId); if (inputWei.isPositive()) { Require.that( inputMarketId == owedMarketId, FILE, "inputMarket mismatch", inputMarketId ); Require.that( !newInputPar.isPositive(), FILE, "Borrows cannot be overpaid", newInputPar.value ); assert(oldInputPar.isNegative()); Require.that( maxOutputWei.isPositive(), FILE, "Collateral must be positive", outputMarketId, maxOutputWei.value ); output = owedWeiToHeldWei( inputWei, outputMarketId, inputMarketId, expiry ); // clear expiry if borrow is fully repaid if (newInputPar.isZero()) { setExpiry(makerAccount, owedMarketId, 0); } } else { Require.that( outputMarketId == owedMarketId, FILE, "outputMarket mismatch", outputMarketId ); Require.that( !newInputPar.isNegative(), FILE, "Collateral cannot be overused", newInputPar.value ); assert(oldInputPar.isPositive()); Require.that( maxOutputWei.isNegative(), FILE, "Borrows must be negative", outputMarketId, maxOutputWei.value ); output = heldWeiToOwedWei( inputWei, inputMarketId, outputMarketId, expiry ); // clear expiry if borrow is fully repaid if (output.value == maxOutputWei.value) { setExpiry(makerAccount, owedMarketId, 0); } } Require.that( output.value <= maxOutputWei.value, FILE, "outputMarket too small", output.value, maxOutputWei.value ); assert(output.sign != maxOutputWei.sign); return output; } function setExpiry( Account.Info memory account, uint256 marketId, uint32 time ) private { g_expiries[account.owner][account.number][marketId] = time; emit ExpirySet( account.owner, account.number, marketId, time ); } function setApproval( address approver, address sender, uint32 minTimeDelta ) private { g_approvedSender[approver][sender] = minTimeDelta; emit LogSenderApproved(approver, sender, minTimeDelta); } function heldWeiToOwedWei( Types.Wei memory heldWei, uint256 heldMarketId, uint256 owedMarketId, uint32 expiry ) private view returns (Types.AssetAmount memory) { ( Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) = getSpreadAdjustedPrices( heldMarketId, owedMarketId, expiry ); uint256 owedAmount = Math.getPartialRoundUp( heldWei.value, heldPrice.value, owedPrice.value ); return Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: owedAmount }); } function owedWeiToHeldWei( Types.Wei memory owedWei, uint256 heldMarketId, uint256 owedMarketId, uint32 expiry ) private view returns (Types.AssetAmount memory) { ( Monetary.Price memory heldPrice, Monetary.Price memory owedPrice ) = getSpreadAdjustedPrices( heldMarketId, owedMarketId, expiry ); uint256 heldAmount = Math.getPartial( owedWei.value, owedPrice.value, heldPrice.value ); return Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: heldAmount }); } }
return zero if input amount is zero
function getTradeCost( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory makerAccount, Account.Info memory /* takerAccount */, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, bytes memory data ) public onlyDolomiteMargin(msg.sender) returns (Types.AssetAmount memory) { if (inputWei.isZero()) { return Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Par, ref: Types.AssetReference.Delta, value: 0 }); } (uint256 owedMarketId, uint32 maxExpiry) = abi.decode(data, (uint256, uint32)); uint32 expiry = getExpiry(makerAccount, owedMarketId); expiry != 0, FILE, "Expiry not set", makerAccount.owner, makerAccount.number, owedMarketId ); Require.that( expiry <= Time.currentTime(), FILE, "Borrow not yet expired", expiry ); Require.that( expiry <= maxExpiry, FILE, "Expiry past maxExpiry", expiry ); return getTradeCostInternal( inputMarketId, outputMarketId, makerAccount, oldInputPar, newInputPar, inputWei, owedMarketId, expiry ); }
6,438,727
// SPDX-License-Identifier: WTFPL pragma solidity =0.6.12; pragma experimental ABIEncoderV2; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // Inheritance import "@openzeppelin/contracts/access/Ownable.sol"; import "../helpers/ERC20Staking.sol"; // Interfaces import "../interfaces/ERC1155/interfaces/IERC1155TokenReceiver.sol"; import "../interfaces/ILootCitadel.sol"; /** * @title Expansion ItemsCraft * @author TheLootMaster * @notice Stake LOOT to earn gold and craft items * @dev Manages staking of LOOT to earn rewards points for minting ERC1155 items */ contract ExpansionItemsCraft is ERC20Staking, Ownable { /***********************************| | Libraries | |__________________________________*/ using SafeMath for uint256; /***********************************| | Constants | |__________________________________*/ // Citadel ILootCitadel public citadel; // Points bool public priceLockup; uint256 public pointsPerDay; // Administation mapping(uint256 => bool) public exists; mapping(uint256 => uint256) public items; // User Rewards mapping(address => uint256) public points; mapping(address => uint256) public lastUpdateTime; /***********************************| | Events | |__________________________________*/ /** * @notice Staked * @dev Event fires when user stakes LOOT for earning points */ event Staked(address user, uint256 amount); /** * @notice Withdrawl * @dev Event fires when user withdrew LOOT from staking */ event Withdrawl(address user, uint256 amount); /** * @notice ItemAdded * @dev Event fires when a new item is added to crafing catalog */ event ItemAdded(uint256 item, uint256 cost); /** * @notice ItemUpdated * @dev Event fires when the cost of item crafting is updated */ event ItemUpdated(uint256 item, uint256 cost); /** * @notice ItemRemoved * @dev Event fires when the item can no longer be crafted */ event ItemRemoved(uint256 item); /** * @notice ItemCrafted * @dev Event fires when a user burns points for item crafting */ event ItemCrafted(uint256 item, address user); /***********************************| | Modifiers | |__________________________________*/ /** * @notice Update users reward balance * @dev Set the expansion confiration parameters * @param account Citadel target address */ modifier updateReward(address account) { if (account != address(0)) { points[account] = earned(account); lastUpdateTime[account] = block.timestamp; } _; } /***********************************| | Constructor | |__________________________________*/ /** * @notice Smart Contract Constructor * @dev Set the expansion confiration parameters * @param _citadel Citadel target address * @param _loot loot address * @param _pointsPerDay loot address */ constructor( address _citadel, address _loot, uint256 _pointsPerDay ) public ERC20Staking(_loot) { citadel = ILootCitadel(_citadel); pointsPerDay = _pointsPerDay; } /***********************************| | Points and Staking | |__________________________________*/ /** * @notice Calculates earned points * @dev Streams points to users every second by dividing pointsPerDay by 86400 * @param account Address of user * @return Points calculated at current block timestamp. */ function earned(address account) public view returns (uint256) { uint256 blockTime = block.timestamp; return points[account].add( blockTime .sub(lastUpdateTime[account]) .mul(pointsPerDay) .div(86400) .mul(balanceOf(account).div(1e18)) ); } /** * @notice Update pointsPerDay for each staked LOOT * @dev The points are streamed each second by dividing by 86400 * @param _pointsPerDay Points per day with 18 decimals * @return True */ function updatePointsPerDay(uint256 _pointsPerDay) external onlyOwner returns (bool) { // Set Points Allocation pointsPerDay = _pointsPerDay; return true; } /** * @notice Stake LOOT in Expansion ItemsCraft * @dev Stakes designated token using the ERC20Staking methods * @param amount Amount of LOOT to stake * @return Amount stake */ function stake(uint256 amount) external updateReward(msg.sender) returns (uint256) { // Enforce 100,000 LOOT Staked require( amount.add(balanceOf(msg.sender)) <= 100000 ether, "Staking Limited to 100,000 LOOT" ); // Stake LOOT _stake(amount); // Emit Staked emit Staked(msg.sender, amount); return amount; } /** * @notice Withdraw LOOT from ItemCraft. * @dev Withdraws designated token using the ERC20Staking methods * @param amount Amount of LOOT to withdraw * @return Amount withdrawn */ function withdraw(uint256 amount) external updateReward(msg.sender) returns (uint256) { // Check User Staked Balance require(amount <= balanceOf(msg.sender)); // Withdraw Staked LOOT _withdraw(amount); // Emit Withdrawl emit Withdrawl(msg.sender, amount); } /** * @notice Enables priceLockup * @dev Permanently prevents owner from updating the cost of item crafting. * @return Current priceLock boolean state */ function enablePriceLock() external onlyOwner returns (bool) { require(priceLockup == false); priceLockup = true; return priceLockup; } /****************************************| | Items | |_______________________________________*/ /** * @notice Add Item and Crafting Cost * @dev Adds a items availabled in an existing ERC1155 smart contact. * @param id Item ID * @param cost Points to redeem Item * @return True */ function addItem(uint256 id, uint256 cost) public onlyOwner returns (bool) { // Check if item exists or is being updated if (exists[id] == false) { // Set Item Cost items[id] = cost; // Set Creator exists[id] = true; // Emit ItemAdded emit ItemAdded(id, cost); } else { // Price Lockup is not activated require(!priceLockup, "Item Price Locked"); // Set Item Cost items[id] = cost; // Emit ItemUpdated emit ItemUpdated(id, cost); } return true; } /** * @notice Batch ddd Items and Crafting Costs * @dev Adds a items availabled in an existing ERC1155 smart contact. * @param ids Item IDs * @param costs Points to craft items * @return True */ function addItemBatch(uint256[] calldata ids, uint256[] calldata costs) external onlyOwner returns (bool) { // IDs and Cost Arrays length Match require(ids.length == costs.length); // Iterate Items and Crafting Cost for (uint256 index = 0; index < ids.length; index++) { addItem(ids[index], costs[index]); } return true; } /** * @notice Remove craftable item * @dev Prevents item from being crafted by setting crafting cost to zero * @param id Item ID * @return True */ function removeItem(uint256 id) external onlyOwner returns (bool) { // Item Cost Set to Zero items[id] = 0; // Emit ItemRemoved emit ItemRemoved(id); return true; } /** * @notice Crafts item using earned points * @dev Mints a new ERC1155 item by calling the Citadel with the MINTER role. * Updates the users earned points before executing the crafting process. * @param id Item ID * @return True */ function redeem(uint256 id) external updateReward(msg.sender) returns (bool) { // Check Item Is Available to Craft require(items[id] != 0, "Item Unavailable"); // Sufficient User Points require(points[msg.sender] >= items[id], "Insufficient Points"); // Update User Points points[msg.sender] = points[msg.sender].sub(items[id]); // Mint Item citadel.alchemy(msg.sender, id, 1); // Emit ItemCrafted emit ItemCrafted(id, msg.sender); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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, 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/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. */ 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; } } // SPDX-License-Identifier: WTFPL pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract ERC20Staking { using SafeMath for uint256; using SafeERC20 for IERC20; // Target token for staking IERC20 public ERC20; constructor(address _ERC20) public { ERC20 = IERC20(_ERC20); } uint256 private _totalSupply; mapping(address => uint256) private _balances; /** * @notice Total stake tokens * @dev The total of tokens staked for all accounts */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @notice Account staked amount * @dev Amount of tokens currently staked */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @notice Stake Token * @dev Stakes designated token * @param amount Amount of token to stake * @return true */ function _stake(uint256 amount) internal virtual returns (bool) { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); ERC20.transferFrom(msg.sender, address(this), amount); return true; } /** * @notice Withdraw Token * @dev Withdraw designated token * @param amount Amount of token to withdraw * @return true */ function _withdraw(uint256 amount) internal virtual returns (bool) { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); ERC20.transfer(msg.sender, amount); return true; } } // SPDX-License-Identifier: MIT pragma solidity =0.6.12; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received( address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data ) external returns (bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external returns (bytes4); } // SPDX-License-Identifier: WTFPL pragma solidity ^0.6.0; abstract contract ILootCitadel { /** * @dev Call alchemy for ERC20 token. * @param to Receiver of rewards * @param amount Amount of rewards */ function alchemy(address to, uint256 amount) external virtual; /** * @dev Call alchemy for ERC1155 token. * @param to Receiver of rewards * @param id Item ID * @param amount Amount of rewards */ function alchemy( address to, uint256 id, uint256 amount ) external virtual; /** * @dev Call alchemy for ERC721 token. * @param to Receiver of rewards * @param tokenId Token Identification Number */ function alchemy721(address to, uint256 tokenId) external virtual; /** * @dev Get current expansion balance * @param expansion Receiver of rewards */ function expansionBalance(address expansion) external virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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; /** * @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; 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.2; /** * @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); } } } }
Calculates earned points Streams points to users every second by dividing pointsPerDay by 86400 account Address of user return Points calculated at current block timestamp./
function earned(address account) public view returns (uint256) { uint256 blockTime = block.timestamp; return points[account].add( blockTime .sub(lastUpdateTime[account]) .mul(pointsPerDay) .div(86400) .mul(balanceOf(account).div(1e18)) ); }
14,870,823
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "../interfaces/IPermittedAirdrops.sol"; import "../utils/Ownable.sol"; /** * @title PermittedAirdrops * @author NFTfi * @dev Registry for airdropa supported by NFTfi. Each Airdrop is associated with a boolean permit. */ contract PermittedAirdrops is Ownable, IPermittedAirdrops { /* ******* */ /* STORAGE */ /* ******* */ /** * @notice A mapping from an airdrop to whether that airdrop * is permitted to be used by NFTfi. */ mapping(bytes => bool) private airdropPermits; /* ****** */ /* EVENTS */ /* ****** */ /** * @notice This event is fired whenever the admin sets a ERC20 permit. * * @param airdropContract - Address of the airdrop contract. * @param selector - The selector of the permitted function in the `airdropContract`. * @param isPermitted - Signals airdrop permit. */ event AirdropPermit(address indexed airdropContract, bytes4 indexed selector, bool isPermitted); /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @notice Initialize `airdropPermits` with a batch of permitted airdops * * @param _admin - Initial admin of this contract. * @param _airdopContracts - The batch of airdrop contract addresses initially permitted. * @param _selectors - The batch of selector of the permitted functions for each `_airdopContracts`. */ constructor( address _admin, address[] memory _airdopContracts, bytes4[] memory _selectors ) Ownable(_admin) { require(_airdopContracts.length == _selectors.length, "function information arity mismatch"); for (uint256 i = 0; i < _airdopContracts.length; i++) { _setAirdroptPermit(_airdopContracts[i], _selectors[i], true); } } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @notice This function can be called by admins to change the permitted status of an airdrop. This includes * both adding an airdrop to the permitted list and removing it. * * @param _airdropContract - The address of airdrop contract whose permit list status changed. * @param _selector - The selector of the permitted function whose permit list status changed. * @param _permit - The new status of whether the airdrop is permitted or not. */ function setAirdroptPermit( address _airdropContract, bytes4 _selector, bool _permit ) external onlyOwner { _setAirdroptPermit(_airdropContract, _selector, _permit); } /** * @notice This function can be called by admins to change the permitted status of a batch of airdrops. This * includes both adding an airdop to the permitted list and removing it. * * @param _airdropContracts - The addresses of the airdrop contracts whose permit list status changed. * @param _selectors - the selector of the permitted functions for each airdop whose permit list status changed. * @param _permits - The new statuses of whether the airdrop is permitted or not. */ function setAirdroptPermits( address[] memory _airdropContracts, bytes4[] memory _selectors, bool[] memory _permits ) external onlyOwner { require( _airdropContracts.length == _selectors.length, "setAirdroptPermits function information arity mismatch" ); require(_selectors.length == _permits.length, "setAirdroptPermits function information arity mismatch"); for (uint256 i = 0; i < _airdropContracts.length; i++) { _setAirdroptPermit(_airdropContracts[i], _selectors[i], _permits[i]); } } /** * @notice This function can be called by anyone to get the permit associated with the airdrop. * * @param _addressSel - The address of the airdrop contract + function selector. * * @return Returns whether the airdrop is permitted */ function isValidAirdrop(bytes memory _addressSel) external view override returns (bool) { return airdropPermits[_addressSel]; } /** * @notice This function can be called by admins to change the permitted status of an airdrop. This includes * both adding an airdrop to the permitted list and removing it. * * @param _airdropContract - The address of airdrop contract whose permit list status changed. * @param _selector - The selector of the permitted function whose permit list status changed. * @param _permit - The new status of whether the airdrop is permitted or not. */ function _setAirdroptPermit( address _airdropContract, bytes4 _selector, bool _permit ) internal { require(_airdropContract != address(0), "airdropContract is zero address"); require(_selector != bytes4(0), "selector is empty"); airdropPermits[abi.encode(_airdropContract, _selector)] = _permit; emit AirdropPermit(_airdropContract, _selector, _permit); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedAirdrops { function isValidAirdrop(bytes memory _addressSig) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/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. * * Modified version from openzeppelin/contracts/access/Ownable.sol that allows to * initialize the owner using a parameter in the constructor */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address _initialOwner) { _setOwner(_initialOwner); } /** * @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); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Sets the owner. */ function _setOwner(address _newOwner) private { address oldOwner = _owner; _owner = _newOwner; emit OwnershipTransferred(oldOwner, _newOwner); } } // 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; } }
This function can be called by admins to change the permitted status of an airdrop. This includes both adding an airdrop to the permitted list and removing it. _airdropContract - The address of airdrop contract whose permit list status changed. _selector - The selector of the permitted function whose permit list status changed. _permit - The new status of whether the airdrop is permitted or not./
function _setAirdroptPermit( address _airdropContract, bytes4 _selector, bool _permit ) internal { require(_airdropContract != address(0), "airdropContract is zero address"); require(_selector != bytes4(0), "selector is empty"); airdropPermits[abi.encode(_airdropContract, _selector)] = _permit; emit AirdropPermit(_airdropContract, _selector, _permit); }
427,271
./full_match/80001/0x38D7c5D106c93831351fc4c6C9686b5FE8dd28C3/sources/src/lib/PureHelpers.sol
Returns number of unique recipients. sortedAccounts _must_ be sorted for this to work properly
function _countUniqueRecipients(address[] memory sortedAccounts) internal pure returns (uint32) { uint32 numRecipients = uint32(sortedAccounts.length); uint32 numUniqRecipients = 1; address lastRecipient = sortedAccounts[0]; for (uint256 i = 1; i < numRecipients;) { if (sortedAccounts[i] != lastRecipient) { unchecked { ++numUniqRecipients; lastRecipient = sortedAccounts[i]; } } unchecked { ++i; } } return numUniqRecipients; }
5,632,471
/** *Submitted for verification at Etherscan.io on 2022-04-01 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // 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; } } // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // 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; } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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/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/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) 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); /** * @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/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: https://github.com/chiru-labs/ERC721A/blob/main/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error UnableDetermineTokenOwner(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal _currentIndex; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; 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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); unchecked { for (uint256 curr = tokenId;; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert UnableDetermineTokenOwner(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 URIQueryForNonexistentToken(); 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 override { address owner = ERC721A.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 override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); 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 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @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, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // 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; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) revert TransferToNonERC721ReceiverImplementer(); else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: TheMetaWarriors.sol pragma solidity >=0.8.0 <0.9.0; contract TheMetaWarriors is ERC721A, Ownable, ReentrancyGuard { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string private uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public publicSaleCost = 0.1 ether; uint256 public presaleCost = 0.08 ether; uint256 public maxSupply = 10000; uint256 public maxMintAmountPerTx = 5; uint256 public maxPublicWalletLimit = 8; uint256 public maxPresaleWalletLimit = 5; bool public paused = true; bool public revealed = false; bool public presaleActive = false; bool public saleActive = false; bytes32 private merkleRoot = ""; constructor() ERC721A("The Meta Warriors", "TMW") { setHiddenMetadataUri("https://ipfs.io/ipfs/QmW5qf3MtG7qQwMKtpKUHHrBBbf68gJp22nxY2s1yXNYrW/hidden.json"); } function totalSupply() public view returns (uint256) { return supply.current(); } function cost() public view returns(uint256) { if(presaleActive) return presaleCost; return publicSaleCost; } function maxWalletLimit() public view returns(uint256) { if(presaleActive) return maxPresaleWalletLimit; return maxPublicWalletLimit; } modifier mintCompliance(uint256 _mintAmount) { require(!paused, "The contract is paused!"); require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(totalSupply() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } modifier selfMintCompliance(uint256 _mintAmount) { require(_mintAmount > 0, "Invalid mint amount!"); require(totalSupply() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(saleActive, "Sale is not Active" ); require(msg.value >= cost() * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender) + _mintAmount <= maxWalletLimit(), "Max mint amount per wallet reached"); _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } function mintForSelf(uint256 _mintAmount) public selfMintCompliance(_mintAmount) onlyOwner { _mintLoop(msg.sender, _mintAmount); } function whitelistMint(uint _mintAmount, bytes32 leaf, bytes32[] memory proof) external payable mintCompliance(_mintAmount) { require(presaleActive, "Sale is not Active" ); // Verify that (msg.sender, amount) correspond to Merkle leaf require(keccak256(abi.encodePacked(msg.sender)) == leaf, "Sender and amount don't match Merkle leaf"); // Verify that (leaf, proof) matches the Merkle root require(verify(merkleRoot, leaf, proof), "Not a valid leaf in the Merkle tree"); require(msg.value >= cost() * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender) + _mintAmount <= maxWalletLimit(), "Max mint amount per wallet reached"); _mintLoop(msg.sender, _mintAmount); } function verify(bytes32 _merkleRoot, bytes32 leaf, bytes32[] memory proof) public pure returns (bool) { return MerkleProof.verify(proof, _merkleRoot, leaf); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } function setPresaleCost(uint256 _cost) public onlyOwner { presaleCost = _cost; } function setPublicSaleCost(uint256 _cost) public onlyOwner { publicSaleCost = _cost; } function setPublicSale(bool _sale) public onlyOwner { saleActive = _sale; } function setPreSale(bool _sale) public onlyOwner { presaleActive = _sale; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setPublicMaxWalletLimit(uint256 _maxWalletLimit) public onlyOwner { maxPublicWalletLimit = _maxWalletLimit; } function setPresaleMaxWalletLimit(uint256 _maxWalletLimit) public onlyOwner { maxPresaleWalletLimit = _maxWalletLimit; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function withdraw() public onlyOwner { require(address(this).balance > 0, "Balance is 0"); payable(owner()).transfer(address(this).balance); } function _mintLoop(address _receiver, uint256 _mintAmount) internal { _safeMint(_receiver, _mintAmount); for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
Gas spent here starts off proportional to the maximum mint batch size. It gradually moves to O(1) as tokens get transferred around in the collection over time./
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); unchecked { for (uint256 curr = tokenId;; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert UnableDetermineTokenOwner(); }
7,694,666
./full_match/1/0x2ccE22c7A4A9f66ee589464D883e85D91F35DD6b/sources/Sorbettiere.sol
Withdraw staked tokens from Sorbettiere.
function withdraw(uint256 _pid, uint128 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "Sorbettiere: you cant eat that much popsicles"); updatePool(_pid); uint128 pending = user.amount * pool.accIcePerShare / 1e12 - user.rewardDebt + user.remainingIceTokenReward; user.remainingIceTokenReward = safeRewardTransfer(msg.sender, pending); user.amount -= _amount; pool.stakingTokenTotalAmount -= _amount; user.rewardDebt = user.amount * pool.accIcePerShare / 1e12; pool.stakingToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
3,088,662
pragma solidity 0.5.7; contract ERC20 { function symbol() public returns(string memory); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); } contract MultiAccess { event AllowAccessEvent(address indexed _address); event DenyAccessEvent(address indexed _address); mapping(address => bool) accessAllowed; constructor () public { accessAllowed[msg.sender] = true; emit AllowAccessEvent(msg.sender); } modifier canAccess() { require(accessAllowed[msg.sender]); _; } function isAllowedAccess() view internal { require(accessAllowed[msg.sender]); } function allowAccess(address _address) canAccess public { accessAllowed[_address] = true; emit AllowAccessEvent(_address); } function denyAccess(address _address) canAccess public { accessAllowed[_address] = false; emit DenyAccessEvent(_address); } } contract BizancioGateway is MultiAccess { event logDeposit (address from, string destination, uint amount, string asset, address assetId); event logWithdrawal (string withdrawHash, address to, address origin, uint amount, string asset, address assetId); // call to deposit ETH // destination: public address in Bizanc.io // msg value will be deposited to destination function depositEth (string memory destination) public payable { emit logDeposit (msg.sender, destination, msg.value, "ETH", address(0x0)); } // call to deposit tokens // destination: public address in Bizanc.io // token: token address // the whole allowance to this contract will be deposited to destination function depositERC20 (string memory destination, address token) public { ERC20 tokenContract = ERC20(token); uint value = tokenContract.allowance(msg.sender, address(this)); require(tokenContract.transferFrom(msg.sender, address(this), value)); emit logDeposit (msg.sender, destination, value, tokenContract.symbol(), token); } // call to send ETH or tokens to users // only owner can call the function // to: Ethereum address to receive funds // origin: public address in Bizanc.io // value: value in wei function withdrawEth (string memory withdrawHash, address payable to, address origin, uint value) public canAccess { if(address(to).send(value)) emit logWithdrawal (withdrawHash, to, origin, value, "ETH", address(0x0)); } // call to send tokens to users // only owner can call the function // to: Ethereum address to receive funds // origin: public address in Bizanc.io // value: value in wei // token: token address function withdrawERC20 (string memory withdrawHash, address to, address origin, uint value, address token ) public canAccess { ERC20 tokenContract = ERC20(token); tokenContract.transfer(to, value); emit logWithdrawal (withdrawHash, to, origin, value, tokenContract.symbol(), token); } }
call to send ETH or tokens to users only owner can call the function to: Ethereum address to receive funds origin: public address in Bizanc.io value: value in wei
function withdrawEth (string memory withdrawHash, address payable to, address origin, uint value) public canAccess { if(address(to).send(value)) emit logWithdrawal (withdrawHash, to, origin, value, "ETH", address(0x0)); }
1,055,600
/** * Dragonking is a blockchain game in which players may purchase dragons and knights of different levels and values. * Once every period of time the volcano erupts and wipes a few of them from the board. The value of the killed characters * gets distributed amongst all of the survivors. The dragon king receive a bigger share than the others. * In contrast to dragons, knights need to be teleported to the battlefield first with the use of teleport tokens. * Additionally, they may attack a dragon once per period. * Both character types can be protected from death up to three times. * Take a look at dragonking.io for more detailed information. * @author: Julia Altenried, Yuriy Kashnikov * */ pragma solidity ^0.4.24; // DragonKing v2.0 2e59d4 // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @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; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; 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); } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @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 Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract DragonKingConfig is Ownable { /** the Gift token contract **/ ERC20 public giftToken; /** amount of gift tokens to send **/ uint256 public giftTokenAmount; /** the cost of each character type */ uint128[] public costs; /** the value of each character type (cost - fee), so it&#39;s not necessary to compute it each time*/ uint128[] public values; /** the fee to be paid each time an character is bought in percent*/ uint8 fee; /** The maximum of characters allowed in the game */ uint16 public maxCharacters; /** the amount of time that should pass since last eruption **/ uint256 public eruptionThreshold; /** the amount of time that should pass ince last castle loot distribution **/ uint256 public castleLootDistributionThreshold; /** how many characters to kill in %, e.g. 20 will stand for 20%, should be < 100 **/ uint8 public percentageToKill; /* Cooldown threshold */ uint256 public constant CooldownThreshold = 1 days; /** fight factor, used to compute extra probability in fight **/ uint8 public fightFactor; /** the price for teleportation*/ uint256 public teleportPrice; /** the price for protection */ uint256 public protectionPrice; /** the luck threshold */ uint256 public luckThreshold; function hasEnoughTokensToPurchase(address buyer, uint8 characterType) external returns (bool canBuy); } contract DragonKing is Destructible { /** * @dev Throws if called by contract not a user */ modifier onlyUser() { require(msg.sender == tx.origin, "contracts cannot execute this method" ); _; } struct Character { uint8 characterType; uint128 value; address owner; uint64 purchaseTimestamp; uint8 fightCount; } DragonKingConfig public config; /** the neverdie token contract used to purchase protection from eruptions and fights */ ERC20 neverdieToken; /** the teleport token contract used to send knights to the game scene */ ERC20 teleportToken; /** the luck token contract **/ ERC20 luckToken; /** the SKL token contract **/ ERC20 sklToken; /** the XP token contract **/ ERC20 xperToken; /** array holding ids of the curret characters **/ uint32[] public ids; /** the id to be given to the next character **/ uint32 public nextId; /** non-existant character **/ uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0); /** the castle treasury **/ uint128 public castleTreasury; /** the id of the oldest character **/ uint32 public oldest; /** the character belonging to a given id **/ mapping(uint32 => Character) characters; /** teleported knights **/ mapping(uint32 => bool) teleported; /** constant used to signal that there is no King at the moment **/ uint32 constant public noKing = ~uint32(0); /** total number of characters in the game **/ uint16 public numCharacters; /** number of characters per type **/ mapping(uint8 => uint16) public numCharactersXType; /** timestamp of the last eruption event **/ uint256 public lastEruptionTimestamp; /** timestamp of the last castle loot distribution **/ uint256 public lastCastleLootDistributionTimestamp; /** character type range constants **/ uint8 public constant DRAGON_MIN_TYPE = 0; uint8 public constant DRAGON_MAX_TYPE = 5; uint8 public constant KNIGHT_MIN_TYPE = 6; uint8 public constant KNIGHT_MAX_TYPE = 11; uint8 public constant BALLOON_MIN_TYPE = 12; uint8 public constant BALLOON_MAX_TYPE = 14; uint8 public constant WIZARD_MIN_TYPE = 15; uint8 public constant WIZARD_MAX_TYPE = 20; uint8 public constant ARCHER_MIN_TYPE = 21; uint8 public constant ARCHER_MAX_TYPE = 26; uint8 public constant NUMBER_OF_LEVELS = 6; uint8 public constant INVALID_CHARACTER_TYPE = 27; /** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */ mapping(uint32 => uint) public cooldown; /** tells the number of times a character is protected */ mapping(uint32 => uint8) public protection; // EVENTS /** is fired when new characters are purchased (who bought how many characters of which type?) */ event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId); /** is fired when a player leaves the game */ event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters); /** is fired when an eruption occurs */ event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost); /** is fired when a single character is sold **/ event NewSell(uint32 characterId, address player, uint256 value); /** is fired when a knight fights a dragon **/ event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice); /** is fired when a knight is teleported to the field **/ event NewTeleport(uint32 characterId); /** is fired when a protection is purchased **/ event NewProtection(uint32 characterId, uint8 lifes); /** is fired when a castle loot distribution occurs**/ event NewDistributionCastleLoot(uint128 castleLoot); /* initializes the contract parameter */ constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public { nextId = 1; teleportToken = ERC20(tptAddress); neverdieToken = ERC20(ndcAddress); sklToken = ERC20(sklAddress); xperToken = ERC20(xperAddress); luckToken = ERC20(luckAddress); config = DragonKingConfig(_configAddress); } /** * gifts one character * @param receiver gift character owner * @param characterType type of the character to create as a gift */ function giftCharacter(address receiver, uint8 characterType) payable public onlyUser { _addCharacters(receiver, characterType); assert(config.giftToken().transfer(receiver, config.giftTokenAmount())); } /** * buys as many characters as possible with the transfered value of the given type * @param characterType the type of the character */ function addCharacters(uint8 characterType) payable public onlyUser { _addCharacters(msg.sender, characterType); } function _addCharacters(address receiver, uint8 characterType) internal { uint16 amount = uint16(msg.value / config.costs(characterType)); require( amount > 0, "insufficient amount of ether to purchase a given type of character"); uint16 nchars = numCharacters; require( config.hasEnoughTokensToPurchase(receiver, characterType), "insufficinet amount of tokens to purchase a given type of character" ); if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert(); uint32 nid = nextId; //if type exists, enough ether was transferred and there are less than maxCharacters characters in the game if (characterType <= DRAGON_MAX_TYPE) { //dragons enter the game directly if (oldest == 0 || oldest == noKing) oldest = nid; for (uint8 i = 0; i < amount; i++) { addCharacter(nid + i, nchars + i); characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0); } numCharactersXType[characterType] += amount; numCharacters += amount; } else { // to enter game knights, mages, and archers should be teleported later for (uint8 j = 0; j < amount; j++) { characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0); } } nextId = nid + amount; emit NewPurchase(receiver, characterType, amount, nid); } /** * adds a single dragon of the given type to the ids array, which is used to iterate over all characters * @param nId the id the character is about to receive * @param nchars the number of characters currently in the game */ function addCharacter(uint32 nId, uint16 nchars) internal { if (nchars < ids.length) ids[nchars] = nId; else ids.push(nId); } /** * leave the game. * pays out the sender&#39;s balance and removes him and his characters from the game * */ function exit() public { uint32[] memory removed = new uint32[](50); uint8 count; uint32 lastId; uint playerBalance; uint16 nchars = numCharacters; for (uint16 i = 0; i < nchars; i++) { if (characters[ids[i]].owner == msg.sender && characters[ids[i]].purchaseTimestamp + 1 days < now && (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) { //first delete all characters at the end of the array while (nchars > 0 && characters[ids[nchars - 1]].owner == msg.sender && characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now && (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) { nchars--; lastId = ids[nchars]; numCharactersXType[characters[lastId].characterType]--; playerBalance += characters[lastId].value; removed[count] = lastId; count++; if (lastId == oldest) oldest = 0; delete characters[lastId]; } //replace the players character by the last one if (nchars > i + 1) { playerBalance += characters[ids[i]].value; removed[count] = ids[i]; count++; nchars--; replaceCharacter(i, nchars); } } } numCharacters = nchars; emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client msg.sender.transfer(playerBalance); if (oldest == 0) findOldest(); } /** * Replaces the character with the given id with the last character in the array * @param index the index of the character in the id array * @param nchars the number of characters * */ function replaceCharacter(uint16 index, uint16 nchars) internal { uint32 characterId = ids[index]; numCharactersXType[characters[characterId].characterType]--; if (characterId == oldest) oldest = 0; delete characters[characterId]; ids[index] = ids[nchars]; delete ids[nchars]; } /** * The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription. * The volcano hits up to a certain percentage of characters, but at least one. * The percantage is specified in &#39;percentageToKill&#39; * */ function triggerVolcanoEruption() public onlyUser { require(now >= lastEruptionTimestamp + config.eruptionThreshold(), "not enough time passed since last eruption"); require(numCharacters > 0, "there are no characters in the game"); lastEruptionTimestamp = now; uint128 pot; uint128 value; uint16 random; uint32 nextHitId; uint16 nchars = numCharacters; uint32 howmany = nchars * config.percentageToKill() / 100; uint128 neededGas = 80000 + 10000 * uint32(nchars); if(howmany == 0) howmany = 1;//hit at least 1 uint32[] memory hitCharacters = new uint32[](howmany); bool[] memory alreadyHit = new bool[](nextId); uint16 i = 0; uint16 j = 0; while (i < howmany) { j++; random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars); nextHitId = ids[random]; if (!alreadyHit[nextHitId]) { alreadyHit[nextHitId] = true; hitCharacters[i] = nextHitId; value = hitCharacter(random, nchars, 0); if (value > 0) { nchars--; } pot += value; i++; } } uint128 gasCost = uint128(neededGas * tx.gasprice); numCharacters = nchars; if (pot > gasCost){ distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs emit NewEruption(hitCharacters, pot - gasCost, gasCost); } else emit NewEruption(hitCharacters, 0, gasCost); } /** * Knight can attack a dragon. * Archer can attack only a balloon. * Dragon can attack wizards and archers. * Wizard can attack anyone, except balloon. * Balloon cannot attack. * The value of the loser is transfered to the winner. * @param characterID the ID of the knight to perfrom the attack * @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs. * In case it&#39;s unknown or incorrect, the index is looked up in the array. * */ function fight(uint32 characterID, uint16 characterIndex) public onlyUser { if (characterID != ids[characterIndex]) characterIndex = getCharacterIndex(characterID); Character storage character = characters[characterID]; require(cooldown[characterID] + config.CooldownThreshold() <= now, "not enough time passed since the last fight of this character"); require(character.owner == msg.sender, "only owner can initiate a fight for this character"); uint8 ctype = character.characterType; require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE, "balloons cannot fight"); uint16 adversaryIndex = getRandomAdversary(characterID, ctype); assert(adversaryIndex != INVALID_CHARACTER_INDEX); uint32 adversaryID = ids[adversaryIndex]; Character storage adversary = characters[adversaryID]; uint128 value; uint16 base_probability; uint16 dice = uint16(generateRandomNumber(characterID) % 100); if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) { base_probability = uint16(generateRandomNumber(dice) % 100); if (base_probability < dice) { dice = base_probability; } base_probability = 0; } uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner); uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner); if (character.value == adversary.value) { base_probability = 50; if (characterPower > adversaryPower) { base_probability += uint16(100 / config.fightFactor()); } else if (adversaryPower > characterPower) { base_probability -= uint16(100 / config.fightFactor()); } } else if (character.value > adversary.value) { base_probability = 100; if (adversaryPower > characterPower) { base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor()); } } else if (characterPower > adversaryPower) { base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor()); } if (dice >= base_probability) { // adversary won if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) { value = hitCharacter(characterIndex, numCharacters, adversary.characterType); if (value > 0) { numCharacters--; } else { cooldown[characterID] = now; if (characters[characterID].fightCount < 3) { characters[characterID].fightCount++; } } if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) { castleTreasury += value; } else { adversary.value += value; } emit NewFight(adversaryID, characterID, value, base_probability, dice); } else { emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back } } else { // character won cooldown[characterID] = now; if (characters[characterID].fightCount < 3) { characters[characterID].fightCount++; } value = hitCharacter(adversaryIndex, numCharacters, character.characterType); if (value > 0) { numCharacters--; } if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) { castleTreasury += value; } else { character.value += value; } if (oldest == 0) findOldest(); emit NewFight(characterID, adversaryID, value, base_probability, dice); } } /* * @param characterType * @param adversaryType * @return whether adversaryType is a valid type of adversary for a given character */ function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) { if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight return (adversaryType <= DRAGON_MAX_TYPE); } else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE); } else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon return (adversaryType >= WIZARD_MIN_TYPE); } else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE) || (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE)); } return false; } /** * pick a random adversary. * @param nonce a nonce to make sure there&#39;s not always the same adversary chosen in a single block. * @return the index of a random adversary character * */ function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) { uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters); // use 7, 11 or 13 as step size. scales for up to 1000 characters uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7; uint16 i = randomIndex; //if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number) //will at some point return to the startingPoint if no character is suited do { if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) { return i; } i = (i + stepSize) % numCharacters; } while (i != randomIndex); return INVALID_CHARACTER_INDEX; } /** * generate a random number. * @param nonce a nonce to make sure there&#39;s not always the same number returned in a single block. * @return the random number * */ function generateRandomNumber(uint256 nonce) internal view returns(uint) { return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce)); } /** * Hits the character of the given type at the given index. * Wizards can knock off two protections. Other characters can do only one. * @param index the index of the character * @param nchars the number of characters * @return the value gained from hitting the characters (zero is the character was protected) * */ function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) { uint32 id = ids[index]; uint8 knockOffProtections = 1; if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { knockOffProtections = 2; } if (protection[id] >= knockOffProtections) { protection[id] = protection[id] - knockOffProtections; return 0; } characterValue = characters[ids[index]].value; nchars--; replaceCharacter(index, nchars); } /** * finds the oldest character * */ function findOldest() public { uint32 newOldest = noKing; for (uint16 i = 0; i < numCharacters; i++) { if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE) newOldest = ids[i]; } oldest = newOldest; } /** * distributes the given amount among the surviving characters * @param totalAmount nthe amount to distribute */ function distribute(uint128 totalAmount) internal { uint128 amount; if (oldest == 0) findOldest(); if (oldest != noKing) { //pay 10% to the oldest dragon characters[oldest].value += totalAmount / 10; amount = totalAmount / 10 * 9; } else { amount = totalAmount; } //distribute the rest according to their type uint128 valueSum; uint8 size = ARCHER_MAX_TYPE + 1; uint128[] memory shares = new uint128[](size); for (uint8 v = 0; v < size; v++) { if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) { valueSum += config.values(v); } } for (uint8 m = 0; m < size; m++) { if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) { shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m]; } } uint8 cType; for (uint16 i = 0; i < numCharacters; i++) { cType = characters[ids[i]].characterType; if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE) characters[ids[i]].value += shares[characters[ids[i]].characterType]; } } /** * allows the owner to collect the accumulated fees * sends the given amount to the owner&#39;s address if the amount does not exceed the * fees (cannot touch the players&#39; balances) minus 100 finney (ensure that oraclize fees can be paid) * @param amount the amount to be collected * */ function collectFees(uint128 amount) public onlyOwner { uint collectedFees = getFees(); if (amount + 100 finney < collectedFees) { owner.transfer(amount); } } /** * withdraw NDC and TPT tokens */ function withdraw() public onlyOwner { uint256 ndcBalance = neverdieToken.balanceOf(this); assert(neverdieToken.transfer(owner, ndcBalance)); uint256 tptBalance = teleportToken.balanceOf(this); assert(teleportToken.transfer(owner, tptBalance)); } /** * pays out the players. * */ function payOut() public onlyOwner { for (uint16 i = 0; i < numCharacters; i++) { characters[ids[i]].owner.transfer(characters[ids[i]].value); delete characters[ids[i]]; } delete ids; numCharacters = 0; } /** * pays out the players and kills the game. * */ function stop() public onlyOwner { withdraw(); payOut(); destroy(); } function generateLuckFactor(uint128 nonce) internal view returns(uint128) { uint128 sum = 0; uint128 inc = 1; for (uint128 i = 49; i >= 5; i--) { if (sum > nonce) { return i+2; } sum += inc; if (i != 40 && i != 8) { inc += 1; } } return 5; } /* @dev distributes castle loot among archers */ function distributeCastleLoot() external onlyUser { require(now >= lastCastleLootDistributionTimestamp + config.castleLootDistributionThreshold(), "not enough time passed since the last castle loot distribution"); lastCastleLootDistributionTimestamp = now; uint128 luckFactor = generateLuckFactor(uint128(now % 1000)); if (luckFactor < 5) { luckFactor = 5; } uint128 amount = castleTreasury * luckFactor / 100; uint128 valueSum; uint128[] memory shares = new uint128[](NUMBER_OF_LEVELS); uint16 archersCount; uint32[] memory archers = new uint32[](numCharacters); uint8 cType; for (uint8 i = 0; i < ids.length; i++) { cType = characters[ids[i]].characterType; if ((cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) && (characters[ids[i]].fightCount >= 3) && (now - characters[ids[i]].purchaseTimestamp >= 7 days)) { valueSum += config.values(cType); archers[archersCount] = ids[i]; archersCount++; } } if (valueSum > 0) { for (uint8 j = 0; j < NUMBER_OF_LEVELS; j++) { shares[j] = amount * config.values(ARCHER_MIN_TYPE + j) / valueSum; } for (uint16 k = 0; k < archersCount; k++) { characters[archers[k]].value += shares[characters[archers[k]].characterType - ARCHER_MIN_TYPE]; } castleTreasury -= amount; emit NewDistributionCastleLoot(amount); } else { emit NewDistributionCastleLoot(0); } } /** * sell the character of the given id * throws an exception in case of a knight not yet teleported to the game * @param characterId the id of the character * */ function sellCharacter(uint32 characterId) public onlyUser { require(msg.sender == characters[characterId].owner, "only owners can sell their characters"); require(characters[characterId].characterType < BALLOON_MIN_TYPE || characters[characterId].characterType > BALLOON_MAX_TYPE, "balloons are not sellable"); require(characters[characterId].purchaseTimestamp + 1 days < now, "character can be sold only 1 day after the purchase"); uint128 val = characters[characterId].value; numCharacters--; replaceCharacter(getCharacterIndex(characterId), numCharacters); msg.sender.transfer(val); if (oldest == 0) findOldest(); emit NewSell(characterId, msg.sender, val); } /** * receive approval to spend some tokens. * used for teleport and protection. * @param sender the sender address * @param value the transferred value * @param tokenContract the address of the token contract * @param callData the data passed by the token contract * */ function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public { uint32 id; uint256 price; if (msg.sender == address(teleportToken)) { id = toUint32(callData); price = config.teleportPrice(); if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) { price *= 2; } require(value >= price, "insufficinet amount of tokens to teleport this character"); assert(teleportToken.transferFrom(sender, this, price)); teleportCharacter(id); } else if (msg.sender == address(neverdieToken)) { id = toUint32(callData); // user can purchase extra lifes only right after character purchaes // in other words, user value should be equal the initial value uint8 cType = characters[id].characterType; require(characters[id].value == config.values(cType), "protection could be bought only before the first fight and before the first volcano eruption"); // calc how many lifes user can actually buy // the formula is the following: uint256 lifePrice; uint8 max; if(cType <= KNIGHT_MAX_TYPE ){ lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice(); max = 3; } else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) { lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2; max = 6; } else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) { lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2; max = 3; } else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) { lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice(); max = 3; } price = 0; uint8 i = protection[id]; for (i; i < max && value >= price + lifePrice * (i + 1); i++) { price += lifePrice * (i + 1); } assert(neverdieToken.transferFrom(sender, this, price)); protectCharacter(id, i); } else { revert("Should be either from Neverdie or Teleport tokens"); } } /** * Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene * @param id the character id * */ function teleportCharacter(uint32 id) internal { // ensure we do not teleport twice require(teleported[id] == false, "already teleported"); teleported[id] = true; Character storage character = characters[id]; require(character.characterType > DRAGON_MAX_TYPE, "dragons do not need to be teleported"); //this also makes calls with non-existent ids fail addCharacter(id, numCharacters); numCharacters++; numCharactersXType[character.characterType]++; emit NewTeleport(id); } /** * adds protection to a character * @param id the character id * @param lifes the number of protections * */ function protectCharacter(uint32 id, uint8 lifes) internal { protection[id] = lifes; emit NewProtection(id, lifes); } /****************** GETTERS *************************/ /** * returns the character of the given id * @param characterId the character id * @return the type, value and owner of the character * */ function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) { return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner); } /** * returns the index of a character of the given id * @param characterId the character id * @return the character id * */ function getCharacterIndex(uint32 characterId) constant public returns(uint16) { for (uint16 i = 0; i < ids.length; i++) { if (ids[i] == characterId) { return i; } } revert(); } /** * returns 10 characters starting from a certain indey * @param startIndex the index to start from * @return 4 arrays containing the ids, types, values and owners of the characters * */ function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) { uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10; uint8 j = 0; uint32 id; for (uint16 i = startIndex; i < endIndex; i++) { id = ids[i]; characterIds[j] = id; types[j] = characters[id].characterType; values[j] = characters[id].value; owners[j] = characters[id].owner; j++; } } /** * returns the number of dragons in the game * @return the number of dragons * */ function getNumDragons() constant public returns(uint16 numDragons) { for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++) numDragons += numCharactersXType[i]; } /** * returns the number of wizards in the game * @return the number of wizards * */ function getNumWizards() constant public returns(uint16 numWizards) { for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++) numWizards += numCharactersXType[i]; } /** * returns the number of archers in the game * @return the number of archers * */ function getNumArchers() constant public returns(uint16 numArchers) { for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++) numArchers += numCharactersXType[i]; } /** * returns the number of knights in the game * @return the number of knights * */ function getNumKnights() constant public returns(uint16 numKnights) { for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++) numKnights += numCharactersXType[i]; } /** * @return the accumulated fees * */ function getFees() constant public returns(uint) { uint reserved = 0; for (uint16 j = 0; j < numCharacters; j++) reserved += characters[ids[j]].value; return address(this).balance - reserved; } /************* SETTERS ****************/ /** * sets DragonKingConfig * */ function setConfig(address _value) public onlyOwner { config = DragonKingConfig(_value); } /************* HELPERS ****************/ /** * only works for bytes of length < 32 * @param b the byte input * @return the uint * */ function toUint32(bytes b) internal pure returns(uint32) { bytes32 newB; assembly { newB: = mload(0xa0) } return uint32(newB); } }
Knight can attack a dragon. Archer can attack only a balloon. Dragon can attack wizards and archers. Wizard can attack anyone, except balloon. Balloon cannot attack. The value of the loser is transfered to the winner. characterID the ID of the knight to perfrom the attack characterIndex the index of the knight in the ids-array. Just needed to save gas costs. In case it&39;s unknown or incorrect, the index is looked up in the array. / adversary won
function fight(uint32 characterID, uint16 characterIndex) public onlyUser { if (characterID != ids[characterIndex]) characterIndex = getCharacterIndex(characterID); Character storage character = characters[characterID]; require(cooldown[characterID] + config.CooldownThreshold() <= now, "not enough time passed since the last fight of this character"); require(character.owner == msg.sender, "only owner can initiate a fight for this character"); uint8 ctype = character.characterType; require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE, "balloons cannot fight"); uint16 adversaryIndex = getRandomAdversary(characterID, ctype); assert(adversaryIndex != INVALID_CHARACTER_INDEX); uint32 adversaryID = ids[adversaryIndex]; Character storage adversary = characters[adversaryID]; uint128 value; uint16 base_probability; uint16 dice = uint16(generateRandomNumber(characterID) % 100); if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) { base_probability = uint16(generateRandomNumber(dice) % 100); if (base_probability < dice) { dice = base_probability; } base_probability = 0; } uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner); uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner); if (character.value == adversary.value) { base_probability = 50; if (characterPower > adversaryPower) { base_probability += uint16(100 / config.fightFactor()); base_probability -= uint16(100 / config.fightFactor()); } base_probability = 100; if (adversaryPower > characterPower) { base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor()); } base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor()); } if (dice >= base_probability) { if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) { value = hitCharacter(characterIndex, numCharacters, adversary.characterType); if (value > 0) { numCharacters--; cooldown[characterID] = now; if (characters[characterID].fightCount < 3) { characters[characterID].fightCount++; } } if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) { castleTreasury += value; adversary.value += value; } emit NewFight(adversaryID, characterID, value, base_probability, dice); } if (characters[characterID].fightCount < 3) { characters[characterID].fightCount++; } value = hitCharacter(adversaryIndex, numCharacters, character.characterType); if (value > 0) { numCharacters--; } if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) { castleTreasury += value; character.value += value; } if (oldest == 0) findOldest(); emit NewFight(characterID, adversaryID, value, base_probability, dice); } }
7,817,326
./partial_match/137/0x7d1762E59eC0954C7A82e6E8c7FF52853DE483Ee/sources/DARKv2test1.sol
To set a new timelock contract for gov
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; }
3,510,132
./full_match/80001/0x4d6bb91Ba70af5cd3FdbfF000Aa9d2741DA5bD68/sources/contracts/CryptoHomiesGenesis.sol
total eth to mint 0.101 Calculate the platform fee Calculate the total amount to be paid by the user Transfer the platform fee to the specified address Refund any excess amount sent by the user
function _mint() internal { uint16 _tokenId = tokenIdCount + 1; require(saleActive, "Sale not active"); require(_tokenId <= MAX_SUPPLY, "No more items left"); require(msg.value >= mintRate, "Not enough ether sent"); require( !mintedUsers[currentStage][msg.sender], "User has already minted" ); uint256 totalAmount = mintRate + platformFee; require(msg.value >= totalAmount, "Insufficient payment"); Address.sendValue( payable(0x0e342c19B2B1a194ACEe8A9b3F85e92680C29f64), platformFee ); uint256 refundAmount = msg.value - totalAmount; _safeMint(msg.sender, _tokenId); commonContract.mintWithGenesis(msg.sender); tokenIdCount = _tokenId; mintedUsers[currentStage][msg.sender] = true; if (refundAmount > 0) { Address.sendValue(payable(msg.sender), refundAmount); } }
5,554,766
./partial_match/80001/0x7a6381D1B30230f29E0469705cF39432099748CA/sources/contracts/Contract.sol
Array of names for Silver package Array of names for Gold package
function getStakerName(address user) public view returns (string memory) { require(stakers[user].package != 0, "User has not purchased a package"); if (stakers[user].package == 1) { string[2] memory silverNames = ["Rookie", "D League"]; uint256 index = uint256(keccak256(abi.encodePacked(user, block.number))) % silverNames.length; return silverNames[index]; string[3] memory goldNames = ["Fan", "Mascot", "Player"]; uint256 index = uint256(keccak256(abi.encodePacked(user, block.number))) % goldNames.length; return goldNames[index]; revert("Invalid package level"); } }
8,797,351
./full_match/137/0xE1e46C14F9E400e928b0ead380B98a9309a2307B/sources/contracts/interfaces/uniswap/callback/IUniswapV3SwapCallback.sol
Callback for IUniswapV3PoolActionsswap Any contract that calls IUniswapV3PoolActionsswap must implement this interface
interface IUniswapV3SwapCallback { function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; pragma solidity >=0.8.4; }
4,684,723
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "./interfaces/IDivinium.sol"; import "./DiviniumGenesisStaker.sol"; import "./DiviniumCreaturesStaker.sol"; contract DiviniumStaker is UUPSUpgradeable, DiviniumGenesisStaker, DiviniumCreaturesStaker { string public constant VERSION = "1.0"; bytes32 public constant SPENDER_ROLE = keccak256("SPENDER"); IDivinium public deployedDivinium; // Yield tracking mapping(address => uint256) public addressToCumulatedRewards; /* * @dev Replaces the constructor for upgradeable contracts */ function initialize( address deployedPowerAddress, address deployedGenesisAddress, address deployedGenesisSupplyAddress ) public initializer { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); __DiviniumGenesisStaker_init_unchained( deployedGenesisAddress, deployedGenesisSupplyAddress ); deployedDivinium = IDivinium(deployedPowerAddress); } /** * @notice Claim $DVN from Genesis and Creatures * @param genesisIds Array containing all genesis ids. These are validated on chain * @dev genesisIds can be empty */ function claim(uint256[] memory genesisIds) external { updateRewards(genesisIds); deployedDivinium.mint( msg.sender, addressToCumulatedRewards[msg.sender] ); addressToCumulatedRewards[msg.sender] = 0; } /** * @notice Update $DNV from Genesis and Creatures * @param genesisIds Array containing all genesis ids. These are validated on chain * @dev genesisIds can be empty */ function updateRewards(uint256[] memory genesisIds) public { // Only run genesis claim if needed if (genesisIds.length > 0) { addressToCumulatedRewards[msg.sender] += _claimGenesisRewards( genesisIds ); } // Only run creature update if creature exists if (address(deployedCreature) != address(0)) { addressToCumulatedRewards[ msg.sender ] += _claimCreaturesPendingRewards(msg.sender); } } /** * @notice Get pending Creatures reward for a user * @param user The user * @return The pending rewards for a user */ function getCreaturesPendingRewards(address user) external view returns (uint256) { return _getCreaturesPendingRewards(user) + addressToCumulatedRewards[user]; } /** * @notice Update the creatures rewards * @dev Called on transfers from Creatures and ascension * @param from The user who transfered * @param to The user who received * @param creatureId The ID of the creature to update * @param creatureType The type of the creature to update */ function updateCreaturesReward( address from, address to, uint256 creatureId, CreaturesAscensionType creatureType ) external onlyRole(CREATURES_ROLE) { uint256 rewardsToAdd = _updateCreaturesRewardAndTimestamp( from, creatureId, creatureType ); if (rewardsToAdd > 0) { addressToCumulatedRewards[from] += rewardsToAdd; } // No need to cumulate rewards here because they've been claimed already above _updateCreaturesRewardAndTimestamp(to, creatureId, creatureType); } /** * @notice Update the creatures rewards form ascension * @dev Called on transfers from Creatures and ascension * @param from The user who transfered * @param creatureId The ID of the creature to update * @param creatureType The type of the creature to update */ function updateCreaturesRewardFromAscension( address from, uint256 creatureId, CreaturesAscensionType creatureType ) external onlyRole(CREATURES_ROLE) { addressToCumulatedRewards[from] += _updateCreaturesRewardAndTimestamp( from, creatureId, creatureType ); } function spendUnclaimedRewards(address from, uint256 amount) external onlyRole(SPENDER_ROLE) returns (uint256 spent) { require(addressToCumulatedRewards[from] > 0, "No unclaimed fund"); spent = amount; if (addressToCumulatedRewards[from] > amount) { addressToCumulatedRewards[from] -= amount; } else { spent = addressToCumulatedRewards[from]; addressToCumulatedRewards[from] = 0; } } /** * UUPS upgradeable */ function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IDivinium { function mint(address to_, uint256 amount_) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IGenesisTypes.sol"; import "./interfaces/IGenesisSupply.sol"; import "./interfaces/IGenesis.sol"; import "./DiviniumConfig.sol"; abstract contract DiviniumGenesisStaker is Initializable, IGenesisTypes, DiviniumConfig { uint256 public constant GENESIS_START_TIMESTAMP = 1641627068; struct GenesisUpdate { TokenType genesisType; uint256 lastUpdatedAt; } IGenesis public deployedGenesis; IGenesisSupply public deployedGenesisSupply; // Yield tracking mapping(uint256 => GenesisUpdate) public genesisIdToUpdate; event GenesisDiviniumClaim(uint256 indexed tokenId, address indexed user); /** * @dev Chained initializer */ function __DiviniumGenesisStaker_init( address deployedGenesisAddress, address deployedGenesisSupplyAddress ) internal onlyInitializing { __DiviniumGenesisStaker_init_unchained( deployedGenesisAddress, deployedGenesisSupplyAddress ); } /** * @dev Unchained initializer */ function __DiviniumGenesisStaker_init_unchained( address deployedGenesisAddress, address deployedGenesisSupplyAddress ) internal onlyInitializing { deployedGenesis = IGenesis(deployedGenesisAddress); deployedGenesisSupply = IGenesisSupply(deployedGenesisSupplyAddress); } /** * @notice Gets the rate multiplier for a genesis holder * @param genesisType The type of genesis * @return rate multiplier for Genesis collection */ function _getGenesisMultiplierForType(TokenType genesisType) internal pure returns (uint256) { require(genesisType != TokenType.NONE, "Invalid Type"); if (genesisType == TokenType.GOD) { return 16; } else if (genesisType == TokenType.DEMI_GOD) { return 8; } return 6; } /** * @notice Get Genesis reward for specific ID * @param id The ID to check reward * @param genesisType The type of genesis * @return The reward for an ID */ function _getGenesisRewardForId(uint256 id, TokenType genesisType) internal view returns (uint256) { uint256 startTimestamp = genesisIdToUpdate[id].lastUpdatedAt; if (startTimestamp == 0) { startTimestamp = GENESIS_START_TIMESTAMP; } return (BASE_RATE * _getGenesisMultiplierForType(genesisType) * (block.timestamp - startTimestamp)) / 1 days; } /** * @notice Claim $DVN from Genesis * @param genesisIds Array containing all genesis ids. These are validated on chain * @return The total Genesis $DVN rewards for ids */ function _claimGenesisRewards(uint256[] memory genesisIds) internal returns (uint256) { uint256 totalRewards; uint256 totalIds = genesisIds.length; TokenTraits memory traits; for (uint256 index = 0; index < totalIds; index++) { require( deployedGenesis.ownerOf(genesisIds[index]) == msg.sender, "Not owner of Genesis" ); traits = deployedGenesisSupply.getMetadataForTokenId( genesisIds[index] ); totalRewards += _getGenesisRewardForId( genesisIds[index], traits.tokenType ); genesisIdToUpdate[genesisIds[index]] = GenesisUpdate( traits.tokenType, block.timestamp ); emit GenesisDiviniumClaim(genesisIds[index], msg.sender); } return totalRewards; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "./interfaces/ICreatures.sol"; import "./interfaces/ICreaturesTypes.sol"; import "./DiviniumConfig.sol"; abstract contract DiviniumCreaturesStaker is Initializable, AccessControlUpgradeable, ICreaturesTypes, DiviniumConfig { bytes32 public constant CREATURES_ROLE = keccak256("CREATURES"); struct CreatureUpdate { CreaturesAscensionType creatureType; uint256 lastUpdatedAt; } ICreatures public deployedCreature; // Yield tracking mapping(uint256 => CreatureUpdate) public creaturesIdToUpdate; event CreaturesDiviniumClaim( uint256 indexed creatureId, address indexed user ); /** * @dev Chained initializer */ function __DiviniumCreaturesStaker_init() internal onlyInitializing { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); __DiviniumCreaturesStaker_init_unchained(); } /** * @dev Unchained initializer */ function __DiviniumCreaturesStaker_init_unchained() internal onlyInitializing {} /** * @notice Sets the Creatures contract address * @dev only admin can run this function * @param creaturesAddress Address of the contract */ function setCreaturesAddress(address creaturesAddress) external onlyRole(DEFAULT_ADMIN_ROLE) { deployedCreature = ICreatures(creaturesAddress); grantRole(CREATURES_ROLE, creaturesAddress); } /** * @notice Get pending Creatures reward for a user * @param user The user * @return The pending rewards for a user */ function _getCreaturesPendingRewards(address user) internal view returns (uint256) { uint256[] memory ids = deployedCreature.tokensForOwner(user); uint256 cumulRewards; // Loop through all indexes of owner, for (uint256 index = 0; index < ids.length; index++) { cumulRewards += _getCreaturesRewardForId(ids[index]); } return cumulRewards; } /** * @notice Gets the rate multiplier for a creature holder * @param creatureAscensionType The ascension type * @return rate multiplier for Creature collection */ function _getCreaturesMultiplierForType( CreaturesAscensionType creatureAscensionType ) internal pure returns (uint256) { if (creatureAscensionType == CreaturesAscensionType.NONE) { return 1; } else if ( creatureAscensionType == CreaturesAscensionType.ASCENDED_NONE ) { return 2; } else if ( creatureAscensionType == CreaturesAscensionType.ASCENDED_SINGLE ) { return 3; } else if ( creatureAscensionType == CreaturesAscensionType.ASCENDED_DOUBLE ) { return 4; } return 5; } /** * @notice Get Creatures reward for Id * @param creatureId id of the creature to get rewards from, * @return The reward for the type */ function _getCreaturesRewardForId(uint256 creatureId) internal view returns (uint256) { require( creaturesIdToUpdate[creatureId].lastUpdatedAt != 0, "Invalid Creature" ); CreatureUpdate memory creatureData = creaturesIdToUpdate[creatureId]; return (BASE_RATE * _getCreaturesMultiplierForType(creatureData.creatureType) * (block.timestamp - creatureData.lastUpdatedAt)) / 1 days; } /** * @notice Claim the creatures pending reward of a user * @param user The user * @return The pending rewards for a user */ function _claimCreaturesPendingRewards(address user) internal returns (uint256) { uint256[] memory ids = deployedCreature.tokensForOwner(user); uint256 cumulRewards; // Loop through all indexes of owner, for (uint256 index = 0; index < ids.length; index++) { uint256 currentId = ids[index]; cumulRewards += _getCreaturesRewardForId(currentId); creaturesIdToUpdate[currentId] = CreatureUpdate( creaturesIdToUpdate[currentId].creatureType, block.timestamp ); } return cumulRewards; } /** * @notice Update the last update timestamp for user * @param user The user to update * @param creatureId The ID of the creature to update * @param creatureType The type of the creature to update */ function _updateCreaturesRewardAndTimestamp( address user, uint256 creatureId, CreaturesAscensionType creatureType ) internal returns (uint256 rewards) { rewards = 0; if (user != address(0)) { // We check if the last update is before the current timestamp // The creatures contract update the FROM then the TO // On a transfer, FROM will get the pending rewards and TO will not // because timestamp is set after. On mint, we set it on the TO. if ( creaturesIdToUpdate[creatureId].lastUpdatedAt < block.timestamp ) { rewards = _getCreaturesRewardForId(creatureId); emit CreaturesDiviniumClaim(creatureId, user); } } if (creaturesIdToUpdate[creatureId].lastUpdatedAt < block.timestamp) { creaturesIdToUpdate[creatureId] = CreatureUpdate( creatureType, block.timestamp ); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @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 Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @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 Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // 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 AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly 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/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IGenesisTypes { enum TokenType { NONE, GOD, DEMI_GOD, ELEMENTAL } enum TokenSubtype { NONE, CREATIVE, DESTRUCTIVE, AIR, EARTH, ELECTRICITY, FIRE, MAGMA, METAL, WATER } struct TokenTraits { TokenType tokenType; TokenSubtype tokenSubtype; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "./IGenesisTypes.sol"; interface IGenesisSupply is IGenesisTypes { function getMetadataForTokenId(uint256 tokenId) external view returns (TokenTraits memory traits); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IGenesis { function ownerOf(uint256 tokenId) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; abstract contract DiviniumConfig { uint256 public constant BASE_RATE = 1 ether; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ 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}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "./ICreaturesTypes.sol"; interface ICreatures is ICreaturesTypes { function tokensForOwner(address user) external view returns (uint256[] memory ids); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface ICreaturesTypes { enum CreaturesAscensionType { NONE, ASCENDED_NONE, ASCENDED_SINGLE, ASCENDED_DOUBLE, ASCENDED_FULL } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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 IERC165Upgradeable { /** * @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); }
Sets the Creatures contract address only admin can run this function creaturesAddress Address of the contract/
function __DiviniumCreaturesStaker_init_unchained() internal onlyInitializing function setCreaturesAddress(address creaturesAddress) external onlyRole(DEFAULT_ADMIN_ROLE) { deployedCreature = ICreatures(creaturesAddress); grantRole(CREATURES_ROLE, creaturesAddress); }
463,934
./full_match/1/0xcB0900D9307Da7FD4e000A9093f24Ce25D937D42/sources/contracts/ClaimManagement.sol
Force file a claim for a COVER-supported contract `_protocol` that bypasses validateClaim by paying the `forceClaimFee` fee `_incidentTimestamp` must be within the past 14 days. Only callable when isAuditorVoting is true _protocol address: contract address of the protocol that COVER supports _protocolName bytes32: protocol name for `_protocol` _incidentTimestamp uint48: timestamp of the claim incident Emits ClaimFiled/
function forceFileClaim(address _protocol, bytes32 _protocolName, uint48 _incidentTimestamp) external override onlyWhenAuditorVoting { require(_protocol != address(0), "COVER_CM: protocol cannot be 0"); require( _protocol == getAddressFromFactory(_protocolName), "COVER_CM: invalid protocol address" ); require( block.timestamp.sub(_incidentTimestamp) <= getFileClaimWindow(_protocol), "COVER_CM: block.timestamp - incidentTimestamp > fileClaimWindow" ); uint256 nonce = getProtocolNonce(_protocol); protocolClaims[_protocol][nonce].push(Claim({ state: ClaimState.ForceFiled, filedBy: msg.sender, payoutNumerator: 0, payoutDenominator: 1, filedTimestamp: uint48(block.timestamp), incidentTimestamp: _incidentTimestamp, decidedTimestamp: 0, feePaid: forceClaimFee })); feeCurrency.safeTransferFrom(msg.sender, address(this), forceClaimFee); emit ClaimFiled({ isForced: true, filedBy: msg.sender, protocol: _protocol, incidentTimestamp: _incidentTimestamp, nonce: nonce, index: protocolClaims[_protocol][nonce].length - 1, feePaid: forceClaimFee }); }
9,760,452
./full_match/84531/0x861450380ad7099591f2b311b192E72eAdF86E2f/sources/contracts/access-control-registry/AccessControlRegistry.sol
Initializes a role by setting its admin role and grants it to the sender If the sender should not have the initialized role, they should explicitly renounce it after initializing it. Once a role is initialized, subsequent initializations have no effect other than granting the role to the sender. The sender must be a member of `adminRole`. `adminRole` value is not validated because the sender cannot have the `bytes32(0)` role. If the sender is an uninitialized manager that is initializing a role directly under their root role, manager initialization will happen automatically, which will grant the sender `adminRole` and allow them to initialize the role. adminRole Admin role to be assigned to the initialized role description Human-readable description of the initialized role return role Initialized role AccessControl roles have `DEFAULT_ADMIN_ROLE` (i.e., `bytes32(0)`) as their `adminRole` by default. No account in AccessControlRegistry can possibly have that role, which means all initialized roles will have non-default admin roles, and vice versa.
function initializeRoleAndGrantToSender( bytes32 adminRole, string calldata description ) external override returns (bytes32 role) { require(bytes(description).length > 0, "Role description empty"); role = deriveRole(adminRole, description); if (getRoleAdmin(role) == DEFAULT_ADMIN_ROLE) { if (adminRole == deriveRootRole(_msgSender())) { initializeManager(_msgSender()); } _setRoleAdmin(role, adminRole); emit InitializedRole(role, adminRole, description, _msgSender()); } grantRole(role, _msgSender()); }
11,504,862
./full_match/44787/0x254b15349D5EB0fbA7Fd834BcF59D033f5b174a0/sources/contracts/VerstContract.sol
Function to get burned tokens for a specific project Initialize a dynamic array to hold the results Counter to keep track of actual results
function getTokensBurnedForProject(uint256 projectId) public view returns (TokenBurn[] memory) { TokenBurn[] memory projectBurnedTokens = new TokenBurn[](burnedTokens.length); uint256 counter = 0; for (uint256 i = 0; i < burnedTokens.length; i++) { if (burnedTokens[i].projectId == projectId) { projectBurnedTokens[counter] = burnedTokens[i]; counter++; } } for (uint256 i = 0; i < burnedTokens.length; i++) { if (burnedTokens[i].projectId == projectId) { projectBurnedTokens[counter] = burnedTokens[i]; counter++; } } TokenBurn[] memory results = new TokenBurn[](counter); for (uint256 i = 0; i < counter; i++) { results[i] = projectBurnedTokens[i]; } return results; }
13,259,941
pragma solidity ^0.4.8; contract Token{ // token总量,默认会为public变量生成一个getter函数接口,名称为totalSupply(). uint256 public totalSupply; /// 获取账户_owner拥有token的数量 function balanceOf(address _owner) constant returns (uint256 balance); //从消息发送者账户中往_to账户转数量为_value的token function transfer(address _to, uint256 _value) returns (bool success); //从账户_from中往账户_to转数量为_value的token,与approve方法配合使用 function transferFrom(address _from, address _to, uint256 _value) returns (bool success); //消息发送账户设置账户_spender能从发送账户中转出数量为_value的token function approve(address _spender, uint256 _value) returns (bool success); //获取账户_spender可以从账户_owner中转出token的数量 function allowance(address _owner, address _spender) constant returns (uint256 remaining); //发生转账时必须要触发的事件 event Transfer(address indexed _from, address indexed _to, uint256 _value); //当函数approve(address _spender, uint256 _value)成功执行时必须触发的事件 event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //默认totalSupply 不会超过最大值 (2^256 - 1). //如果随着时间的推移将会有新的token生成,则可以用下面这句避免溢出的异常 //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value;//从消息发送者账户中减去token数量_value balances[_to] += _value;//往接收账户增加token数量_value Transfer(msg.sender, _to, _value);//触发转币交易事件 return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //require(balances[_from] >= _value && allowed[_from][msg.sender] >= // _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value Transfer(_from, _to, _value);//触发转币交易事件 return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender];//允许_spender从_owner中转出的token数 } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract KangKangToken is StandardToken { string public constant name = "Kang Kang Token"; string public constant symbol = "KKT"; uint8 public constant decimals = 18; uint256 public constant ONE_TOKENS = (10 ** uint256(decimals)); uint256 public constant MILLION_TOKENS = (10**6) * ONE_TOKENS; uint256 public constant TOTAL_TOKENS = 1500 * MILLION_TOKENS; function KangKangToken () { balances[msg.sender] = TOTAL_TOKENS; // 初始token数量给予消息发送者 totalSupply = TOTAL_TOKENS; // 设置初始总量 } }
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); return true; }
5,545,600
./full_match/1/0xa0334AD349c1D805BF6c9e42125845B7D4F63aDe/sources/contracts/BlockHistory.sol
Parses the proof inputs for block history snark proofs proof the snark proof return proofParent the parentHash of the proof blocks return proofLast the lastHash of the proof blocks return proofRoot the merkle root of the proof blocks/
function parseProofInputs(SignedRecursiveProof calldata proof) internal pure returns ( bytes32 proofParent, bytes32 proofLast, bytes32 proofRoot ) { uint256[] calldata inputs = proof.inner.inputs; require(inputs.length == 12); proofParent = readHashWords(inputs[0:4]); proofLast = readHashWords(inputs[4:8]); proofRoot = readHashWords(inputs[8:12]); }
17,179,310
./full_match/4/0xf75701CD57BC4EF0ed9C4BeBB6751C859c4E7Ccb/sources/contracts/synthetix/SafeDecimalMath.sol
return The result of safely dividing x and y. The return value is as a rounded decimal in the precision unit specified in the parameter. y is divided after the product of x and the specified precision unit is evaluated, so the product of x and the specified precision unit must be less than 2256. The result is rounded to the nearest increment./
function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; }
13,306,110
/** *Submitted for verification at Etherscan.io on 2021-04-01 */ pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; /** * @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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 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. * * _Available since v2.4.0._ */ 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. 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 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); } /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library Constants { /* Chain */ uint256 private constant CHAIN_ID = 1; // Mainnet /* Bootstrapping */ uint256 private constant BOOTSTRAPPING_PERIOD = 150; // 150 epochs uint256 private constant BOOTSTRAPPING_PRICE = 154e16; // 1.54 USDC (targeting 4.5% inflation) /* Oracle */ address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); uint256 private constant ORACLE_RESERVE_MINIMUM = 1e10; // 10,000 USDC /* Bonding */ uint256 private constant INITIAL_STAKE_MULTIPLE = 1e6; // 100 DSD -> 100M DSDS /* Epoch */ struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant EPOCH_OFFSET = 0; uint256 private constant EPOCH_START = 1606348800; uint256 private constant EPOCH_PERIOD = 7200; /* Governance */ uint256 private constant GOVERNANCE_PERIOD = 36; uint256 private constant GOVERNANCE_QUORUM = 20e16; // 20% uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5% uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66% uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs /* DAO */ uint256 private constant ADVANCE_INCENTIVE_PREMIUM = 125e16; // pay out 25% more than tx fee value uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 36; // 36 epochs fluid /* Pool */ uint256 private constant POOL_EXIT_LOCKUP_EPOCHS = 12; // 12 epochs fluid address private constant POOL_ADDRESS = address(0xf929fc6eC25850ce00e457c4F28cDE88A94415D8); address private constant CONTRACTION_POOL_ADDRESS = address(0); // TODO: add deployed address uint256 private constant CONTRACTION_POOL_TARGET_SUPPLY = 10e16; // target 10% of the supply in the CPool uint256 private constant CONTRACTION_POOL_TARGET_REWARD = 29e13; // 0.029% per epoch ~ 250% APY with 10% of supply in the CPool /* Regulator */ uint256 private constant SUPPLY_CHANGE_LIMIT = 2e16; // 2% uint256 private constant SUPPLY_CHANGE_DIVISOR = 25e18; // 25 > Max expansion at 1.5 uint256 private constant COUPON_SUPPLY_CHANGE_LIMIT = 3e16; // 3% uint256 private constant COUPON_SUPPLY_CHANGE_DIVISOR = 1666e16; // 16.66 > Max expansion at ~1.5 uint256 private constant NEGATIVE_SUPPLY_CHANGE_DIVISOR = 5e18; // 5 > Max negative expansion at 0.9 uint256 private constant ORACLE_POOL_RATIO = 40; // 40% uint256 private constant TREASURY_RATIO = 3; // 3% /* Deployed */ address private constant DAO_ADDRESS = address(0x6Bf977ED1A09214E6209F4EA5f525261f1A2690a); address private constant DOLLAR_ADDRESS = address(0xBD2F0Cd039E0BFcf88901C98c0bFAc5ab27566e3); address private constant CONTRACTION_DOLLAR_ADDRESS = address(0xDe25486CCb4588Ce5D9fB188fb6Af72E768a466a); address private constant PAIR_ADDRESS = address(0x26d8151e631608570F3c28bec769C3AfEE0d73a3); // SushiSwap pair address private constant CONTRACTION_PAIR_ADDRESS = address(0x4a4572D92Daf14D29C3b8d001A2d965c6A2b1515); address private constant TREASURY_ADDRESS = address(0xC7DA8087b8BA11f0892f1B0BFacfD44C116B303e); /* DIP-10 */ uint256 private constant EARNABLE_FACTOR = 1e18; // 100% - Amount of CDSD earnable for DSD burned uint256 private constant CDSD_REDEMPTION_RATIO = 50; // 50% uint256 private constant CONTRACTION_BONDING_REWARDS = 51000000000000; // ~25% APY /** * Getters */ function getUsdcAddress() internal pure returns (address) { return USDC; } function getOracleReserveMinimum() internal pure returns (uint256) { return ORACLE_RESERVE_MINIMUM; } function getEpochStrategy() internal pure returns (EpochStrategy memory) { return EpochStrategy({ offset: EPOCH_OFFSET, start: EPOCH_START, period: EPOCH_PERIOD }); } function getInitialStakeMultiple() internal pure returns (uint256) { return INITIAL_STAKE_MULTIPLE; } function getBootstrappingPeriod() internal pure returns (uint256) { return BOOTSTRAPPING_PERIOD; } function getBootstrappingPrice() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: BOOTSTRAPPING_PRICE }); } function getGovernancePeriod() internal pure returns (uint256) { return GOVERNANCE_PERIOD; } function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_QUORUM }); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_PROPOSAL_THRESHOLD }); } function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_SUPER_MAJORITY }); } function getGovernanceEmergencyDelay() internal pure returns (uint256) { return GOVERNANCE_EMERGENCY_DELAY; } function getAdvanceIncentivePremium() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: ADVANCE_INCENTIVE_PREMIUM }); } function getDAOExitLockupEpochs() internal pure returns (uint256) { return DAO_EXIT_LOCKUP_EPOCHS; } function getPoolExitLockupEpochs() internal pure returns (uint256) { return POOL_EXIT_LOCKUP_EPOCHS; } function getPoolAddress() internal pure returns (address) { return POOL_ADDRESS; } function getContractionPoolAddress() internal pure returns (address) { return CONTRACTION_POOL_ADDRESS; } function getContractionPoolTargetSupply() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: CONTRACTION_POOL_TARGET_SUPPLY}); } function getContractionPoolTargetReward() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: CONTRACTION_POOL_TARGET_REWARD}); } function getSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: SUPPLY_CHANGE_LIMIT }); } function getSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: SUPPLY_CHANGE_DIVISOR }); } function getCouponSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: COUPON_SUPPLY_CHANGE_LIMIT }); } function getCouponSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: COUPON_SUPPLY_CHANGE_DIVISOR }); } function getNegativeSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: NEGATIVE_SUPPLY_CHANGE_DIVISOR }); } function getOraclePoolRatio() internal pure returns (uint256) { return ORACLE_POOL_RATIO; } function getTreasuryRatio() internal pure returns (uint256) { return TREASURY_RATIO; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getDaoAddress() internal pure returns (address) { return DAO_ADDRESS; } function getDollarAddress() internal pure returns (address) { return DOLLAR_ADDRESS; } function getContractionDollarAddress() internal pure returns (address) { return CONTRACTION_DOLLAR_ADDRESS; } function getPairAddress() internal pure returns (address) { return PAIR_ADDRESS; } function getContractionPairAddress() internal pure returns (address) { return CONTRACTION_PAIR_ADDRESS; } function getTreasuryAddress() internal pure returns (address) { return TREASURY_ADDRESS; } function getEarnableFactor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: EARNABLE_FACTOR}); } function getCDSDRedemptionRatio() internal pure returns (uint256) { return CDSD_REDEMPTION_RATIO; } function getContractionBondingRewards() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: CONTRACTION_BONDING_REWARDS}); } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IDollar is IERC20 { function burn(uint256 amount) public; function burnFrom(address account, uint256 amount) public; function mint(address account, uint256 amount) public returns (bool); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IDAO { function epoch() external view returns (uint256); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IUSDC { function isBlacklisted(address _account) external view returns (bool); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract CPoolAccount { enum Status { Frozen, Fluid, Locked } struct State { uint256 staged; uint256 claimable; uint256 bonded; uint256 phantom; uint256 fluidUntil; } } contract CPoolStorage { struct Provider { IDAO dao; IDollar dollar; IERC20 univ2; } struct Balance { uint256 staged; uint256 claimable; uint256 bonded; uint256 phantom; } struct State { Balance balance; Provider provider; bool paused; mapping(address => CPoolAccount.State) accounts; } } contract CPoolState { CPoolStorage.State _state; } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract CPoolGetters is CPoolState { using SafeMath for uint256; /** * Global */ function usdc() public view returns (address) { return Constants.getUsdcAddress(); } function dao() public view returns (IDAO) { return IDAO(Constants.getDaoAddress()); } function cdsd() public view returns (IDollar) { return IDollar(Constants.getContractionDollarAddress()); } function univ2() public view returns (IERC20) { return IERC20(Constants.getContractionPairAddress()); } function totalBonded() public view returns (uint256) { return _state.balance.bonded; } function totalStaged() public view returns (uint256) { return _state.balance.staged; } function totalClaimable() public view returns (uint256) { return _state.balance.claimable; } function totalPhantom() public view returns (uint256) { return _state.balance.phantom; } function totalRewarded() public view returns (uint256) { return cdsd().balanceOf(address(this)).sub(totalClaimable()); } function paused() public view returns (bool) { return _state.paused; } /** * Account */ function balanceOfStaged(address account) public view returns (uint256) { return _state.accounts[account].staged; } function balanceOfClaimable(address account) public view returns (uint256) { return _state.accounts[account].claimable; } function balanceOfBonded(address account) public view returns (uint256) { return _state.accounts[account].bonded; } function balanceOfPhantom(address account) public view returns (uint256) { return _state.accounts[account].phantom; } function balanceOfRewarded(address account) public view returns (uint256) { uint256 totalBonded = totalBonded(); if (totalBonded == 0) { return 0; } uint256 totalRewardedWithPhantom = totalRewarded().add(totalPhantom()); uint256 balanceOfRewardedWithPhantom = totalRewardedWithPhantom .mul(balanceOfBonded(account)) .div(totalBonded); uint256 balanceOfPhantom = balanceOfPhantom(account); if (balanceOfRewardedWithPhantom > balanceOfPhantom) { return balanceOfRewardedWithPhantom.sub(balanceOfPhantom); } return 0; } function fluidUntil(address account) public view returns (uint256) { return _state.accounts[account].fluidUntil; } function statusOf(address account) public view returns (CPoolAccount.Status) { return epoch() >= _state.accounts[account].fluidUntil ? CPoolAccount.Status.Frozen : CPoolAccount.Status.Fluid; } /** * Epoch */ function epoch() internal view returns (uint256) { return dao().epoch(); } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract CPoolSetters is CPoolState, CPoolGetters { using SafeMath for uint256; /** * Global */ function pause() internal { _state.paused = true; } /** * Account */ function incrementBalanceOfBonded(address account, uint256 amount) internal { _state.accounts[account].bonded = _state.accounts[account].bonded.add(amount); _state.balance.bonded = _state.balance.bonded.add(amount); } function decrementBalanceOfBonded(address account, uint256 amount, string memory reason) internal { _state.accounts[account].bonded = _state.accounts[account].bonded.sub(amount, reason); _state.balance.bonded = _state.balance.bonded.sub(amount, reason); } function incrementBalanceOfStaged(address account, uint256 amount) internal { _state.accounts[account].staged = _state.accounts[account].staged.add(amount); _state.balance.staged = _state.balance.staged.add(amount); } function decrementBalanceOfStaged(address account, uint256 amount, string memory reason) internal { _state.accounts[account].staged = _state.accounts[account].staged.sub(amount, reason); _state.balance.staged = _state.balance.staged.sub(amount, reason); } function incrementBalanceOfClaimable(address account, uint256 amount) internal { _state.accounts[account].claimable = _state.accounts[account].claimable.add(amount); _state.balance.claimable = _state.balance.claimable.add(amount); } function decrementBalanceOfClaimable(address account, uint256 amount, string memory reason) internal { _state.accounts[account].claimable = _state.accounts[account].claimable.sub(amount, reason); _state.balance.claimable = _state.balance.claimable.sub(amount, reason); } function incrementBalanceOfPhantom(address account, uint256 amount) internal { _state.accounts[account].phantom = _state.accounts[account].phantom.add(amount); _state.balance.phantom = _state.balance.phantom.add(amount); } function decrementBalanceOfPhantom(address account, uint256 amount, string memory reason) internal { _state.accounts[account].phantom = _state.accounts[account].phantom.sub(amount, reason); _state.balance.phantom = _state.balance.phantom.sub(amount, reason); } function unfreeze(address account) internal { _state.accounts[account].fluidUntil = epoch().add(Constants.getPoolExitLockupEpochs()); } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure 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 factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract CLiquidity is CPoolGetters { function addLiquidity(uint256 dollarAmount) internal returns (uint256, uint256) { (address cdsd, address usdc) = (address(cdsd()), usdc()); (uint reserveA, uint reserveB) = getReserves(cdsd, usdc); uint256 usdcAmount = (reserveA == 0 && reserveB == 0) ? dollarAmount : UniswapV2Library.quote(dollarAmount, reserveA, reserveB); address pair = address(univ2()); IERC20(cdsd).transfer(pair, dollarAmount); IERC20(usdc).transferFrom(msg.sender, pair, usdcAmount); return (usdcAmount, IUniswapV2Pair(pair).mint(address(this))); } // overridable for testing function getReserves(address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(Constants.getContractionPairAddress()).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract CPool is CPoolSetters, CLiquidity { using SafeMath for uint256; constructor() public { } bytes32 private constant FILE = "Pool"; event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, uint256 value); event Claim(address indexed account, uint256 value); event Bond(address indexed account, uint256 start, uint256 value); event Unbond(address indexed account, uint256 start, uint256 value, uint256 newClaimable); event Provide(address indexed account, uint256 value, uint256 lessUsdc, uint256 newUniv2); function deposit(uint256 value) external onlyFrozen(msg.sender) notPaused { univ2().transferFrom(msg.sender, address(this), value); incrementBalanceOfStaged(msg.sender, value); balanceCheck(); emit Deposit(msg.sender, value); } function withdraw(uint256 value) external onlyFrozen(msg.sender) { univ2().transfer(msg.sender, value); decrementBalanceOfStaged(msg.sender, value, "Pool: insufficient staged balance"); balanceCheck(); emit Withdraw(msg.sender, value); } function claim(uint256 value) external onlyFrozen(msg.sender) { cdsd().transfer(msg.sender, value); decrementBalanceOfClaimable(msg.sender, value, "Pool: insufficient claimable balance"); balanceCheck(); emit Claim(msg.sender, value); } function bond(uint256 value) external notPaused { unfreeze(msg.sender); uint256 totalRewardedWithPhantom = totalRewarded().add(totalPhantom()); uint256 newPhantom = totalBonded() == 0 ? totalRewarded() == 0 ? Constants.getInitialStakeMultiple().mul(value) : 0 : totalRewardedWithPhantom.mul(value).div(totalBonded()); incrementBalanceOfBonded(msg.sender, value); incrementBalanceOfPhantom(msg.sender, newPhantom); decrementBalanceOfStaged(msg.sender, value, "Pool: insufficient staged balance"); balanceCheck(); emit Bond(msg.sender, epoch().add(1), value); } function unbond(uint256 value) external { unfreeze(msg.sender); uint256 balanceOfBonded = balanceOfBonded(msg.sender); Require.that( balanceOfBonded > 0, FILE, "insufficient bonded balance" ); uint256 newClaimable = balanceOfRewarded(msg.sender).mul(value).div(balanceOfBonded); uint256 lessPhantom = balanceOfPhantom(msg.sender).mul(value).div(balanceOfBonded); incrementBalanceOfStaged(msg.sender, value); incrementBalanceOfClaimable(msg.sender, newClaimable); decrementBalanceOfBonded(msg.sender, value, "Pool: insufficient bonded balance"); decrementBalanceOfPhantom(msg.sender, lessPhantom, "Pool: insufficient phantom balance"); balanceCheck(); emit Unbond(msg.sender, epoch().add(1), value, newClaimable); } function provide(uint256 value) external notPaused { Require.that( totalBonded() > 0, FILE, "insufficient total bonded" ); Require.that( totalRewarded() > 0, FILE, "insufficient total rewarded" ); Require.that( balanceOfRewarded(msg.sender) >= value, FILE, "insufficient rewarded balance" ); (uint256 lessUsdc, uint256 newUniv2) = addLiquidity(value); uint256 totalRewardedWithPhantom = totalRewarded().add(totalPhantom()).add(value); uint256 newPhantomFromBonded = totalRewardedWithPhantom.mul(newUniv2).div(totalBonded()); incrementBalanceOfBonded(msg.sender, newUniv2); incrementBalanceOfPhantom(msg.sender, value.add(newPhantomFromBonded)); balanceCheck(); emit Provide(msg.sender, value, lessUsdc, newUniv2); } function emergencyWithdraw(address token, uint256 value) external onlyDao { IERC20(token).transfer(address(dao()), value); } function emergencyPause() external onlyDao { pause(); } function balanceCheck() private { Require.that( univ2().balanceOf(address(this)) >= totalStaged().add(totalBonded()), FILE, "Inconsistent UNI-V2 balances" ); } modifier onlyFrozen(address account) { Require.that( statusOf(account) == CPoolAccount.Status.Frozen, FILE, "Not frozen" ); _; } modifier onlyDao() { Require.that( msg.sender == address(dao()), FILE, "Not dao" ); _; } modifier notPaused() { Require.that( !paused(), FILE, "Paused" ); _; } }
overridable for testing
function getReserves(address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(Constants.getContractionPairAddress()).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); }
8,026,374
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.13; import "./libraries/SafeMath.sol"; import "./libraries/SafeERC20.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IsOHM.sol"; import "./interfaces/IgOHM.sol"; import "./interfaces/IDistributor.sol"; import "./types/OlympusAccessControlled.sol"; contract OlympusStaking is OlympusAccessControlled { /* ========== DEPENDENCIES ========== */ using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for IsOHM; using SafeERC20 for IgOHM; /* ========== EVENTS ========== */ event DistributorSet(address distributor); event WarmupSet(uint256 warmup); /* ========== DATA STRUCTURES ========== */ struct Epoch { uint256 length; // in seconds uint256 number; // since inception uint256 end; // timestamp uint256 distribute; // amount } struct Claim { uint256 deposit; // if forfeiting uint256 gons; // staked balance uint256 expiry; // end of warmup period bool lock; // prevents malicious delays for claim } /* ========== STATE VARIABLES ========== */ IERC20 public immutable OHM; IsOHM public immutable sOHM; IgOHM public immutable gOHM; Epoch public epoch; IDistributor public distributor; mapping(address => Claim) public warmupInfo; uint256 public warmupPeriod; uint256 private gonsInWarmup; /* ========== CONSTRUCTOR ========== */ constructor( address _ohm, address _sOHM, address _gOHM, uint256 _epochLength, uint256 _firstEpochNumber, uint256 _firstEpochTime, address _authority ) OlympusAccessControlled(IOlympusAuthority(_authority)) { require(_ohm != address(0), "Zero address: OHM"); OHM = IERC20(_ohm); require(_sOHM != address(0), "Zero address: sOHM"); sOHM = IsOHM(_sOHM); require(_gOHM != address(0), "Zero address: gOHM"); gOHM = IgOHM(_gOHM); epoch = Epoch({ length: _epochLength, number: _firstEpochNumber, end: _firstEpochTime, distribute: 0 }); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice stake OHM to enter warmup * @param _to address * @param _amount uint * @param _claim bool * @param _rebasing bool * @return uint */ function stake( address _to, uint256 _amount, bool _rebasing, bool _claim ) external returns (uint256) { OHM.safeTransferFrom(msg.sender, address(this), _amount); _amount = _amount.add(rebase()); // add bounty if rebase occurred if (_claim && warmupPeriod == 0) { return _send(_to, _amount, _rebasing); } else { Claim memory info = warmupInfo[_to]; if (!info.lock) { require(_to == msg.sender, "External deposits for account are locked"); } warmupInfo[_to] = Claim({ deposit: info.deposit.add(_amount), gons: info.gons.add(sOHM.gonsForBalance(_amount)), expiry: epoch.number.add(warmupPeriod), lock: info.lock }); gonsInWarmup = gonsInWarmup.add(sOHM.gonsForBalance(_amount)); return _amount; } } /** * @notice retrieve stake from warmup * @param _to address * @param _rebasing bool * @return uint */ function claim(address _to, bool _rebasing) public returns (uint256) { Claim memory info = warmupInfo[_to]; if (!info.lock) { require(_to == msg.sender, "External claims for account are locked"); } if (epoch.number >= info.expiry && info.expiry != 0) { delete warmupInfo[_to]; gonsInWarmup = gonsInWarmup.sub(info.gons); return _send(_to, sOHM.balanceForGons(info.gons), _rebasing); } return 0; } /** * @notice forfeit stake and retrieve OHM * @return uint */ function forfeit() external returns (uint256) { Claim memory info = warmupInfo[msg.sender]; delete warmupInfo[msg.sender]; gonsInWarmup = gonsInWarmup.sub(info.gons); OHM.safeTransfer(msg.sender, info.deposit); return info.deposit; } /** * @notice prevent new deposits or claims from ext. address (protection from malicious activity) */ function toggleLock() external { warmupInfo[msg.sender].lock = !warmupInfo[msg.sender].lock; } /** * @notice redeem sOHM for OHMs * @param _to address * @param _amount uint * @param _trigger bool * @param _rebasing bool * @return amount_ uint */ function unstake( address _to, uint256 _amount, bool _trigger, bool _rebasing ) external returns (uint256 amount_) { amount_ = _amount; uint256 bounty; if (_trigger) { bounty = rebase(); } if (_rebasing) { sOHM.safeTransferFrom(msg.sender, address(this), _amount); amount_ = amount_.add(bounty); } else { gOHM.burn(msg.sender, _amount); // amount was given in gOHM terms amount_ = gOHM.balanceFrom(amount_).add(bounty); // convert amount to OHM terms & add bounty } require( amount_ <= OHM.balanceOf(address(this)), "Insufficient OHM balance in contract" ); OHM.safeTransfer(_to, amount_); } /** * @notice convert _amount sOHM into gBalance_ gOHM * @param _to address * @param _amount uint * @return gBalance_ uint */ function wrap(address _to, uint256 _amount) external returns (uint256 gBalance_) { sOHM.safeTransferFrom(msg.sender, address(this), _amount); gBalance_ = gOHM.balanceTo(_amount); gOHM.mint(_to, gBalance_); } /** * @notice convert _amount gOHM into sBalance_ sOHM * @param _to address * @param _amount uint * @return sBalance_ uint */ function unwrap(address _to, uint256 _amount) external returns (uint256 sBalance_) { gOHM.burn(msg.sender, _amount); sBalance_ = gOHM.balanceFrom(_amount); sOHM.safeTransfer(_to, sBalance_); } /** * @notice trigger rebase if epoch over * @return uint256 */ function rebase() public returns (uint256) { uint256 bounty; if (epoch.end <= block.timestamp) { sOHM.rebase(epoch.distribute, epoch.number); epoch.end = epoch.end.add(epoch.length); epoch.number++; if (address(distributor) != address(0)) { distributor.distribute(); bounty = distributor.retrieveBounty(); // Will mint ohm for this contract if there exists a bounty } uint256 balance = OHM.balanceOf(address(this)); uint256 staked = sOHM.circulatingSupply(); if (balance <= staked.add(bounty)) { epoch.distribute = 0; } else { epoch.distribute = balance.sub(staked).sub(bounty); } } return bounty; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice send staker their amount as sOHM or gOHM * @param _to address * @param _amount uint * @param _rebasing bool */ function _send( address _to, uint256 _amount, bool _rebasing ) internal returns (uint256) { if (_rebasing) { sOHM.safeTransfer(_to, _amount); // send as sOHM (equal unit as OHM) return _amount; } else { gOHM.mint(_to, gOHM.balanceTo(_amount)); // send as gOHM (convert units from OHM) return gOHM.balanceTo(_amount); } } /* ========== VIEW FUNCTIONS ========== */ /** * @notice returns the sOHM index, which tracks rebase growth * @return uint */ function index() public view returns (uint256) { return sOHM.index(); } /** * @notice total supply in warmup */ function supplyInWarmup() public view returns (uint256) { return sOHM.balanceForGons(gonsInWarmup); } /** * @notice seconds until the next epoch begins */ function secondsToNextEpoch() external view returns (uint256) { return epoch.end.sub(block.timestamp); } /* ========== MANAGERIAL FUNCTIONS ========== */ /** * @notice sets the contract address for LP staking * @param _distributor address */ function setDistributor(address _distributor) external onlyGovernor { distributor = IDistributor(_distributor); emit DistributorSet(_distributor); } /** * @notice set warmup period for new stakers * @param _warmupPeriod uint */ function setWarmupLength(uint256 _warmupPeriod) external onlyGovernor { warmupPeriod = _warmupPeriod; emit WarmupSet(_warmupPeriod); } }
total supply in warmup/
function supplyInWarmup() public view returns (uint256) { return sOHM.balanceForGons(gonsInWarmup); }
1,811,431
./full_match/5/0xEE6F650593766d9114236986609ae52252c58d1a/sources/Sapphire/MarketplaceContract.sol
Updates the fee amount which is collected during sales This is callable only by the owner. Fee may not exceed MAX_FEE _newFee the updated fee amount is basis points
function setFee(uint256 _newFee) public onlyRole(SAPPHIRE_MARKETPLACE_ADMIN_ROLE) { require(_newFee <= MAX_FEE, "SapphireMarketplace: max fee"); fee = _newFee; emit UpdateFee(_newFee); }
7,050,931
/** *Submitted for verification at Etherscan.io on 2021-09-17 */ // Sources flattened with hardhat v2.6.0 https://hardhat.org // File contracts/interfaces/IArmorMaster.sol pragma solidity ^0.6.0; interface IArmorMaster { function registerModule(bytes32 _key, address _module) external; function getModule(bytes32 _key) external view returns(address); function keep() external; } // File contracts/general/Ownable.sol pragma solidity ^0.6.6; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * @dev Completely default OpenZeppelin. */ contract Ownable { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initializeOwnable() internal { require(_owner == address(0), "already initialized"); _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "msg.sender is not owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return 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 { _pendingOwner = newOwner; } function receiveOwnership() public { require(msg.sender == _pendingOwner, "only pending owner can call this function"); _transferOwnership(_pendingOwner); _pendingOwner = address(0); } /** * @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; } uint256[50] private __gap; } // File contracts/general/Bytes32.sol pragma solidity ^0.6.6; library Bytes32 { function toString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } // File contracts/general/ArmorModule.sol pragma solidity ^0.6.0; /** * @dev Each arCore contract is a module to enable simple communication and interoperability. ArmorMaster.sol is master. **/ contract ArmorModule { IArmorMaster internal _master; using Bytes32 for bytes32; modifier onlyOwner() { require(msg.sender == Ownable(address(_master)).owner(), "only owner can call this function"); _; } modifier doKeep() { _master.keep(); _; } modifier onlyModule(bytes32 _module) { string memory message = string(abi.encodePacked("only module ", _module.toString()," can call this function")); require(msg.sender == getModule(_module), message); _; } /** * @dev Used when multiple can call. **/ modifier onlyModules(bytes32 _moduleOne, bytes32 _moduleTwo) { string memory message = string(abi.encodePacked("only module ", _moduleOne.toString()," or ", _moduleTwo.toString()," can call this function")); require(msg.sender == getModule(_moduleOne) || msg.sender == getModule(_moduleTwo), message); _; } function initializeModule(address _armorMaster) internal { require(address(_master) == address(0), "already initialized"); require(_armorMaster != address(0), "master cannot be zero address"); _master = IArmorMaster(_armorMaster); } function changeMaster(address _newMaster) external onlyOwner { _master = IArmorMaster(_newMaster); } function getModule(bytes32 _key) internal view returns(address) { return _master.getModule(_key); } } // File contracts/libraries/SafeMath.sol pragma solidity ^0.6.6; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error * * @dev Default OpenZeppelin */ 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; } } // File contracts/libraries/MerkleProof.sol pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { function calculateRoot(bytes32[] memory leaves) internal pure returns(bytes32) { require(leaves.length > 0, "Cannot compute zero length"); bytes32[] memory elements = leaves; bytes32[] memory nextLayer = new bytes32[]((elements.length+1)/2) ; while(elements.length > 1) { for(uint256 i = 0; i<elements.length;i+=2){ bytes32 left; bytes32 right; if(i == elements.length - 1){ left = elements[i]; right = elements[i]; } else if(elements[i] <= elements[i+1]){ left = elements[i]; right = elements[i+1]; } else { left = elements[i+1]; right = elements[i]; } bytes32 elem = keccak256(abi.encodePacked(left,right)); nextLayer[i/2] = elem; } elements = nextLayer; nextLayer = new bytes32[]((elements.length+1)/2); } return elements[0]; } /** * @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; } } // File contracts/interfaces/IStakeManager.sol pragma solidity ^0.6.6; interface IStakeManager { function totalStakedAmount(address protocol) external view returns(uint256); function protocolAddress(uint64 id) external view returns(address); function protocolId(address protocol) external view returns(uint64); function initialize(address _armorMaster) external; function allowedCover(address _newProtocol, uint256 _newTotalCover) external view returns (bool); function subtractTotal(uint256 _nftId, address _protocol, uint256 _subtractAmount) external; } // File contracts/interfaces/IBalanceManager.sol pragma solidity ^0.6.6; interface IBalanceManager { event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Loss(address indexed user, uint256 amount); event PriceChange(address indexed user, uint256 price); event AffiliatePaid(address indexed affiliate, address indexed referral, uint256 amount, uint256 timestamp); event ReferralAdded(address indexed affiliate, address indexed referral, uint256 timestamp); function expireBalance(address _user) external; function deposit(address _referrer) external payable; function withdraw(uint256 _amount) external; function initialize(address _armormaster, address _devWallet) external; function balanceOf(address _user) external view returns (uint256); function perSecondPrice(address _user) external view returns(uint256); function changePrice(address user, uint64 _newPricePerSec) external; } // File contracts/interfaces/IPlanManager.sol pragma solidity ^0.6.6; interface IPlanManager { // Mapping = protocol => cover amount struct Plan { uint64 startTime; uint64 endTime; uint128 length; } struct ProtocolPlan { uint64 protocolId; uint192 amount; } // Event to notify frontend of plan update. event PlanUpdate(address indexed user, address[] protocols, uint256[] amounts, uint256 endTime); function userCoverageLimit(address _user, address _protocol) external view returns(uint256); function markup() external view returns(uint256); function nftCoverPrice(address _protocol) external view returns(uint256); function initialize(address _armorManager) external; function changePrice(address _scAddress, uint256 _pricePerAmount) external; function updatePlan(address[] calldata _protocols, uint256[] calldata _coverAmounts) external; function checkCoverage(address _user, address _protocol, uint256 _hacktime, uint256 _amount) external view returns (uint256, bool); function coverageLeft(address _protocol) external view returns(uint256); function getCurrentPlan(address _user) external view returns(uint256 idx, uint128 start, uint128 end); function updateExpireTime(address _user, uint256 _expiry) external; function planRedeemed(address _user, uint256 _planIndex, address _protocol) external; function totalUsedCover(address _scAddress) external view returns (uint256); } // File contracts/interfaces/IRewardManagerV2.sol pragma solidity ^0.6.6; interface IRewardManagerV2 { function initialize(address _armorMaster, uint256 _rewardCycleBlocks) external; function deposit( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external; function withdraw( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external; function updateAllocPoint(address _protocol, uint256 _allocPoint) external; function initPool(address _protocol) external; function notifyRewardAmount() external payable; } // File contracts/interfaces/IClaimManager.sol pragma solidity ^0.6.6; interface IClaimManager { function initialize(address _armorMaster) external; function transferNft(address _to, uint256 _nftId) external; function exchangeWithdrawal(uint256 _amount) external; function redeemClaim(address _protocol, uint256 _hackTime, uint256 _amount) external; } // File contracts/core/PlanManager.sol // SPDX-License-Identifier: (c) Armor.Fi DAO, 2021 pragma solidity ^0.6.6; contract PlanManager is ArmorModule, IPlanManager { using SafeMath for uint; uint256 constant private DENOMINATOR = 1000; // List of plans that a user has purchased so there is a historical record. mapping (address => Plan[]) public plans; // keccak256("ARMORFI.PLAN", address(user), uint256(planIdx), uint256(protocolIdx)) => ProtocolPlan mapping (bytes32 => ProtocolPlan) public protocolPlan; // StakeManager calls this when a new NFT is added to update what the price for that protocol is. // Cover price in ETH (1e18) of price per second per ETH covered. mapping (address => uint256) public override nftCoverPrice; // Mapping to doKeep track of how much coverage we've sold for each protocol. // smart contract address => total borrowed cover mapping (address => uint256) public override totalUsedCover; // Protocol => amount of coverage bought by shields (then shields plus) for that protocol. // Keep track of these to only allow a % of staked NFTs to be bought by each. mapping (address => uint256) public arShieldCover; mapping (address => uint256) public arShieldPlusCover; mapping (address => uint256) public coreCover; // Percent allocated to each part of the system. 350 == 35%. uint256 public arShieldPercent; uint256 public arShieldPlusPercent; uint256 public corePercent; // Mapping of the address of shields => 1 if they're arShield and 2 if they're arShieldPlus. mapping (address => uint256) public arShields; // The amount of markup for Armor's service vs. the original cover cost. 200 == 200%. uint256 public override markup; modifier checkExpiry(address _user) { IBalanceManager balanceManager = IBalanceManager(getModule("BALANCE")); if(balanceManager.balanceOf(_user) == 0 ){ balanceManager.expireBalance(_user); } _; } function initialize( address _armorMaster ) external override { initializeModule(_armorMaster); markup = 150; arShieldPercent = 350; arShieldPlusPercent = 350; corePercent = 300; } function getCurrentPlan(address _user) external view override returns(uint256 idx, uint128 start, uint128 end){ if(plans[_user].length == 0){ return(0,0,0); } Plan memory plan = plans[_user][plans[_user].length-1]; //return 0 if there is no active plan if(plan.endTime < now){ return(0,0,0); } else { idx = plans[_user].length - 1; start = plan.startTime; end = plan.endTime; } } function getProtocolPlan(address _user, uint256 _idx, address _protocol) external view returns(uint256 idx, uint64 protocolId, uint192 amount) { IStakeManager stakeManager = IStakeManager(getModule("STAKE")); uint256 length = plans[_user][_idx].length; for(uint256 i = 0; i<length; i++){ ProtocolPlan memory protocol = protocolPlan[_hashKey(_user, _idx, i)]; address addr = stakeManager.protocolAddress(protocol.protocolId); if(addr == _protocol){ return (i, protocol.protocolId, protocol.amount); } } return(0,0,0); } function userCoverageLimit(address _user, address _protocol) external view override returns(uint256){ IStakeManager stakeManager = IStakeManager(getModule("STAKE")); uint64 protocolId = stakeManager.protocolId(_protocol); uint256 idx = plans[_user].length - 1; uint256 currentCover = 0; if(idx != uint256(-1)){ Plan memory plan = plans[_user][idx]; uint256 length = uint256( plan.length ); for (uint256 i = 0; i < length; i++) { ProtocolPlan memory protocol = protocolPlan[ _hashKey(_user, idx, i) ]; if (protocol.protocolId == protocolId) currentCover = uint256( protocol.amount ); } } uint256 extraCover = coverageLeft(_protocol); // Add current coverage because coverageLeft on planManager does not include what we're currently using. return extraCover.add(currentCover); } /* * @dev User can update their plan for cover amount on any protocol. * @param _protocols Addresses of the protocols that we want coverage for. * @param _coverAmounts The amount of coverage desired in WEI. * @notice Let's simplify this somehow--even just splitting into different functions. **/ function updatePlan(address[] calldata _protocols, uint256[] calldata _coverAmounts) external override checkExpiry(msg.sender) // doKeep { require(_protocols.length == _coverAmounts.length, "protocol and coverAmount length mismatch"); require(_protocols.length <= 30, "You may not protect more than 30 protocols at once."); IBalanceManager balanceManager = IBalanceManager(getModule("BALANCE")); // Need to get price of the protocol here if(plans[msg.sender].length > 0){ Plan storage lastPlan = plans[msg.sender][plans[msg.sender].length - 1]; // this should happen only when plan is not expired yet if(lastPlan.endTime > now) { // First go through and subtract all old cover amounts. _removeLatestTotals(msg.sender); lastPlan.endTime = uint64(now); } } _addNewTotals(_protocols, _coverAmounts); uint256 newPricePerSec; uint256 _markup = markup; // Loop through protocols, find price per second, add to rate, add coverage amount to mapping. for (uint256 i = 0; i < _protocols.length; i++) { require(nftCoverPrice[_protocols[i]] != 0, "Protocol price is zero"); // nftCoverPrice is Wei per second per full Ether, so a cover amont in Wei. This is divided after this loop. uint256 pricePerSec = nftCoverPrice[ _protocols[i] ].mul(_coverAmounts[i]); newPricePerSec = newPricePerSec.add(pricePerSec); } //newPricePerSec = newPricePerSec * _markup / 1e18 for decimals / 100 to make up for markup (200 == 200%); newPricePerSec = newPricePerSec.mul(_markup).div(1e18).div(100); // this means user is canceling all plans if(newPricePerSec == 0){ Plan memory newPlan; newPlan = Plan(uint64(now), uint64(-1), uint128(0)); plans[msg.sender].push(newPlan); balanceManager.changePrice(msg.sender, 0); emit PlanUpdate(msg.sender, _protocols, _coverAmounts, uint64(-1)); return; } uint256 endTime = balanceManager.balanceOf(msg.sender).div(newPricePerSec).add(block.timestamp); // Let's make sure a user can pay for this for at least a week. Weird manipulation of utilization farming could happen otherwise. require(endTime >= block.timestamp.add(7 days), "Balance must be enough for 7 days of coverage."); //add plan Plan memory newPlan; newPlan = Plan(uint64(now), uint64(endTime), uint128(_protocols.length)); plans[msg.sender].push(newPlan); //add protocol plan for(uint256 i = 0;i<_protocols.length; i++){ bytes32 key = _hashKey(msg.sender, plans[msg.sender].length - 1, i); uint64 protocolId = IStakeManager(getModule("STAKE")).protocolId(_protocols[i]); protocolPlan[key] = ProtocolPlan(protocolId, uint192(_coverAmounts[i])); } // update balance price per second here uint64 castPricePerSec = uint64(newPricePerSec); require(uint256(castPricePerSec) == newPricePerSec); IBalanceManager(getModule("BALANCE")).changePrice(msg.sender, castPricePerSec); emit PlanUpdate(msg.sender, _protocols, _coverAmounts, endTime); } /** * @dev Update the contract-wide totals for each protocol that has changed. * @param _user User whose plan is updating these totals. **/ function _removeLatestTotals(address _user) internal { Plan storage plan = plans[_user][plans[_user].length - 1]; uint256 idx = plans[_user].length - 1; IRewardManagerV2 rewardManager = IRewardManagerV2(getModule("REWARDV2")); for (uint256 i = 0; i < plan.length; i++) { bytes32 key = _hashKey(_user, idx, i); ProtocolPlan memory protocol = protocolPlan[key]; address protocolAddress = IStakeManager(getModule("STAKE")).protocolAddress(protocol.protocolId); totalUsedCover[protocolAddress] = totalUsedCover[protocolAddress].sub(uint256(protocol.amount)); rewardManager.updateAllocPoint(protocolAddress, totalUsedCover[protocolAddress]); uint256 shield = arShields[_user]; if (shield == 1) { arShieldCover[protocolAddress] = arShieldCover[protocolAddress].sub(protocol.amount); } else if (shield == 2) { arShieldPlusCover[protocolAddress] = arShieldPlusCover[protocolAddress].sub(protocol.amount); } else { coreCover[protocolAddress] = coreCover[protocolAddress].sub(protocol.amount); } } } /** * @dev Add new totals for new protocol/cover amounts. * @param _newProtocols Protocols that are being borrowed for. * @param _newCoverAmounts Cover amounts (in Wei) that are being borrowed. **/ function _addNewTotals(address[] memory _newProtocols, uint256[] memory _newCoverAmounts) internal { IRewardManagerV2 rewardManager = IRewardManagerV2(getModule("REWARDV2")); for (uint256 i = 0; i < _newProtocols.length; i++) { (uint256 shield, uint256 allowed) = _checkBuyerAllowed(_newProtocols[i]); require(allowed >= _newCoverAmounts[i], "Exceeds allowed cover amount."); totalUsedCover[_newProtocols[i]] = totalUsedCover[_newProtocols[i]].add(_newCoverAmounts[i]); rewardManager.updateAllocPoint(_newProtocols[i], totalUsedCover[_newProtocols[i]]); if (shield == 1) { arShieldCover[_newProtocols[i]] = arShieldCover[_newProtocols[i]].add(_newCoverAmounts[i]); } else if (shield == 2) { arShieldPlusCover[_newProtocols[i]] = arShieldPlusCover[_newProtocols[i]].add(_newCoverAmounts[i]); } else { coreCover[_newProtocols[i]] = coreCover[_newProtocols[i]].add(_newCoverAmounts[i]); } } } /** * @dev Determine the amount of coverage left for a specific protocol. * @param _protocol The address of the protocol we're determining coverage left for. **/ function coverageLeft(address _protocol) public override view returns (uint256) { (/* uint256 shield */, uint256 allowed) = _checkBuyerAllowed(_protocol); return allowed; } /** * @dev Check whether the buyer is allowed to purchase this amount of cover. * Used because core can only buy 30%, and 35% for shields. * @param _protocol The protocol cover is being purchased for. **/ function _checkBuyerAllowed(address _protocol) internal view returns (uint256, uint256) { uint256 totalAllowed = IStakeManager(getModule("STAKE")).totalStakedAmount(_protocol); uint256 shield = arShields[msg.sender]; if (shield == 1) { uint256 currentCover = arShieldCover[_protocol]; uint256 allowed = totalAllowed * arShieldPercent / DENOMINATOR; return (shield, allowed > currentCover ? allowed - currentCover : 0); } else if (shield == 2) { uint256 currentCover = arShieldPlusCover[_protocol]; uint256 allowed = totalAllowed * arShieldPlusPercent / DENOMINATOR; return (shield, allowed > currentCover ? allowed - currentCover : 0); } else { uint256 currentCover = coreCover[_protocol]; uint256 allowed = totalAllowed * corePercent / DENOMINATOR; return (shield, allowed > currentCover ? allowed - currentCover : 0); } } /** * @dev Used by ClaimManager to check how much coverage the user had at the time of a hack. * @param _user The user to check coverage for. * @param _protocol The address of the protocol that was hacked. (Address used according to arNFT). * @param _hackTime The timestamp of when a hack happened. * @return index index of plan for hackTime * @return check whether amount is allowed **/ function checkCoverage(address _user, address _protocol, uint256 _hackTime, uint256 _amount) external view override returns(uint256 index, bool check) { // This may be more gas efficient if we don't grab this first but instead grab each plan from storage individually? Plan[] storage planArray = plans[_user]; // In normal operation, this for loop should never get too big. // If it does (from malicious action), the user will be the only one to suffer. for (int256 i = int256(planArray.length - 1); i >= 0; i--) { Plan storage plan = planArray[uint256(i)]; // Only one plan will be active at the time of a hack--return cover amount from then. if (_hackTime >= plan.startTime && _hackTime < plan.endTime) { for(uint256 j = 0; j< plan.length; j++){ bytes32 key = _hashKey(_user, uint256(i), j); if(IStakeManager(getModule("STAKE")).protocolAddress(protocolPlan[key].protocolId) == _protocol){ return (uint256(i), _amount <= uint256(protocolPlan[key].amount)); } } return (uint256(i), false); } } return (uint256(-1), false); } /** * @dev ClaimManager redeems the plan if it has been claimed. Sets claim amount to 0 so it cannot be claimed again. * @param _user User that is redeeming this plan. * @param _planIndex The index in the user's Plan array that we're checking. * @param _protocol Address of the protocol that a claim is being redeemed for. **/ function planRedeemed(address _user, uint256 _planIndex, address _protocol) external override onlyModule("CLAIM") { Plan storage plan = plans[_user][_planIndex]; require(plan.endTime <= now, "Cannot redeem active plan, update plan to redeem properly."); for (uint256 i = 0; i < plan.length; i++) { bytes32 key = _hashKey(_user,_planIndex,i); ProtocolPlan memory protocol = protocolPlan[key]; address protocolAddress = IStakeManager(getModule("STAKE")).protocolAddress(protocol.protocolId); if (protocolAddress == _protocol) protocolPlan[key].amount = 0; } } /** * @dev Armor has the ability to change the price that a user is paying for their insurance. * @param _protocol The protocol whose arNFT price is being updated. * @param _newPrice the new price PER SECOND that the user will be paying. **/ function changePrice(address _protocol, uint256 _newPrice) external override onlyModule("STAKE") { nftCoverPrice[_protocol] = _newPrice; } /** * @dev BalanceManager calls to update expire time of a plan when a deposit/withdrawal happens. * @param _user Address whose balance was updated. * @param _expiry New time plans expire. **/ function updateExpireTime(address _user, uint256 _expiry) external override onlyModule("BALANCE") { if (plans[_user].length == 0) return; Plan storage plan = plans[_user][plans[_user].length-1]; if (_expiry <= block.timestamp) _removeLatestTotals(_user); plan.endTime = uint64(_expiry); } /** * @dev Hash for protocol info identifier. * @param _user Address of the user. * @param _planIndex Index of the plan in the user's plan array. * @param _protoIndex Index of the protocol in the plan. * @return Hash for identifier for protocolPlan mapping. **/ function _hashKey(address _user, uint256 _planIndex, uint256 _protoIndex) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ARMORFI.PLAN.", _user, _planIndex, _protoIndex)); } /** * @dev Owner (DAO) can adjust the markup buyers pay for coverage. * @param _newMarkup The new markup that will be used. 100 == 100% (no markup). **/ function adjustMarkup(uint256 _newMarkup) external onlyOwner { require(_newMarkup >= 100, "Markup must be at least 0 (100%)."); markup = _newMarkup; } /** * @dev Owner (DAO) can adjust the percent of coverage allowed for each product. * @param _newCorePercent New percent of coverage for general arCore users. * @param _newArShieldPercent New percent of coverage for arShields. * @param _newArShieldPlusPercent New percent of coverage for arShield Plus. **/ function adjustPercents(uint256 _newCorePercent, uint256 _newArShieldPercent, uint256 _newArShieldPlusPercent) external onlyOwner { require(_newCorePercent + _newArShieldPercent + _newArShieldPlusPercent == 1000, "Total allocation cannot be more than 100%."); corePercent = _newCorePercent; arShieldPercent = _newArShieldPercent; arShieldPlusPercent = _newArShieldPlusPercent; } /** * @dev Owner (DAO) can adjust shields on the contract. * @param _shieldAddress Array of addresses we're adjusting. * @param _shieldType Type of shield: 1 for arShield, 2 for arShield Plus. **/ function adjustShields(address[] calldata _shieldAddress, uint256[] calldata _shieldType) external onlyOwner { require(_shieldAddress.length == _shieldType.length, "Submitted arrays are not of equal length."); for (uint256 i = 0; i < _shieldAddress.length; i++) { arShields[_shieldAddress[i]] = _shieldType[i]; } } function forceAdjustTotalUsedCover(address[] calldata _protocols, uint256[] calldata _usedCovers) external onlyOwner { IRewardManagerV2 rewardManager = IRewardManagerV2(getModule("REWARDV2")); for(uint256 i = 0; i<_protocols.length; i++){ totalUsedCover[_protocols[i]] = _usedCovers[i]; coreCover[_protocols[i]] = _usedCovers[i]; rewardManager.updateAllocPoint(_protocols[i], totalUsedCover[_protocols[i]]); } } }
Add new totals for new protocol/cover amounts. _newProtocols Protocols that are being borrowed for. _newCoverAmounts Cover amounts (in Wei) that are being borrowed./
function _addNewTotals(address[] memory _newProtocols, uint256[] memory _newCoverAmounts) internal { IRewardManagerV2 rewardManager = IRewardManagerV2(getModule("REWARDV2")); for (uint256 i = 0; i < _newProtocols.length; i++) { (uint256 shield, uint256 allowed) = _checkBuyerAllowed(_newProtocols[i]); require(allowed >= _newCoverAmounts[i], "Exceeds allowed cover amount."); totalUsedCover[_newProtocols[i]] = totalUsedCover[_newProtocols[i]].add(_newCoverAmounts[i]); rewardManager.updateAllocPoint(_newProtocols[i], totalUsedCover[_newProtocols[i]]); if (shield == 1) { arShieldCover[_newProtocols[i]] = arShieldCover[_newProtocols[i]].add(_newCoverAmounts[i]); arShieldPlusCover[_newProtocols[i]] = arShieldPlusCover[_newProtocols[i]].add(_newCoverAmounts[i]); coreCover[_newProtocols[i]] = coreCover[_newProtocols[i]].add(_newCoverAmounts[i]); } } }
6,624,320
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "base64-sol/base64.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./IAchievement.sol"; import "./AchievementModel.sol"; import "hardhat/console.sol"; /** * @title Achievement * @author @StErMi * @notice A general purpose Achievement System for the FTM ecosystem */ contract Achievement is ERC721Enumerable { using Strings for uint256; using Counters for Counters.Counter; /// @notice Metadata ID tracker Counters.Counter private _metadataId; /// @notice Achievement ID tracker Counters.Counter private _achievementId; /// @notice Registered achievement metadats from contracts mapping(uint256 => AchievementModel.Metadata) private metadatas; /// @notice List of achievements awarded to a user mapping(address => AchievementModel.Achievement[]) private userAchievements; /// @notice NFT ID -> Achievement tracker mapping(uint256 => AchievementModel.Achievement) private achievements; /// @notice Fast check ownership of an achievement metadata mapping(address => mapping(uint256 => bool)) private _ownerships; /// @notice event emitted when an achievement is awarded to a user event AchievementAwarded( address indexed receiver, uint256 indexed tokenId, uint256 indexed metadataId, address source, string sourceName, AchievementModel.Rarity rarity, string title, uint256 points, uint256 timestamp ); /// @notice event emitted when an achievement metadata is registered by a contract event AchievementRegistered( address indexed source, uint256 indexed metadataId, string sourceName, AchievementModel.Rarity rarity, string title, uint256 points ); /// @notice Constructor constructor() ERC721("FTM Achievement", "FTMACK") {} /** * @notice Function used by external contract to register achievement metadata * @param metadata Metadata of the achievement * @return metadataId The ID of the registered achievement metadata */ function registerAchievement(AchievementModel.Metadata memory metadata) external returns (uint256 metadataId) { checkMetadata(metadata); _metadataId.increment(); metadata.source = msg.sender; metadata.id = _metadataId.current(); metadatas[metadata.id] = metadata; emit AchievementRegistered( metadata.source, metadata.id, metadata.sourceName, metadata.rarity, metadata.title, metadata.points ); return metadata.id; } /** * @notice Function used by external contract to award an achievement to a receiving wallet * @param receiver Address of the wallet that will receive the achievement * @param metadataId ID of the achievement metadata */ function awardAchievement(address receiver, uint256 metadataId) external returns (bool success, string memory failMessage) { AchievementModel.Metadata storage metadata = metadatas[metadataId]; if (metadata.source == address(0)) return (false, "Requested metadata not exist"); if (metadata.source != msg.sender) return (false, "You are not the owner of the metadata"); if (receiver == msg.sender) return (false, "Source can't award itself"); if (_ownerships[receiver][metadataId] == true) return (false, "Wallet already own the achievement"); // get the current achievement ID uint256 currentAchievementId = _achievementId.current(); // Add the ownership to the summoner _ownerships[receiver][metadataId] = true; // Add the achievement to the summoner's list uint256 timestamp = block.timestamp; // AchievementModel.Achievement storage achievement = AchievementModel.Achievement(metadataId, currentAchievementId, receiver, timestamp); userAchievements[receiver].push( AchievementModel.Achievement(metadataId, currentAchievementId, receiver, timestamp) ); achievements[currentAchievementId] = AchievementModel.Achievement( metadataId, currentAchievementId, receiver, timestamp ); emit AchievementAwarded( receiver, currentAchievementId, metadataId, metadata.source, metadata.sourceName, metadata.rarity, metadata.title, metadata.points, timestamp ); _safeMint(receiver, currentAchievementId); _achievementId.increment(); return (true, ""); } ///////////////////////// // External Utilities ///////////////////////// /** * @notice Get achievement metadata by providing a metadataId * @param metadataId ID of the achievement metadata * @return List of achievements */ function getMetadata(uint256 metadataId) external view returns (AchievementModel.Metadata memory) { return metadatas[metadataId]; } /** * @notice Get achievement expanded information by providing a achievementId * @param achievementId ID of the achievement * @return Data of the requested achievement */ function getAchievement(uint256 achievementId) external view returns (AchievementModel.AchievementExpanded memory) { AchievementModel.Achievement storage _achievement = achievements[achievementId]; AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId]; return AchievementModel.AchievementExpanded({ metadata: metadata, achievementId: achievementId, user: _achievement.user, timestamp: _achievement.timestamp }); } /** * @notice Check if a user has been awarded with an achievement * @param user Address of the user * @param metadataId Achievement Metadata ID * @return true if he already has the achievement */ function hasAchievement(address user, uint256 metadataId) external view returns (bool) { return _ownerships[user][metadataId]; } /** * @notice Get the total achievement points collected by the summoner * @param user Address of the user * @param sources List of whitelisted contracts to filter achievements with. Can be empty. * @return amount of achievement points */ function getPoints(address user, address[] memory sources) external view returns (uint256) { (, , uint256 points) = filterAchievements(user, sources); return points; } /** * @notice Get list of achievements owned by the summoner * @param user Address of the user * @param sources List of whitelisted contracts to filter achievements with. Can be empty. * @param offset Position from which start * @param limit Amount of achievements to return * @return List of achievements owned by the user */ function getAchievements( address user, address[] memory sources, uint256 offset, uint256 limit ) external view returns (AchievementModel.AchievementExpanded[] memory) { (AchievementModel.AchievementExpanded[] memory _tempList, uint256 maxWhitelistedLength, ) = filterAchievements( user, sources ); uint256 safeLimit = limit == 0 ? 2**32 - 1 : limit; if (safeLimit > maxWhitelistedLength) { require(maxWhitelistedLength >= offset, "Offset is greater than number of records available"); } uint256 maxLen = safeLimit > maxWhitelistedLength ? maxWhitelistedLength - offset : safeLimit; AchievementModel.AchievementExpanded[] memory _achievements = new AchievementModel.AchievementExpanded[]( maxLen ); for (uint256 i = 0; i < maxLen; i++) { _achievements[i] = _tempList[offset + i]; } return _achievements; } ///////////////////////// // Internal Utilities ///////////////////////// /** * @dev Filter summoner's achievement by the list of whitelisted sources */ function filterAchievements(address user, address[] memory sources) internal view returns ( AchievementModel.AchievementExpanded[] memory, uint256, uint256 ) { // Get the correct length uint256 achievementCount = userAchievements[user].length; uint256 points = 0; AchievementModel.AchievementExpanded[] memory _tempList = new AchievementModel.AchievementExpanded[]( achievementCount ); uint256 maxWhitelistedLength = 0; for (uint256 i = 0; i < achievementCount; i++) { AchievementModel.Achievement storage _achievement = userAchievements[user][i]; AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId]; bool whitelisted = false; if (sources.length > 0) { for (uint256 j = 0; j < sources.length; j++) { if (metadata.source == sources[j]) { whitelisted = true; break; } } if (whitelisted == false) { // skip this achivement continue; } } points += metadata.points; AchievementModel.AchievementExpanded memory achievement = AchievementModel.AchievementExpanded({ metadata: metadata, achievementId: _achievement.achievementId, user: _achievement.user, timestamp: _achievement.timestamp }); _tempList[maxWhitelistedLength] = achievement; maxWhitelistedLength++; } return (_tempList, maxWhitelistedLength, points); } /** * @dev Check the integrity of a achievement metadata */ function checkMetadata(AchievementModel.Metadata memory _metadata) internal pure { require( _metadata.rarity >= AchievementModel.Rarity.Common && _metadata.rarity <= AchievementModel.Rarity.Legendary, "Invalid rarity" ); require(bytes(_metadata.sourceName).length > 0, "Source Name must not be empty"); require(bytes(_metadata.title).length > 0, "Title must not be empty"); require(bytes(_metadata.description).length > 0, "Description must not be empty"); require(_metadata.points > 0, "Points must be greater than 0"); } ///////////////////////// // ERC721 overrides ///////////////////////// /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "token does not exist"); AchievementModel.Achievement storage _achievement = achievements[tokenId]; AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId]; string[11] memory parts; parts[ 0 ] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = string(abi.encodePacked("Source: ", metadata.sourceName)); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = string(abi.encodePacked("Title: ", metadata.title)); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = string(abi.encodePacked("Description: ", metadata.description)); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = string(abi.encodePacked("Rarity: ", uint256(metadata.rarity).toString())); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = string(abi.encodePacked("Points: ", metadata.points.toString())); parts[10] = "</text></svg>"; string memory output = string( abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]) ); output = string(abi.encodePacked(output, parts[9], parts[10])); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "Archievement #', tokenId.toString(), '", "description": "FTM Achievement to track user achievements and engagement with the platform", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}' ) ) ) ); output = string(abi.encodePacked("data:application/json;base64,", json)); return output; } /** * @dev Hook that is called before any token transfer. Check if the user has the NFT locked */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Enumerable) { // Archievement can be minted but it cannot be transferred to other users, it's soulbound to the person require(from == address(0), "The Archievement NFT is soul bound to the user"); super._beforeTokenTransfer(from, to, tokenId); } }
Get achievement expanded information by providing a achievementId achievementId ID of the achievement return Data of the requested achievement/
function getAchievement(uint256 achievementId) external view returns (AchievementModel.AchievementExpanded memory) { AchievementModel.Achievement storage _achievement = achievements[achievementId]; AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId]; return AchievementModel.AchievementExpanded({ metadata: metadata, achievementId: achievementId, user: _achievement.user, timestamp: _achievement.timestamp }); }
6,436,318
./full_match/8453/0x2499D94880B30fA505543550ac8a1e24cfFeFe78/sources/contracts/past-versions/UnlockV12.sol
Create upgradeable lock This deploys a lock for a creator. It also keeps track of the deployed lock. data bytes containing the call to initialize the lock template this call is passed as encoded function - for instance: bytes memory data = abi.encodeWithSignature( 'initialize(address,uint256,address,uint256,uint256,string)', msg.sender, _expirationDuration, _tokenAddress, _keyPrice, _maxNumberOfKeys, _lockName ); return address of the create lock/
function createUpgradeableLock(bytes memory data) public returns (address) { address newLock = createUpgradeableLockAtVersion( data, publicLockLatestVersion ); return newLock; }
11,554,770
./partial_match/1/0x9460b380c57F65e8AFc4bA3518F643A526640F26/sources/contracts/dependencies/uniswapv3-core/UniswapV3Pool.sol
@inheritdoc IUniswapV3PoolOwnerActions
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner { unchecked { require( (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) && (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10)) ); uint8 feeProtocolOld = slot0.feeProtocol; slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4); emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1); } }
4,203,131
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title The ChessCryptos contract. * @author Manuel Liebchen */ contract ChessCryptos is ERC721, Ownable, PaymentSplitter, IERC721Enumerable { using Address for address; using Strings for uint256; event MintPriceIncrement(uint256 newPrice); /// The total number of token. uint256 public constant TOTAL_SUPPLY = 4716; /// The number of token that will be created for the creators when deploying the contract. uint256 public constant GALLERY_TOKEN = 100; /// The increment with witch the price will grow. uint256 public constant PRICE_INCREMENT = 0.04 ether; /// The number of token one pricesegment. uint256 public constant PRICESEGMENT_RANGE = 1000; /// The metadata ipfs file uri. string public baseURI; /** @dev The current minting price. */ uint256 _mintPrice = 0.02 ether; /** @dev When the next price range will begin.*/ uint256 _nextPriceIncrement = 600; /** @dev A number that is used for production of the pseudorandom mint sequence.*/ uint256 private _indexIncrement; /** @dev The index of the token that will be created next.*/ uint256 private _mintIndex; // ERC 165 mapping(bytes4 => bool) internal supportedInterfaces; // Array with all token ids, used for enumeration uint256[] private _allTokens; /** * */ constructor(string memory baseURI_, address[] memory payees, uint256[] memory shares, uint256 indexIncrement_) ERC721("ChessCryptos", "CC") PaymentSplitter(payees, shares) { require(payees[0] == _msgSender(), "Sender/Owner is not first shareholder."); baseURI = baseURI_; _indexIncrement = indexIncrement_; supportedInterfaces[0x01ffc9a7] = true; // ERC165 supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x780e9d63] = true; // ERC721 Enumerable supportedInterfaces[0x5b5e139f] = true; // ERC721 Metadata } function mintGallery() external onlyOwner { require(totalSupply() < GALLERY_TOKEN, "Only once."); for(uint256 i = 0; i < GALLERY_TOKEN; ++i){ _mint(_msgSender(), _mintIndex); _mintIndex = (_mintIndex + _indexIncrement) % TOTAL_SUPPLY; } } /** * @dev Creates a new token for _msgSender. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * */ function mint() external payable returns (uint256) { require(totalSupply() < TOTAL_SUPPLY, "There are no token left to mint."); require(GALLERY_TOKEN <= totalSupply(), "Gallery Token haven't been minted."); require(msg.value == _mintPrice, "Value is not equal to mint price."); uint256 newItemId = _mintIndex; _mintIndex = (_mintIndex + _indexIncrement) % TOTAL_SUPPLY; if(totalSupply() >= _nextPriceIncrement){ _mintPrice += PRICE_INCREMENT; _nextPriceIncrement += PRICESEGMENT_RANGE; emit MintPriceIncrement(_mintPrice); } _safeMint(_msgSender(), newItemId); return newItemId; } /** * @dev The number of token that can still be created. */ function remainingToken() public view returns(uint256){ return TOTAL_SUPPLY - totalSupply(); } /** * @dev The number of token that can still be created at this fee. */ function remainingTokenAtFee() public view returns(uint256){ return _nextPriceIncrement - totalSupply(); } /** * @dev The value mint expects for a token. */ function mintPrice() external view returns(uint256) { return _mintPrice; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function maximumToken() public pure virtual returns (uint256) { return TOTAL_SUPPLY; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @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 override returns (uint256 tokenId){ require(index < balanceOf(owner)); uint256 count = 0; for(uint256 i = 0; i < totalSupply(); i++){ if(ownerOf(_allTokens[i]) == owner){ if(count == index){ return _allTokens[i]; } count++; } } } /** * @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)) { _allTokens.push(tokenId); } } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view override returns(string memory) { return baseURI; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function ipfsRoot() external view returns(string memory) { return baseURI; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(tokenId < TOTAL_SUPPLY, "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI, "/", tokenId.toString(), "/meta.json")); } function contractURI() public view returns (string memory) { return string(abi.encodePacked(baseURI, "/meta.json")); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceID) public view override( ERC721, IERC165) returns (bool) { return supportedInterfaces[interfaceID]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.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}. 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 || 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 _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 || ERC721.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 { // solhint-disable-next-line no-inline-assembly 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` 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 { } } // 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 "../utils/Address.sol"; import "../utils/Context.sol"; import "../utils/math/SafeMath.sol"; /** * @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. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(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; /** * @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 { // solhint-disable-next-line max-line-length 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 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 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 = totalReceived * _shares[account] / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @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_); } } // 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 () { 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.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; // 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.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) { 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.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[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; // 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. 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) { 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; } } }
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.adocusing-hooks[Using Hooks]./
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _allTokens.push(tokenId); } }
11,904,538
./full_match/4/0x8BA68Fe0Bc728c4c3B4D8BEe3E66f72a96c1750d/sources/Users/alpha/Desktop/Coding_Projects/Active_Contractor_projects/0geyser/0geyser_truffle/contracts/TokenGeyser.sol
return The current multiplier coefficient for user [1, 2]./
function getMultiplier() public view returns (uint256) { uint256 numerator = 0; for (uint256 i = 0; i < _userStakes[msg.sender].length; i++) { numerator += _userStakes[msg.sender][i].stakingShares.mul(block.timestamp.sub(_userStakes[msg.sender][i].timestampSec)); } if (numerator == 0) return 0; uint256 denom = _userTotals[msg.sender].stakingShares.mul(bonusPeriodSec); if (numerator <= denom) return 1 + numerator.div(denom); return 2; }
656,151
pragma solidity ^0.5.13; import "openzeppelin-solidity/contracts/math/Math.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/IElection.sol"; import "./interfaces/IValidators.sol"; import "../common/CalledByVm.sol"; import "../common/Initializable.sol"; import "../common/FixidityLib.sol"; import "../common/linkedlists/AddressSortedLinkedList.sol"; import "../common/UsingPrecompiles.sol"; import "../common/UsingRegistry.sol"; import "../common/interfaces/IMapVersionedContract.sol"; import "../common/libraries/Heap.sol"; import "../common/libraries/ReentrancyGuard.sol"; contract Election is IElection, IMapVersionedContract, Ownable, ReentrancyGuard, Initializable, UsingRegistry, UsingPrecompiles, CalledByVm { using AddressSortedLinkedList for SortedLinkedList.List; using FixidityLib for FixidityLib.Fraction; using SafeMath for uint256; // 1e20 ensures that units can be represented as precisely as possible to avoid rounding errors // when translating to votes, without risking integer overflow. // A maximum of 1,000,000,000 MAP (1e27) yields a maximum of 1e47 units, whose product is at // most 1e74, which is less than 2^256. uint256 private constant UNIT_PRECISION_FACTOR = 100000000000000000000; struct PendingVote { // The value of the vote, in gold. uint256 value; // The epoch at which the vote was cast. uint256 epoch; } struct ValidatorPendingVotes { // The total number of pending votes that have been cast for this validator. uint256 total; // Pending votes cast per voter. mapping(address => PendingVote) byAccount; address[] voters; } // Pending votes are those for which no following elections have been held. // These votes have yet to contribute to the election of validators and thus do not accrue // rewards. struct PendingVotes { // The total number of pending votes cast across all validators. uint256 total; mapping(address => ValidatorPendingVotes) forValidator; } // validator info struct ValidatorActiveVotes { // The total number of active votes that have been cast for this validator. uint256 total; // The total number of active votes by a voter is equal to the number of active vote units for // that voter times the total number of active votes divided by the total number of active // vote units. uint256 totalUnits; mapping(address => uint256) unitsByAccount; //voter => value } // Active votes are those for which at least one following election has been held. // These votes have contributed to the election of validators and thus accrue rewards. struct ActiveVotes { // The total number of active votes cast across all validators. uint256 total; mapping(address => ValidatorActiveVotes) forValidator; // validator => voters } struct TotalVotes { // A list of eligible Validators sorted by total (pending+active) votes. // Note that this list will omit ineligible Validators, including those that may have > 0 // total votes. SortedLinkedList.List eligible; } struct Votes { //pending and active can distinguish between before and after reward PendingVotes pending; //validator => voters pending ActiveVotes active; //validator => voters active TotalVotes total; //sort validators // Maps an account to the list of validators it's voting for. mapping(address => address[]) validatorsVotedFor; // voter => validators } struct ElectableValidators { uint256 min; uint256 max; } Votes private votes; // Governs the minimum and maximum number of validators that can be elected. ElectableValidators public electableValidators; // Governs how many validator validators a single account can vote for. uint256 public maxNumValidatorsVotedFor; // Validators must receive at least this fraction of the total votes in order to be considered in // elections. FixidityLib.Fraction public electabilityThreshold; event ElectableValidatorsSet(uint256 min, uint256 max); event MaxNumValidatorsVotedForSet(uint256 maxNumValidatorsVotedFor); event ElectabilityThresholdSet(uint256 electabilityThreshold); event ValidatorMarkedEligible(address indexed validator); event ValidatorMarkedIneligible(address indexed validator); event ValidatorVoteCast(address indexed account, address indexed validator, uint256 value); event ValidatorVoteActivated( address indexed account, address indexed validator, uint256 value ); event ValidatorPendingVoteRevoked( address indexed account, address indexed validator, uint256 value ); event ValidatorActiveVoteRevoked( address indexed account, address indexed validator, uint256 value ); event EpochRewardRemainsDistributedToValidators(address indexed validator, uint256 value); event EpochRewardsDistributedToVoters(address indexed voterAddress, uint256 value); /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 1, 2, 1); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry core smart contract. * @param minElectableValidators The minimum number of validators that can be elected. * @param _maxNumValidatorsVotedFor The maximum number of validators that an account can vote for at once. * @param _electabilityThreshold The minimum ratio of votes a validator needs before its members can * be elected. * @dev Should be called only once. */ function initialize( address registryAddress, uint256 minElectableValidators, uint256 maxElectableValidators, uint256 _maxNumValidatorsVotedFor, uint256 _electabilityThreshold ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setElectableValidators(minElectableValidators, maxElectableValidators); setMaxNumValidatorsVotedFor(_maxNumValidatorsVotedFor); setElectabilityThreshold(_electabilityThreshold); } /** * @notice Sets initialized == true on implementation contracts * @param test Set to true to skip implementation initialization */ constructor(bool test) public Initializable(test) {} /** * @notice Updates the minimum and maximum number of validators that can be elected. * @param min The minimum number of validators that can be elected. * @param max The maximum number of validators that can be elected. * @return True upon success. */ function setElectableValidators(uint256 min, uint256 max) public onlyOwner returns (bool) { require(0 < min, "Minimum electable validators cannot be zero"); require(min <= max, "Maximum electable validators cannot be smaller than minimum"); require( min != electableValidators.min || max != electableValidators.max, "Electable validators not changed" ); electableValidators = ElectableValidators(min, max); emit ElectableValidatorsSet(min, max); return true; } /** * @notice Returns the minimum and maximum number of validators that can be elected. * @return The minimum and maximum number of validators that can be elected. */ function getElectableValidators() external view returns (uint256, uint256) { return (electableValidators.min, electableValidators.max); } /** * @notice Updates the maximum number of validators an account can be voting for at once. * @param _maxNumValidatorsVotedFor The maximum number of validators an account can vote for. * @return True upon success. */ function setMaxNumValidatorsVotedFor(uint256 _maxNumValidatorsVotedFor) public onlyOwner returns (bool) { require(_maxNumValidatorsVotedFor != maxNumValidatorsVotedFor, "Max validators voted for not changed"); maxNumValidatorsVotedFor = _maxNumValidatorsVotedFor; emit MaxNumValidatorsVotedForSet(_maxNumValidatorsVotedFor); return true; } /** * @notice Sets the electability threshold. * @param threshold Electability threshold as unwrapped Fraction. * @return True upon success. */ function setElectabilityThreshold(uint256 threshold) public onlyOwner returns (bool) { electabilityThreshold = FixidityLib.wrap(threshold); require( electabilityThreshold.lt(FixidityLib.fixed1()), "Electability threshold must be lower than 100%" ); emit ElectabilityThresholdSet(threshold); return true; } /** * @notice Gets the election threshold. * @return Threshold value as unwrapped fraction. */ function getElectabilityThreshold() external view returns (uint256) { return electabilityThreshold.unwrap(); } /** * @notice Increments the number of total and pending votes for `validator`. * @param validator The validator to vote for. * @param value The amount of gold to use to vote. * @param lesser The validator receiving fewer votes than `validator`, or 0 if `validator` has the * fewest votes of any validator. * @param greater The validator receiving more votes than `validator`, or 0 if `validator` has the * most votes of any validator. * @return True upon success. * @dev Fails if `validator` is empty or not a validator. */ function vote(address validator, uint256 value, address lesser, address greater) external nonReentrant returns (bool) { require(votes.total.eligible.contains(validator), "Validator not eligible"); require(0 < value, "Vote value cannot be zero"); // require(canReceiveVotes(validator, value), "Validator cannot receive votes"); address account = getAccounts().voteSignerToAccount(msg.sender); // Add validator to the validators voted for by the account. bool alreadyVotedForValidator = false; address[] storage validators = votes.validatorsVotedFor[account]; for (uint256 i = 0; i < validators.length; i = i.add(1)) { alreadyVotedForValidator = alreadyVotedForValidator || validators[i] == validator; } if (!alreadyVotedForValidator) { require(validators.length < maxNumValidatorsVotedFor, "Voted for too many validators"); validators.push(validator); } require(value <= getLockedGold().getAccountNonvotingLockedGold(account), "Nonvoting Locked Gold too low"); incrementPendingVotes(validator, account, value); incrementTotalVotes(validator, value, lesser, greater); getLockedGold().decrementNonvotingAccountBalance(account, value); emit ValidatorVoteCast(account, validator, value); return true; } /** * @notice Converts `account`'s pending votes for `validator` to active votes. * @param validator The voter to vote for. * @return True upon success. * @dev Pending votes cannot be activated until an election has been held. */ function activate(address validator) external nonReentrant returns (bool) { address account = getAccounts().voteSignerToAccount(msg.sender); return _activate(validator, account); } /** * @notice Converts `account`'s pending votes for `validator` to active votes. * @param validator The voter to vote for. * @param account The voter account's pending votes to active votes * @return True upon success. * @dev Pending votes cannot be activated until an election has been held. */ function activateForAccount(address validator, address account) external nonReentrant returns (bool) { return _activate(validator, account); } function _activate(address validator, address account) internal returns (bool) { PendingVote storage pendingVote = votes.pending.forValidator[validator].byAccount[account]; require(pendingVote.epoch < getEpochNumber(), "Pending vote epoch not passed"); uint256 value = pendingVote.value; require(value > 0, "Vote value cannot be zero"); decrementPendingVotes(validator, account, value); incrementActiveVotes(validator, account, value); emit ValidatorVoteActivated(account, validator, value); return true; } /** * @notice Returns whether or not an account's votes for the specified validator can be activated. * @param account The account with pending votes. * @param validator The validator that `account` has pending votes for. * @return Whether or not `account` has activatable votes for `validator`. * @dev Pending votes cannot be activated until an election has been held. */ function hasActivatablePendingVotes(address account, address validator) external view returns (bool) { PendingVote storage pendingVote = votes.pending.forValidator[validator].byAccount[account]; return pendingVote.epoch < getEpochNumber() && pendingVote.value > 0; } function pendingInfo(address account, address validator) external view returns (uint256, uint256) { PendingVote storage pendingVote = votes.pending.forValidator[validator].byAccount[account]; return (pendingVote.value, pendingVote.epoch); } /** * @notice Revokes `value` pending votes for `validator` * @param validator The validator to revoke votes from. * @param value The number of votes to revoke. * @param lesser The validator receiving fewer votes than the validator for which the vote was revoked, * or 0 if that validator has the fewest votes of any validator. * @param greater The validator receiving more votes than the validator for which the vote was revoked, * or 0 if that validator has the most votes of any validator. * @param index The index of the validator in the account's voting list. * @return True upon success. * @dev Fails if the account has not voted on a validator. */ function revokePending( address validator, uint256 value, address lesser, address greater, uint256 index ) external nonReentrant returns (bool) { require(validator != address(0), "Validator address zero"); address account = getAccounts().voteSignerToAccount(msg.sender); require(0 < value, "Vote value cannot be zero"); require( value <= getPendingVotesForValidatorByAccount(validator, account), "Vote value larger than pending votes" ); decrementPendingVotes(validator, account, value); decrementTotalVotes(validator, value, lesser, greater); getLockedGold().incrementNonvotingAccountBalance(account, value); if (getTotalVotesForValidatorByAccount(validator, account) == 0) { deleteElement(votes.validatorsVotedFor[account], validator, index); } emit ValidatorPendingVoteRevoked(account, validator, value); return true; } /** * @notice Revokes all active votes for `validator` * @param validator The validator to revoke votes from. * @param lesser The validator receiving fewer votes than the validator for which the vote was revoked, * or 0 if that validator has the fewest votes of any validator. * @param greater The validator receiving more votes than the validator for which the vote was revoked, * or 0 if that validator has the most votes of any validator. * @param index The index of the validator in the account's voting list. * @return True upon success. * @dev Fails if the account has not voted on a validator. */ function revokeAllActive(address validator, address lesser, address greater, uint256 index) external nonReentrant returns (bool) { address account = getAccounts().voteSignerToAccount(msg.sender); uint256 value = getActiveVotesForValidatorByAccount(validator, account); return _revokeActive(validator, value, lesser, greater, index); } /** * @notice Revokes `value` active votes for `validator` * @param validator The validator to revoke votes from. * @param value The number of votes to revoke. * @param lesser The validator receiving fewer votes than the validator for which the vote was revoked, * or 0 if that validator has the fewest votes of any validator. * @param greater The validator receiving more votes than the validator for which the vote was revoked, * or 0 if that validator has the most votes of any validator. * @param index The index of the validator in the account's voting list. * @return True upon success. * @dev Fails if the account has not voted on a validator. */ function revokeActive( address validator, uint256 value, address lesser, address greater, uint256 index ) external nonReentrant returns (bool) { return _revokeActive(validator, value, lesser, greater, index); } function _revokeActive( address validator, uint256 value, address lesser, address greater, uint256 index ) internal returns (bool) { // TODO(asa): Dedup with revokePending. require(validator != address(0), "Validator address zero"); address account = getAccounts().voteSignerToAccount(msg.sender); require(0 < value, "Vote value cannot be zero"); require( value <= getActiveVotesForValidatorByAccount(validator, account), "Vote value larger than active votes" ); decrementActiveVotes(validator, account, value); decrementTotalVotes(validator, value, lesser, greater); getLockedGold().incrementNonvotingAccountBalance(account, value); if (getTotalVotesForValidatorByAccount(validator, account) == 0) { deleteElement(votes.validatorsVotedFor[account], validator, index); } emit ValidatorActiveVoteRevoked(account, validator, value); return true; } /** * @notice Decrements `value` pending or active votes for `validator` from `account`. * First revokes all pending votes and then, if `value` votes haven't * been revoked yet, revokes additional active votes. * Fundamentally calls `revokePending` and `revokeActive` but only resorts validators once. * @param account The account whose votes to `validator` should be decremented. * @param validator The validator to decrement votes from. * @param maxValue The maxinum number of votes to decrement and revoke. * @param lesser The validator receiving fewer votes than the validator for which the vote was revoked, * or 0 if that validator has the fewest votes of any validator. * @param greater The validator receiving more votes than the validator for which the vote was revoked, * or 0 if that validator has the most votes of any validator. * @param index The index of the validator in the account's voting list. * @return uint256 Number of votes successfully decremented and revoked, with a max of `value`. */ function _decrementVotes( address account, address validator, uint256 maxValue, address lesser, address greater, uint256 index ) internal returns (uint256) { uint256 remainingValue = maxValue; uint256 pendingVotes = getPendingVotesForValidatorByAccount(validator, account); if (pendingVotes > 0) { uint256 decrementValue = Math.min(remainingValue, pendingVotes); decrementPendingVotes(validator, account, decrementValue); emit ValidatorPendingVoteRevoked(account, validator, decrementValue); remainingValue = remainingValue.sub(decrementValue); } uint256 activeVotes = getActiveVotesForValidatorByAccount(validator, account); if (activeVotes > 0 && remainingValue > 0) { uint256 decrementValue = Math.min(remainingValue, activeVotes); decrementActiveVotes(validator, account, decrementValue); emit ValidatorActiveVoteRevoked(account, validator, decrementValue); remainingValue = remainingValue.sub(decrementValue); } uint256 decrementedValue = maxValue.sub(remainingValue); if (decrementedValue > 0) { decrementTotalVotes(validator, decrementedValue, lesser, greater); if (getTotalVotesForValidatorByAccount(validator, account) == 0) { deleteElement(votes.validatorsVotedFor[account], validator, index); } } return decrementedValue; } /** * @notice Returns the total number of votes cast by an account. * @param account The address of the account. * @return The total number of votes cast by an account. */ function getTotalVotesByAccount(address account) external view returns (uint256) { uint256 total = 0; address[] memory validators = votes.validatorsVotedFor[account]; for (uint256 i = 0; i < validators.length; i = i.add(1)) { total = total.add(getTotalVotesForValidatorByAccount(validators[i], account)); } return total; } /** * @notice Returns the pending votes for `validator` made by `account`. * @param validator The address of the validator. * @param account The address of the voting account. * @return The pending votes for `validator` made by `account`. */ function getPendingVotesForValidatorByAccount(address validator, address account) public view returns (uint256) { return votes.pending.forValidator[validator].byAccount[account].value; } /** * @notice Returns the total votes for `validator` made by `account`. * @param validator The address of the validator. * @param account The address of the voting account. * @return The total votes for `validator` made by `account`. */ function getTotalVotesForValidatorByAccount(address validator, address account) public view returns (uint256) { uint256 pending = getPendingVotesForValidatorByAccount(validator, account); uint256 active = getActiveVotesForValidatorByAccount(validator, account); return pending.add(active); } /** * @notice Returns the total active vote units made for `validator`. * @param validator The address of the validator. * @return The total active vote units made for `validator`. */ function getActiveVotesForValidator(address validator) public view returns (uint256) { return votes.active.forValidator[validator].total; } /** * @notice Returns the total votes made for `validator`. * @param validator The address of the validator. * @return The total votes made for `validator`. */ function getTotalVotesForValidator(address validator) public view returns (uint256) { return votes.pending.forValidator[validator].total.add(votes.active.forValidator[validator].total); } /** * @notice Returns the pending voters vote for `validator`. * @param validator The address of the validator. * @return The active voters made for `validator`. */ function getPendingVotersForValidator(address validator) public view returns (address[] memory) { return votes.pending.forValidator[validator].voters; } /** * @notice Returns the pending votes made for `validator`. * @param validator The address of the validator. * @return The pending votes made for `validator`. */ function getPendingVotesForValidator(address validator) public view returns (uint256) { return votes.pending.forValidator[validator].total; } /** * @notice Returns whether or not a validator is eligible to receive votes. * @return Whether or not a validator is eligible to receive votes. * @dev Eligible validators that have received their maximum number of votes cannot receive more. */ function getValidatorEligibility(address validator) external view returns (bool) { return votes.total.eligible.contains(validator); } function getTopValidators(uint256 topNum) external view returns (address[] memory) { uint256 numElectionValidators = votes.total.eligible.numElementsGreaterThan(0, topNum); return votes.total.eligible.headN(numElectionValidators); } function distributeEpochVotersRewards(address validator, uint256 value, address lesser, address greater) external onlyVm { _distributeEpochVotersRewards(validator, value, lesser, greater); } function _distributeEpochVotersRewards(address validator, uint256 value, address lesser, address greater) internal { if (votes.total.eligible.contains(validator)) { uint256 newVoteTotal = votes.total.eligible.getValue(validator).add(value); votes.total.eligible.update(validator, newVoteTotal, lesser, greater); } votes.active.forValidator[validator].total = votes.active.forValidator[validator].total.add(value); votes.active.total = votes.active.total.add(value); emit EpochRewardsDistributedToVoters(validator, value); } /** * @notice Increments the number of total votes for `validator` by `value`. * @param validator The validator whose vote total should be incremented. * @param value The number of votes to increment. * @param lesser The validator receiving fewer votes than the validator for which the vote was cast, * or 0 if that validator has the fewest votes of any validator. * @param greater The validator receiving more votes than the validator for which the vote was cast, * or 0 if that validator has the most votes of any validator. */ function incrementTotalVotes(address validator, uint256 value, address lesser, address greater) private { uint256 newVoteTotal = votes.total.eligible.getValue(validator).add(value); votes.total.eligible.update(validator, newVoteTotal, lesser, greater); } /** * @notice Decrements the number of total votes for `validator` by `value`. * @param validator The validator whose vote total should be decremented. * @param value The number of votes to decrement. * @param lesser The validator receiving fewer votes than the validator for which the vote was revoked, * or 0 if that validator has the fewest votes of any validator. * @param greater The validator receiving more votes than the validator for which the vote was revoked, * or 0 if that validator has the most votes of any validator. */ function decrementTotalVotes(address validator, uint256 value, address lesser, address greater) private { if (votes.total.eligible.contains(validator)) { uint256 newVoteTotal = votes.total.eligible.getValue(validator).sub(value); votes.total.eligible.update(validator, newVoteTotal, lesser, greater); } } /** * @notice Marks a validator ineligible for electing validators. * @param validator The address of the validator. * @dev Can only be called by the registered "Validators" contract. */ function markValidatorIneligible(address validator) external onlyRegisteredContract(VALIDATORS_REGISTRY_ID) { votes.total.eligible.remove(validator); emit ValidatorMarkedIneligible(validator); } /** * @notice Marks a validator eligible for electing validators. * @param validator The address of the validator. * @param lesser The address of the validator that has received fewer votes than this validator. * @param greater The address of the validator that has received more votes than this validator. */ function markValidatorEligible(address lesser, address greater, address validator) external onlyRegisteredContract(VALIDATORS_REGISTRY_ID) { uint256 value = getTotalVotesForValidator(validator); //will reload the last voters Info votes.total.eligible.insert(validator, value, lesser, greater); emit ValidatorMarkedEligible(validator); } /** * @notice Increments the number of pending votes for `validator` made by `account`. * @param validator The address of the validator. * @param account The address of the voting account. * @param value The number of votes. */ function incrementPendingVotes(address validator, address account, uint256 value) private { PendingVotes storage pending = votes.pending; pending.total = pending.total.add(value); ValidatorPendingVotes storage validatorPending = pending.forValidator[validator]; validatorPending.total = validatorPending.total.add(value); PendingVote storage pendingVote = validatorPending.byAccount[account]; if (pendingVote.value == 0) { validatorPending.voters.push(account); } pendingVote.value = pendingVote.value.add(value); pendingVote.epoch = getEpochNumber(); } /** * @notice Decrements the number of pending votes for `validator` made by `account`. * @param validator The address of the validator. * @param account The address of the voting account. * @param value The number of votes. */ function decrementPendingVotes(address validator, address account, uint256 value) private { PendingVotes storage pending = votes.pending; pending.total = pending.total.sub(value); ValidatorPendingVotes storage validatorPending = pending.forValidator[validator]; validatorPending.total = validatorPending.total.sub(value); PendingVote storage pendingVote = validatorPending.byAccount[account]; pendingVote.value = pendingVote.value.sub(value); if (pendingVote.value == 0) { pendingVote.epoch = 0; } } /** * @notice Increments the number of active votes for `validator` made by `account`. * @param validator The address of the validator. * @param account The address of the voting account. * @param value The number of votes. */ function incrementActiveVotes(address validator, address account, uint256 value) private returns (uint256) { ActiveVotes storage active = votes.active; active.total = active.total.add(value); uint256 units = votesToUnits(validator, value); ValidatorActiveVotes storage validatorActive = active.forValidator[validator]; validatorActive.total = validatorActive.total.add(value); validatorActive.totalUnits = validatorActive.totalUnits.add(units); validatorActive.unitsByAccount[account] = validatorActive.unitsByAccount[account].add(units); return value; } /** * @notice Decrements the number of active votes for `validator` made by `account`. * @param validator The address of the validator. * @param account The address of the voting account. * @param value The number of votes. */ function decrementActiveVotes(address validator, address account, uint256 value) private returns (uint256) { ActiveVotes storage active = votes.active; active.total = active.total.sub(value); ValidatorActiveVotes storage validatorActive = active.forValidator[validator]; //-------------------------- // Rounding may cause votesToUnits to return 0 for value != 0, preventing users // from revoking the last of their votes. The case where value == votes is special cased // to prevent this. uint256 units = 0; uint256 activeVotes = getActiveVotesForValidatorByAccount(validator, account); if (activeVotes == value) { units = validatorActive.unitsByAccount[account]; } else { units = votesToUnits(validator, value); } validatorActive.total = validatorActive.total.sub(value); validatorActive.totalUnits = validatorActive.totalUnits.sub(units); validatorActive.unitsByAccount[account] = validatorActive.unitsByAccount[account].sub(units); return value; } /** * @notice Returns the validators that `account` has voted for. * @param account The address of the account casting votes. * @return The validators that `account` has voted for. */ function getValidatorsVotedForByAccount(address account) external view returns (address[] memory) { return votes.validatorsVotedFor[account]; } /** * @notice Deletes an element from a list of addresses. * @param list The list of addresses. * @param element The address to delete. * @param index The index of `element` in the list. */ function deleteElement(address[] storage list, address element, uint256 index) private { require(index < list.length && list[index] == element, "Bad index"); uint256 lastIndex = list.length.sub(1); list[index] = list[lastIndex]; list.length = lastIndex; } /** * @notice Returns whether or not a validator can receive the specified number of votes. * @param validator The address of the validator. * @param value The number of votes. * @return Whether or not a validator can receive the specified number of votes. * @dev Votes are not allowed to be cast that validator's proportion of locked gold * voting for it to greater than TotalLockedGold * @dev Note that validators may still receive additional votes via rewards even if this function * returns false. */ function canReceiveVotes(address validator, uint256 value) public view returns (bool) { uint256 left = getTotalVotesForValidator(validator).add(value); uint256 right = getLockedGold().getTotalLockedGold(); return left <= right; } /** * @notice Returns the number of votes that a validator can receive. * @return The number of votes that a validator can receive. * @dev Votes are not allowed to be cast that would increase a validator's proportion of locked gold * voting for it to greater than * (numValidatorMembers + 1) / min(maxElectableValidators, numRegisteredValidators) * @dev Note that a validator's vote total may exceed this number through rewards or config changes. */ function getNumVotesReceivable() external view returns (uint256) { uint256 numerator = getLockedGold().getTotalLockedGold(); uint256 denominator = Math.min( electableValidators.max, getValidators().getNumRegisteredValidators() ); return numerator.div(denominator); } /** * @notice Returns the total votes received across all validators. * @return The total votes received across all validators. */ function getTotalVotes() public view returns (uint256) { return votes.active.total.add(votes.pending.total); } /** * @notice Returns the active votes received across all validators. * @return The active votes received across all validators. */ function getActiveVotes() public view returns (uint256) { return votes.active.total; } /** * @notice Returns the list of validator validators eligible to elect validators. * @return The list of validator validators eligible to elect validators. */ function getEligibleValidators() external view returns (address[] memory) { return votes.total.eligible.getKeys(); } /** * @notice Returns lists of all validator validators and the number of votes they've received. * @return Lists of all validators and the number of votes they've received. */ function getTotalVotesForEligibleValidators() external view returns (address[] memory validators, uint256[] memory values) { return votes.total.eligible.getElements(); } /** * @notice Returns a list of elected validators with seats allocated to validators via the D'Hondt * method. * @return The list of elected validators. */ function electValidatorSigners() external view returns (address[] memory) { return electNValidatorSigners(electableValidators.min, electableValidators.max); } /** * @notice Returns a list of elected validators with seats allocated to validators * @return The list of elected validators. */ function electNValidatorSigners(uint256 minElectableValidators, uint256 maxElectableValidators) public view returns (address[] memory) { require(getTotalVotes() > 0, "require TotalVotes > 0"); // Validators must have at least `electabilityThreshold` proportion of the total votes to be // considered for the election. uint256 requiredVotes = electabilityThreshold .multiply(FixidityLib.newFixed(getTotalVotes())) .fromFixed(); // Only consider validators with at least `requiredVotes` but do not consider more validators than the // max number of electable validators. uint256 numElectionValidators = votes.total.eligible.numElementsGreaterThan( requiredVotes, maxElectableValidators ); address[] memory electionValidators = votes.total.eligible.headN(numElectionValidators); uint256 totalNumMembersElected = electionValidators.length; require(totalNumMembersElected >= minElectableValidators, "Not enough elected validators"); address[] memory electedValidators = new address[](totalNumMembersElected); totalNumMembersElected = 0; for (uint256 j = 0; j < electionValidators.length; j = j.add(1)) { electedValidators[totalNumMembersElected] = getAccounts().getValidatorSigner(electionValidators[j]); totalNumMembersElected = totalNumMembersElected.add(1); } return electedValidators; } /** * @notice Returns get current validator signers using the precompiles. * @return List of current validator signers. */ function getCurrentValidatorSigners() public view returns (address[] memory) { uint256 n = numberValidatorsInCurrentSet(); address[] memory res = new address[](n); for (uint256 i = 0; i < n; i = i.add(1)) { res[i] = validatorSignerAddressFromCurrentSet(i); } return res; } // Struct to hold local variables for `forceDecrementVotes`. // Needed to prevent solc error of "stack too deep" from too many local vars. struct DecrementVotesInfo { address[] validators; uint256 remainingValue; } /** * @notice Reduces the total amount of `account`'s voting gold by `value` by * iterating over all validators voted for by account. * @param account Address to revoke votes from. * @param value Maximum amount of votes to revoke. * @param lessers The validators receiving fewer votes than the i'th `validator`, or 0 if * the i'th `validator` has the fewest votes of any validator. * @param greaters The validators receivier more votes than the i'th `validator`, or 0 if * the i'th `validator` has the most votes of any validator. * @param indices The indices of the i'th validator in the account's voting list. * @return Number of votes successfully decremented. */ function forceDecrementVotes( address account, uint256 value, address[] calldata lessers, address[] calldata greaters, uint256[] calldata indices ) external nonReentrant onlyRegisteredContract(LOCKED_GOLD_REGISTRY_ID) returns (uint256) { require(value > 0, "Decrement value must be greater than 0."); DecrementVotesInfo memory info = DecrementVotesInfo(votes.validatorsVotedFor[account], value); require( lessers.length <= info.validators.length && lessers.length == greaters.length && greaters.length == indices.length, "Input lengths must be correspond." ); // Iterate in reverse order to hopefully optimize removing pending votes before active votes // And to attempt to preserve `account`'s earliest votes (assuming earliest = prefered) for (uint256 i = info.validators.length; i > 0; i = i.sub(1)) { info.remainingValue = info.remainingValue.sub( _decrementVotes( account, info.validators[i.sub(1)], info.remainingValue, lessers[i.sub(1)], greaters[i.sub(1)], indices[i.sub(1)] ) ); if (info.remainingValue == 0) { break; } } require(info.remainingValue == 0, "Failure to decrement all votes."); return value; } /** * @notice Returns the active votes for `validator` made by `account`. * @param validator The address of the validator. * @param account The address of the voting account. * @return The active votes for `validator` made by `account`. */ function getActiveVotesForValidatorByAccount(address validator, address account) public view returns (uint256) { return unitsToVotes(validator, votes.active.forValidator[validator].unitsByAccount[account]); } /** * @notice Returns the number of units corresponding to `value` active votes. * @param validator The address of the validator. * @param value The number of active votes. * @return The corresponding number of units. */ function votesToUnits(address validator, uint256 value) private view returns (uint256) { if (votes.active.forValidator[validator].totalUnits == 0) { return value.mul(UNIT_PRECISION_FACTOR); } else { return value.mul(votes.active.forValidator[validator].totalUnits).div(votes.active.forValidator[validator].total); } } /** * @notice Returns the number of active votes corresponding to `value` units. * @param validator The address of the validator. * @param value The number of units. * @return The corresponding number of active votes. */ function unitsToVotes(address validator, uint256 value) private view returns (uint256) { if (votes.active.forValidator[validator].totalUnits == 0) { return 0; } else { return value.mul(votes.active.forValidator[validator].total).div(votes.active.forValidator[validator].totalUnits); } } function activeAllPending(address[] calldata validators) external nonReentrant onlyVm returns (bool) { for (uint256 i = 0; i < validators.length; i = i.add(1)) { _activeAllPending(validators[i]); } return true; } function _activeAllPending(address validator) internal returns (bool) { address[] memory voters = votes.pending.forValidator[validator].voters; for (uint256 i = 0; i < voters.length; i = i.add(1)) { address account = voters[i]; PendingVote memory pendingVote = votes.pending.forValidator[validator].byAccount[account]; uint256 value = pendingVote.value; decrementPendingVotes(validator, account, value); incrementActiveVotes(validator, account, value); emit ValidatorVoteActivated(account, validator, value); } delete votes.pending.forValidator[validator].voters; //clear voters return true; } }
TODO(asa): Dedup with revokePending.
function _revokeActive( address validator, uint256 value, address lesser, address greater, uint256 index ) internal returns (bool) { require(validator != address(0), "Validator address zero"); address account = getAccounts().voteSignerToAccount(msg.sender); require(0 < value, "Vote value cannot be zero"); require( value <= getActiveVotesForValidatorByAccount(validator, account), "Vote value larger than active votes" ); decrementActiveVotes(validator, account, value); decrementTotalVotes(validator, value, lesser, greater); getLockedGold().incrementNonvotingAccountBalance(account, value); if (getTotalVotesForValidatorByAccount(validator, account) == 0) { deleteElement(votes.validatorsVotedFor[account], validator, index); } emit ValidatorActiveVoteRevoked(account, validator, value); return true; }
7,245,064
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.2; /* * @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; } } pragma solidity ^0.6.2; /** * @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: node_modules\@openzeppelin\contracts\introspection\ERC165.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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 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.2; /** * @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; } } pragma solidity ^0.6.2; /** * @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; } } pragma solidity ^0.6.2; /** * @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); } } } } pragma solidity ^0.6.2; /** * @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. */ 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 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()); } } pragma solidity ^0.6.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.2; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } pragma solidity ^0.6.2; /** * @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); } pragma solidity ^0.6.2; /** * @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"); } } } pragma solidity ^0.6.2; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered 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: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Metadata.sol pragma solidity ^0.6.2; /** * @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: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Enumerable.sol pragma solidity ^0.6.2; /** * @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); } /** * @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 { // 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]; } // 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(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(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(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(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: node_modules\@openzeppelin\contracts\utils\EnumerableMap.sol pragma solidity ^0.6.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 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) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ 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(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(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(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // File: node_modules\@openzeppelin\contracts\utils\Strings.sol pragma solidity ^0.6.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--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin\contracts\access\AccessControl.sol pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * 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 { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet 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 Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @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 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 { require(hasRole(_roles[role].adminRole, _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 { require(hasRole(_roles[role].adminRole, _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 { 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, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity ^0.6.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 ^ 0xe985e9c ^ 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 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 override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).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(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, 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 returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 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 = 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 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 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 mecanisms 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 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 returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || 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 = ownerOf(tokenId); _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(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); _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); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(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 { } } // File: contracts\categories\NFT.sol pragma solidity ^0.6.8; contract NFT is Ownable, ERC721 { event BaseURIChange(string baseURI); event ItemCreated( address indexed owner, uint256 indexed tokenId ); struct TokenExtraInfo { string metaDataURI; bytes32 metaDataHash; address tokenMinter; } mapping (uint256 => TokenExtraInfo) public extraInfoMap; mapping(uint256 => uint256) public royaltyAmount; // Used to correctly support fingerprint verification for the assets bytes4 public constant _INTERFACE_ID_ERC721_VERIFY_FINGERPRINT = bytes4( keccak256("verifyFingerprint(uint256,bytes32)") ); constructor ( string memory _name, string memory _symbol, string memory _baseUri ) public Ownable() ERC721(_name, _symbol) { setBaseURI(_baseUri); // Registers _registerInterface(_INTERFACE_ID_ERC721_VERIFY_FINGERPRINT); } /** * @dev Sets the base URI for the registry metadata * @param _baseUri Address for the fees collector */ function setBaseURI(string memory _baseUri) public onlyOwner { _setBaseURI(_baseUri); emit BaseURIChange(_baseUri); } /** * Creates a NFT * @param _metaDataURI for the new token * @param _metaData metadata JSONified string */ function create( string calldata _metaDataURI, string calldata _metaData, uint256 _royaltyAmount ) external { _create(_metaDataURI, _metaData, _royaltyAmount); } function _create( string memory _metaDataURI, string memory _metaData, uint256 _royaltyAmount ) internal returns (uint256 tokenId) { tokenId = totalSupply(); /// Save data extraInfoMap[tokenId] = TokenExtraInfo({ metaDataURI: _metaDataURI, metaDataHash: getMetaDataHash(_metaData), tokenMinter: msg.sender }); royaltyAmount[tokenId] = _royaltyAmount; /// Mint new NFT _mint(msg.sender, tokenId); _setTokenURI(tokenId, _metaDataURI); emit ItemCreated(msg.sender, tokenId); } function getMetaDataHash(string memory _metaData) public pure returns (bytes32) { bytes32 msgHash = keccak256(abi.encodePacked(_metaData)); // return prefixed hash, see: eth_sign() return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash) ); } function verifyFingerprint(uint256 _tokenId, bytes32 _fingerprint) public view returns (bool) { return extraInfoMap[_tokenId].metaDataHash == _fingerprint; } function getRoyaltyAmount(uint256 _tokenId) external view returns (uint256) { return royaltyAmount[_tokenId] ; } function getTokenMinter(uint256 _tokenId) external view returns (address) { return extraInfoMap[_tokenId].tokenMinter; } } pragma solidity ^0.6.2; interface IERC721Verifiable is IERC721 { function verifyFingerprint(uint256, bytes32) external view returns (bool); } pragma solidity ^0.6.2; interface IMarketplace { struct Order { // Order ID bytes32 id; // Owner of the NFT address seller; // NFT registry address address nftAddress; // Price (in wei) for the published item uint256 price; // royalty percentage uint256 royalty; // Time when this sale ends uint256 expiresAt; // ERC20 currency address address currency; } struct Bid { // Bid Id bytes32 id; // Bidder address address bidder; // Time when bid was created uint256 price; // Time when this bid ends uint256 expiresAt; } // ORDER EVENTS event OrderCreated( bytes32 id, address indexed seller, address indexed nftAddress, uint256 indexed assetId, uint256 priceInWei, uint256 expiresAt, address currency ); event OrderUpdated( bytes32 id, uint256 priceInWei, uint256 expiresAt ); event OrderSuccessful( bytes32 id, address indexed buyer, uint256 priceInWei ); event OrderCancelled(bytes32 id); // BID EVENTS event BidCreated( bytes32 id, address indexed nftAddress, uint256 indexed assetId, address indexed bidder, uint256 priceInWei, uint256 expiresAt ); event BidAccepted(bytes32 id); event BidCancelled(bytes32 id); } pragma solidity ^0.6.2; contract FeeManager is Ownable { event ChangedFeePerMillion(uint256 cutPerMillion); // Market fee on sales uint256 public cutPerMillion; uint256 public constant maxCutPerMillion = 100000; // 10% cut /** * @dev Sets the share cut for the owner of the contract that's * charged to the seller on a successful sale * @param _cutPerMillion - Share amount, from 0 to 99,999 */ function setOwnerCutPerMillion(uint256 _cutPerMillion) external onlyOwner { require( _cutPerMillion < maxCutPerMillion, "The owner cut should be between 0 and maxCutPerMillion" ); cutPerMillion = _cutPerMillion; emit ChangedFeePerMillion(cutPerMillion); } } contract OpenMarketplace is Ownable, Pausable, FeeManager, IMarketplace, ERC721Holder { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; // IERC20 public acceptedToken; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE"); // From ERC721 registry assetId to Order (to avoid asset collision) mapping(address => mapping(uint256 => Order)) public orderByAssetId; // From ERC721 registry assetId to Bid (to avoid asset collision) mapping(address => mapping(uint256 => Bid)) public bidByOrderId; // From IERC20 to status for toggling accepted currencies mapping (address => bool) public acceptedCurrencies; // 721 Interfaces bytes4 public constant _INTERFACE_ID_ERC721 = 0x80ac58cd; // Mocking a constant for ether as currency address public constant MARKETPLACE_ETHER = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @dev Initialize this contract. Acts as a constructor */ constructor() public Ownable() { // require(_acceptedToken.isContract(),"The accepted token address must be a deployed contract"); // acceptedToken = IERC20(_acceptedToken); acceptedCurrencies[MARKETPLACE_ETHER] = true; } /** * @dev Sets the paused failsafe. Can only be called by owner * @param _setPaused - paused state */ function setPaused(bool _setPaused) public onlyOwner { return (_setPaused) ? _pause() : _unpause(); } /** * @dev Set accepted currencies as payments. Can only be called by owner * @param _token - ERC20 contract address * @param _status - status for the token */ function setCurrency(address _token, bool _status) external onlyOwner { require(_token.isContract(),"The accepted token address must be a deployed contract"); acceptedCurrencies[_token] = _status; } /*** * @dev Creates a new order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - Duration of the order (in hours) * @param _currency - Currency for which the order is created */ function createOrder(address _nftAddress, uint256 _assetId, uint256 _priceInWei,uint256 _royality, uint256 _expiresAt, address _currency) external whenNotPaused { _createOrder(_nftAddress, _assetId, _priceInWei, _royality, _expiresAt, _currency); } /** * @dev Cancel an already published order * can only be canceled by seller or the contract owner * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function cancelOrder(address _nftAddress, uint256 _assetId) external whenNotPaused { Order memory order = orderByAssetId[_nftAddress][_assetId]; require(order.seller == msg.sender || msg.sender == owner(), "Marketplace: unauthorized sender"); // Remove pending bid if any Bid memory bid = bidByOrderId[_nftAddress][_assetId]; if (bid.id != 0) { _cancelBid(bid.id, _nftAddress, _assetId, bid.bidder, bid.price); } // Cancel order. _cancelOrder(order.id, _nftAddress, _assetId, msg.sender); } /** * @dev Update an already published order * can only be updated by seller * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function updateOrder(address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt) external whenNotPaused { Order storage order = orderByAssetId[_nftAddress][_assetId]; // Check valid order to update require(order.id != 0, "Marketplace: asset not published"); require(order.seller == msg.sender, "Marketplace: sender not allowed"); require(order.expiresAt >= block.timestamp, "Marketplace: order expired"); // check order updated params require(_priceInWei > 0, "Marketplace: Price should be bigger than 0"); require(_expiresAt > block.timestamp.add(1 minutes), "Marketplace: Expire time should be more than 1 minute in the future"); order.price = _priceInWei; order.expiresAt = _expiresAt; emit OrderUpdated(order.id, _priceInWei, _expiresAt); } /** * @dev Executes the sale for a published NFT * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _priceInWei - Order price */ function safeExecuteOrder(address _nftAddress, uint256 _assetId, uint256 _priceInWei) external payable whenNotPaused { // Get the current valid order for the asset or fail Order memory order = _getValidOrder(_nftAddress, _assetId); /// Check the execution price matches the order price // require(order.price == _priceInWei, "Marketplace: invalid price"); require(order.seller != msg.sender, "Marketplace: unauthorized sender"); order.currency == MARKETPLACE_ETHER ? require(order.price == msg.value, "Marketplace: invalid price") : require(order.price == _priceInWei, "Marketplace: invalid price"); // market fee to cut uint256 saleShareAmount = 0; // Send market fees to owner if (FeeManager.cutPerMillion > 0) { // Calculate sale share saleShareAmount = order.price.mul(FeeManager.cutPerMillion).div(1e6); // Transfer share amount for marketplace Owner order.currency == MARKETPLACE_ETHER ? payable(owner()).transfer(saleShareAmount) : IERC20(order.currency).safeTransferFrom(msg.sender, owner(),saleShareAmount); } // royalty fee to cut uint256 royaltyAmount = 0; // Send market fees to owner if (order.royalty != 0) { // Calculate sale share royaltyAmount = order.price.mul(order.royalty).div( 100 ); if(NFT(order.nftAddress).getTokenMinter(_assetId) != msg.sender) { // Transfer royalty percentage for marketplace Owner order.currency == MARKETPLACE_ETHER ? payable(address(NFT(order.nftAddress).getTokenMinter(_assetId))).transfer(royaltyAmount) : IERC20(order.currency).safeTransferFrom(msg.sender, address(NFT(order.nftAddress).getTokenMinter(_assetId)), royaltyAmount); } } order.currency == MARKETPLACE_ETHER ? payable(order.seller).transfer(order.price.sub(saleShareAmount).sub(royaltyAmount)) : IERC20(order.currency).safeTransferFrom(msg.sender, order.seller, order.price.sub(saleShareAmount).sub(royaltyAmount)); // Remove pending bid if any Bid memory bid = bidByOrderId[_nftAddress][_assetId]; if (bid.id != 0) { _cancelBid(bid.id, _nftAddress, _assetId, bid.bidder, bid.price); } _executeOrder(order.id, msg.sender, _nftAddress, _assetId, _priceInWei); } /** * @dev Places a bid for a published NFT * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _priceInWei - Bid price in acceptedToken currency * @param _expiresAt - Bid expiration time */ function safePlaceBid(address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt) external payable whenNotPaused { Order memory order = _getValidOrder(_nftAddress, _assetId); order.currency == MARKETPLACE_ETHER ? _createBid(_nftAddress, _assetId, msg.value, _expiresAt) : _createBid(_nftAddress, _assetId, _priceInWei, _expiresAt); } /** * @dev Cancel an already published bid * can only be canceled by seller or the contract owner * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function cancelBid(address _nftAddress, uint256 _assetId) public whenNotPaused { Bid memory bid = bidByOrderId[_nftAddress][_assetId]; require(bid.bidder == msg.sender || msg.sender == owner(),"Marketplace: Unauthorized sender"); _cancelBid(bid.id, _nftAddress, _assetId, bid.bidder, bid.price); } /** * @dev Executes the sale for a published NFT by accepting a current bid * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _priceInWei - Bid price in wei in acceptedTokens currency */ function acceptBid(address _nftAddress, uint256 _assetId, uint256 _priceInWei) public whenNotPaused { // check order validity Order memory order = _getValidOrder(_nftAddress, _assetId); // item seller is the only allowed to accept a bid require(order.seller == msg.sender, "Marketplace: unauthorized sender"); Bid memory bid = bidByOrderId[_nftAddress][_assetId]; require(bid.price == _priceInWei, "Marketplace: invalid bid price"); require(bid.expiresAt >= block.timestamp, "Marketplace: the bid expired"); // remove bid delete bidByOrderId[_nftAddress][_assetId]; emit BidAccepted(bid.id); // market fee to cut uint256 saleShareAmount = 0; // Send market fees to owner if (FeeManager.cutPerMillion > 0) { // Calculate sale share saleShareAmount = (bid.price).mul(FeeManager.cutPerMillion).div(1e6); // Transfer share amount for marketplace Owner order.currency == MARKETPLACE_ETHER ? payable(owner()).transfer(saleShareAmount) : IERC20(order.currency).safeTransfer(owner(),saleShareAmount); } // royalty fee to cut uint256 royaltyAmount = 0; // Send market fees to owner if (order.royalty != 0) { // Calculate royalty amount royaltyAmount = bid.price.mul(order.royalty).div( 100 ); if(NFT(order.nftAddress).getTokenMinter(_assetId) != msg.sender) { // Transfer royalty percentage for marketplace Owner order.currency == MARKETPLACE_ETHER ? payable(address(NFT(order.nftAddress).getTokenMinter(_assetId))).transfer(royaltyAmount) : IERC20(order.currency).safeTransfer(address(NFT(order.nftAddress).getTokenMinter(_assetId)), royaltyAmount); } } // transfer escrowed bid amount minus market fee to seller order.currency == MARKETPLACE_ETHER ? payable(order.seller).transfer(bid.price.sub(saleShareAmount).sub(royaltyAmount)) : IERC20(order.currency).safeTransfer(order.seller, bid.price.sub(saleShareAmount).sub(royaltyAmount)); _executeOrder(order.id, bid.bidder, _nftAddress, _assetId, _priceInWei); } /** * @dev Internal function gets Order by nftRegistry and assetId. Checks for the order validity * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function _getValidOrder(address _nftAddress, uint256 _assetId) internal view returns (Order memory order) { order = orderByAssetId[_nftAddress][_assetId]; require(order.id != 0, "Marketplace: asset not published"); require(order.expiresAt >= block.timestamp, "Marketplace: order expired"); } /** * @dev Executes the sale for a published NFT * @param _orderId - Order Id to execute * @param _buyer - address * @param _nftAddress - Address of the NFT registry * @param _assetId - NFT id * @param _priceInWei - Order price */ function _executeOrder(bytes32 _orderId, address _buyer, address _nftAddress, uint256 _assetId, uint256 _priceInWei) internal { // remove order delete orderByAssetId[_nftAddress][_assetId]; // Transfer NFT asset IERC721(_nftAddress).safeTransferFrom(address(this), _buyer, _assetId); // Notify .. emit OrderSuccessful(_orderId, _buyer, _priceInWei); } /** * @dev Creates a new order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - Expiration time for the order */ function _createOrder(address _nftAddress, uint256 _assetId, uint256 _priceInWei,uint256 _royality, uint256 _expiresAt, address _currency) internal { // Check nft registry IERC721 nftRegistry = IERC721(_nftAddress); // Check _acceptedCurrency require( acceptedCurrencies[_currency], "Marketplace: Unacceptable marketplace currency" ); // Check order creator is the asset owner address assetOwner = nftRegistry.ownerOf(_assetId); require( assetOwner == msg.sender, "Marketplace: Only the asset owner can create orders" ); require(_priceInWei > 0, "Marketplace: Price should be bigger than 0"); require( _expiresAt > block.timestamp.add(1 minutes), "Marketplace: Publication should be more than 1 minute in the future" ); // get NFT asset from seller nftRegistry.safeTransferFrom(assetOwner, address(this), _assetId); // create the orderId bytes32 orderId = keccak256(abi.encodePacked(block.timestamp, assetOwner, _nftAddress, _assetId, _priceInWei)); // save order orderByAssetId[_nftAddress][_assetId] = Order({ id: orderId, seller: assetOwner, nftAddress: _nftAddress, price: _priceInWei, royalty:_royality, expiresAt: _expiresAt, currency: _currency }); emit OrderCreated(orderId, assetOwner, _nftAddress, _assetId, _priceInWei, _expiresAt, _currency); } /** * @dev Creates a new bid on a existing order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - expires time */ function _createBid(address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt) internal { // Checks order validity Order memory order = _getValidOrder(_nftAddress, _assetId); // check on expire time if (_expiresAt > order.expiresAt) { _expiresAt = order.expiresAt; } // Check price if theres previous a bid Bid memory bid = bidByOrderId[_nftAddress][_assetId]; // if theres no previous bid, just check price > 0 if (bid.id != 0) { if (bid.expiresAt >= block.timestamp) { require( _priceInWei > bid.price, "Marketplace: bid price should be higher than last bid" ); } else { require(_priceInWei > 0, "Marketplace: bid should be > 0"); } _cancelBid(bid.id, _nftAddress, _assetId, bid.bidder, bid.price); } else { require(_priceInWei > 0, "Marketplace: bid should be > 0"); } // Transfer sale amount from bidder to escrow // acceptedToken.safeTransferFrom(msg.sender, address(this), _priceInWei); if(order.currency != 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE){ IERC20(address(order.currency)).transferFrom(msg.sender, address(this), _priceInWei); } // Create bid bytes32 bidId = keccak256(abi.encodePacked(block.timestamp, msg.sender, order.id, _priceInWei, _expiresAt)); // Save Bid for this order bidByOrderId[_nftAddress][_assetId] = Bid({ id: bidId, bidder: msg.sender, price: _priceInWei, expiresAt: _expiresAt }); emit BidCreated(bidId, _nftAddress, _assetId, msg.sender, _priceInWei, _expiresAt); } /** * @dev Cancel an already published order * can only be canceled by seller or the contract owner * @param _orderId - Bid identifier * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _seller - Address */ function _cancelOrder(bytes32 _orderId, address _nftAddress, uint256 _assetId, address _seller) internal { delete orderByAssetId[_nftAddress][_assetId]; /// send asset back to seller IERC721(_nftAddress).safeTransferFrom(address(this), _seller, _assetId); emit OrderCancelled(_orderId); } /** * @dev Cancel bid from an already published order * can only be canceled by seller or the contract owner * @param _bidId - Bid identifier * @param _nftAddress - registry address * @param _assetId - ID of the published NFT * @param _bidder - Address * @param _escrowAmount - in acceptenToken currency */ function _cancelBid(bytes32 _bidId, address _nftAddress, uint256 _assetId, address _bidder, uint256 _escrowAmount) internal { delete bidByOrderId[_nftAddress][_assetId]; Order memory order = _getValidOrder(_nftAddress, _assetId); // return escrow to canceled bidder order.currency == MARKETPLACE_ETHER ? payable(_bidder).transfer(_escrowAmount) : IERC20(order.currency).safeTransfer(_bidder, _escrowAmount); emit BidCancelled(_bidId); } // function _requireERC721(address _nftAddress) internal view returns (IERC721) { // require(_nftAddress.isContract(),"The NFT Address should be a contract"); // require(IERC721(_nftAddress).supportsInterface(_INTERFACE_ID_ERC721), "The NFT contract has an invalid ERC721 implementation"); // return IERC721(_nftAddress); // } }
Executes the sale for a published NFT by accepting a current bid _nftAddress - Address of the NFT registry _assetId - ID of the published NFT _priceInWei - Bid price in wei in acceptedTokens currency/ check order validity item seller is the only allowed to accept a bid remove bid market fee to cut Send market fees to owner Calculate sale share Transfer share amount for marketplace Owner Send market fees to owner Calculate royalty amount Transfer royalty percentage for marketplace Owner
function acceptBid(address _nftAddress, uint256 _assetId, uint256 _priceInWei) public whenNotPaused { Order memory order = _getValidOrder(_nftAddress, _assetId); require(order.seller == msg.sender, "Marketplace: unauthorized sender"); Bid memory bid = bidByOrderId[_nftAddress][_assetId]; require(bid.price == _priceInWei, "Marketplace: invalid bid price"); require(bid.expiresAt >= block.timestamp, "Marketplace: the bid expired"); delete bidByOrderId[_nftAddress][_assetId]; emit BidAccepted(bid.id); uint256 saleShareAmount = 0; if (FeeManager.cutPerMillion > 0) { saleShareAmount = (bid.price).mul(FeeManager.cutPerMillion).div(1e6); order.currency == MARKETPLACE_ETHER ? payable(owner()).transfer(saleShareAmount) : IERC20(order.currency).safeTransfer(owner(),saleShareAmount); } if (order.royalty != 0) { royaltyAmount = bid.price.mul(order.royalty).div( 100 ); if(NFT(order.nftAddress).getTokenMinter(_assetId) != msg.sender) { order.currency == MARKETPLACE_ETHER ? payable(address(NFT(order.nftAddress).getTokenMinter(_assetId))).transfer(royaltyAmount) : IERC20(order.currency).safeTransfer(address(NFT(order.nftAddress).getTokenMinter(_assetId)), royaltyAmount); } } payable(order.seller).transfer(bid.price.sub(saleShareAmount).sub(royaltyAmount)) : IERC20(order.currency).safeTransfer(order.seller, bid.price.sub(saleShareAmount).sub(royaltyAmount)); _executeOrder(order.id, bid.bidder, _nftAddress, _assetId, _priceInWei); }
13,995,269
// File: contracts/common/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/ContextMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/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 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; } } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: @openzeppelin/contracts/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 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 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() { _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); } } // File: @openzeppelin/contracts/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/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 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 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 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/IERC721Enumerable.sol 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); } // File: @openzeppelin/contracts/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: @openzeppelin/contracts/token/ERC721/ERC721.sol 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; /** * @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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol 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(); } } // File: contracts/ERC721Tradable.sol pragma solidity ^0.8.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // File: contracts/BitKoi.sol pragma solidity ^0.8.0; /** * @title BitKoi * BitKoi - a blockchain game at scale */ /// @title mix up two fish and find out which traits they should have abstract contract BitKoiTraitInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isBitKoiTraits() virtual public pure returns (bool); ///mix up the "genes" of the fish to see which genes our new fish will have function smooshFish(uint256 genes1, uint256 genes2, uint256 targetBlock) virtual public returns (uint256); } /// @title A facet of BitKoiCore that manages special access privileges. /// Based on work from Axiom Zen (https://www.axiomzen.co) contract BitKoiAccessControl { // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address payable _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() virtual public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for KoiPond. Holds all common structs, events and base variables. /// based on code written for CK by Axiom Zen (https://www.axiomzen.co) abstract contract BitKoiBase is BitKoiAccessControl, ERC721Tradable { /*** EVENTS ***/ /// @dev The Spawn event is fired whenever a new fish comes into existence. This obviously /// includes any time a fish is created through the spawnFish method, but it is also called /// when a new gen0 fish is created. event Spawn(address owner, uint256 koiFishId, uint256 parent1Id, uint256 parent2Id, uint256 genes, uint16 generation, uint64 timestamp); event BreedingSuccessful(address owner, uint256 newFishId, uint256 parent1Id, uint256 parent2Id, uint64 cooldownEndBlock); /*** DATA TYPES ***/ struct BitKoi { // The fish's genetic code - this will never change for any fish. uint256 genes; // The timestamp from the block when this fish came into existence. uint64 spawnTime; // The minimum timestamp after which this fish can engage in spawning // activities again. uint64 cooldownEndBlock; // The ID of the parents of this fish, set to 0 for gen0 fish. // With uint32 there's a limit of 4 billion fish uint32 parent1Id; uint32 parent2Id; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this fish. This starts at zero // for gen0 fish, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action. uint16 cooldownIndex; // The "generation number" of this fish. Fish minted by the KP contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other fish is the larger of the two generation // numbers of their parents, plus one. uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "cooldown" Designed such that the cooldown roughly /// doubles each time a fish is bred, encouraging owners not to just keep breeding the same fish over /// and over again. Caps out at one week (a fish can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the KoiFish struct for all KoiFish in existence. The ID /// of each fish is actually an index into this array. Fish 0 has an invalid genetic /// code and can't be used to produce offspring. BitKoi[] bitKoi; /// @dev A mapping from fish IDs to the address that owns them. All fish have /// some valid owner address, even gen0 fish are created with a non-zero owner. mapping (uint256 => address) bitKoiIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from KoiFishIDs to an address that has been approved to call /// transferFrom(). Each KoiFish can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) bitKoiIndexToApproved; // /// @dev Assigns ownership of a specific KoiFish to an address. function _transfer(address _from, address _to, uint256 _tokenId) override internal { require(ownerOf(_tokenId) == _from, "ERC721: transfer of token that is not own"); require(_to != address(0), "ERC721: transfer to the zero address"); // Since the number of fish is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; ownershipTokenCount[_from]--; _beforeTokenTransfer(_from, _to, _tokenId); // actually transfer ownership bitKoiIndexToOwner[_tokenId] = _to; // Clear approvals from the previous owner _approve(address(0), _tokenId); emit Transfer(_from, _to, _tokenId); } /// @notice Returns the address currently assigned ownership of a given BitKoi. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) override public view returns (address owner) { owner = bitKoiIndexToOwner[_tokenId]; require(owner != address(0)); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return ownershipTokenCount[owner]; } /// @notice Returns a list of all KoiFish IDs assigned to an address. /// @param _owner The owner whose KoiFish we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire KoiFish array looking for fish belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalBitKoi = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all fish have IDs starting at 1 and increasing // sequentially up to the totalKoi count. uint256 bitKoiId; for (bitKoiId = 1; bitKoiId <= totalBitKoi; bitKoiId++) { if (bitKoiIndexToOwner[bitKoiId] == _owner) { result[resultIndex] = bitKoiId; resultIndex++; } } return result; } } function _mintNewKoi(address _to, uint256 _tokenId) internal { _mint(_to, _tokenId); // Since the number of fish is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership bitKoiIndexToOwner[_tokenId] = _to; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } abstract contract BitKoiOwnership is BitKoiBase { /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns( address _claimant, uint256 _tokenId ) internal view returns (bool) { return (ownerOf(_tokenId) == _claimant); } /// @dev Checks if a given address currently has transferApproval for a particular KoiFish. /// @param _claimant the address we are confirming fish is approved for. /// @param _tokenId fish id, only valid when > 0 function _approvedFor( address _claimant, uint256 _tokenId ) internal view returns (bool) { return bitKoiIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting KoiFish on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve( uint256 _tokenId, address _approved ) internal { bitKoiIndexToApproved[_tokenId] = _approved; } function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any fish (except very briefly // after a gen0 fish is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of fish // through the allow + transferFrom flow. // You can only send your own fish require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } } abstract contract BitKoiBreeding is BitKoiOwnership { event Hatch(address owner, uint256 fishId, uint256 genes); uint256 public breedFee = 0 wei; uint256 public hatchFee = 0 wei; /// @dev The address of the sibling contract that is used to implement the genetic combination algorithm. BitKoiTraitInterface public bitKoiTraits; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setBitKoiTraitAddress(address _address) external onlyCEO { BitKoiTraitInterface candidateContract = BitKoiTraitInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isBitKoiTraits()); // Set the new contract address bitKoiTraits = candidateContract; } /// @dev Checks to see if a given fish is ready to hatch after the gestation period has passed. function _isReadyToHatch(uint256 _fishId) private view returns (bool) { BitKoi storage fishToHatch = bitKoi[_fishId]; return fishToHatch.cooldownEndBlock <= uint64(block.number); } /// @dev Checks that a given fish is able to breed. Requires that the /// current cooldown is finished function _isReadyToBreed(BitKoi storage _fish) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the fish has a pending birth; there can be some period of time between the end // of the pregnacy timer and the spawn event. return _fish.cooldownEndBlock <= uint64(block.number); } /// @dev Set the cooldownEndTime for the given fish based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _koiFish A reference to the KoiFish in storage which needs its timer started. function _triggerCooldown(BitKoi storage _koiFish) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _koiFish.cooldownEndBlock = uint64((cooldowns[_koiFish.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_koiFish.cooldownIndex < 13) { _koiFish.cooldownIndex += 1; } } // @dev Updates the minimum payment required for calling breedWith(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setBreedFee(uint256 val) external onlyCEO { breedFee = val; } // @dev Updates the minimum payment required for calling hatchFish(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setHatchFee(uint256 val) external onlyCEO { hatchFee = val; } /// @notice Checks that a given fish is able to breed (i.e. it is not /// in the middle of a siring cooldown). /// @param _koiId reference the id of the fish, any user can inquire about it function isReadyToBreed(uint256 _koiId) public view returns (bool) { require(_koiId > 0); BitKoi storage fish = bitKoi[_koiId]; return _isReadyToBreed(fish); } /// @notice Checks that a given fish is able to breed (i.e. it is not /// in the middle of a siring cooldown). /// @param _koiId reference the id of the fish, any user can inquire about it function isReadyToHatch(uint256 _koiId) public view returns (bool) { require(_koiId > 0); return _isReadyToHatch(_koiId); } /// @dev Internal check to see if a the parents are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _parent1 A reference to the Fish struct of the potential first parent /// @param _parent1Id The first parent's ID. /// @param _parent2 A reference to the Fish struct of the potential second parent /// @param _parent2Id The second parent's ID. function _isValidMatingPair( BitKoi storage _parent1, uint256 _parent1Id, BitKoi storage _parent2, uint256 _parent2Id ) private view returns(bool) { // A Fish can't breed with itself! if (_parent1Id == _parent2Id) { return false; } //the fish have to have genes if (_parent1.genes == 0 || _parent2.genes == 0) { return false; } // Fish can't breed with their parents. if (_parent1.parent1Id == _parent1Id || _parent1.parent2Id == _parent2Id) { return false; } if (_parent2.parent1Id == _parent1Id || _parent2.parent2Id == _parent2Id) { return false; } // OK the tx if either fish is gen zero (no parent found). if (_parent2.parent1Id == 0 || _parent1.parent1Id == 0) { return true; } // Fish can't breed with full or half siblings. if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent1Id == _parent1.parent2Id) { return false; } if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent2Id == _parent1.parent2Id) { return false; } // gtg return true; } /// @notice Checks to see if two BitKoi can breed together, including checks for /// ownership and siring approvals. Doesn't check that both BitKoi are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// @param _parent1Id The ID of the proposed first parent. /// @param _parent2Id The ID of the proposed second parent. function canBreedWith(uint256 _parent1Id, uint256 _parent2Id) external view returns(bool) { require(_parent1Id > 0); require(_parent2Id > 0); BitKoi storage parent1 = bitKoi[_parent1Id]; BitKoi storage parent2 = bitKoi[_parent2Id]; return _isValidMatingPair(parent1, _parent1Id, parent2, _parent2Id); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _parent1Id, uint256 _parent2Id) internal returns(uint256) { // Grab a reference to the Koi from storage. BitKoi storage parent1 = bitKoi[_parent1Id]; BitKoi storage parent2 = bitKoi[_parent2Id]; // Determine the higher generation number of the two parents uint16 parentGen = parent1.generation; if (parent2.generation > parent1.generation) { parentGen = parent2.generation; } uint256 bitKoiCoProceeds = msg.value; //transfer the breed fee less the pond cut to the CFO contract payable(address(cfoAddress)).transfer(bitKoiCoProceeds); // Make the new fish! address owner = bitKoiIndexToOwner[_parent1Id]; uint256 newFishId = _createBitKoi(_parent1Id, _parent2Id, parentGen + 1, 0, owner); // Trigger the cooldown for both parents. _triggerCooldown(parent1); _triggerCooldown(parent2); // Emit the breeding event. emit BreedingSuccessful(bitKoiIndexToOwner[_parent1Id], newFishId, _parent1Id, _parent2Id, parent1.cooldownEndBlock); return newFishId; } function breedWith(uint256 _parent1Id, uint256 _parent2Id) external payable whenNotPaused { // Checks for payment. require(msg.value >= breedFee); ///check to see if the caller owns both fish require(_owns(msg.sender, _parent1Id)); require(_owns(msg.sender, _parent2Id)); // Grab a reference to the first parent BitKoi storage parent1 = bitKoi[_parent1Id]; // Make sure enough time has passed since the last time this fish was bred require(_isReadyToBreed(parent1)); // Grab a reference to the second parent BitKoi storage parent2 = bitKoi[_parent2Id]; // Make sure enough time has passed since the last time this fish was bred require(_isReadyToBreed(parent2)); // Test that these fish are a valid mating pair. require(_isValidMatingPair( parent2, _parent2Id, parent1, _parent1Id )); // All checks passed, make a new fish!! _breedWith(_parent1Id, _parent2Id); } /// @dev An internal method that creates a new fish and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _parent1Id The fish ID of the first parent (zero for gen0) /// @param _parent2Id The fish ID of the second parent (zero for gen0) /// @param _generation The generation number of this fish, must be computed by caller. /// @param _genes The fish's genetic code. /// @param _owner The inital owner of this fish, must be non-zero (except for fish ID 0) function _createBitKoi( uint256 _parent1Id, uint256 _parent2Id, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKoiFish() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_parent1Id == uint256(uint32(_parent1Id))); require(_parent2Id == uint256(uint32(_parent2Id))); require(_generation == uint256(uint16(_generation))); // New fish starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } BitKoi memory _bitKoi = BitKoi({ genes: _genes, spawnTime: uint64(block.timestamp), cooldownEndBlock: 0, parent1Id: uint32(_parent1Id), parent2Id: uint32(_parent2Id), cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newBitKoiId = bitKoi.length; bitKoi.push(_bitKoi); // It's probably never going to happen, 4 billion fish is A LOT, but // let's just be 100% sure we never let this happen. require(newBitKoiId == uint256(uint32(newBitKoiId))); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _mintNewKoi(_owner, newBitKoiId); // emit the spawn event emit Spawn( _owner, newBitKoiId, uint256(_bitKoi.parent1Id), uint256(_bitKoi.parent2Id), _bitKoi.genes, uint16(_generation), uint64(block.timestamp) ); BitKoi storage brandNewKoi = bitKoi[newBitKoiId]; _triggerCooldown(brandNewKoi); return newBitKoiId; } function hatchFish(uint256 _fishId, uint256 _geneSet1, uint256 _geneSet2) external payable whenNotPaused { // Checks for payment. require(msg.value >= hatchFee); //ensure the caller owns the egg they want to hatch require(_owns(msg.sender, _fishId)); _hatchFish(_fishId, _geneSet1, _geneSet2); } function _hatchFish(uint256 _fishId, uint256 _geneSet1, uint256 _geneSet2) internal { BitKoi storage fishToHatch = bitKoi[_fishId]; BitKoi storage parent1 = bitKoi[fishToHatch.parent1Id]; BitKoi storage parent2 = bitKoi[fishToHatch.parent2Id]; uint256 genes1 = 0; uint256 genes2 = 0; if (fishToHatch.parent1Id > 0){ genes1 = parent1.genes; } else { genes1 = _geneSet1; } if (fishToHatch.parent2Id > 0){ genes2 = parent2.genes; } else { genes2 = _geneSet2; } // Check that the parent is a valid fish require(parent1.spawnTime != 0 && parent2.spawnTime != 0); // Check to see if the fish is ready to hatch require(_isReadyToHatch(_fishId)); // Make sure this fish doesn't already have genes require(fishToHatch.genes == 0); // next, let's get new genes for the fish we're about to hatch uint256 newFishGenes = bitKoiTraits.smooshFish(genes1, genes2, fishToHatch.cooldownEndBlock - 1); fishToHatch.genes = uint256(newFishGenes); //transfer the hatch fee less the pond cut to the CFO contract payable(address(cfoAddress)).transfer(msg.value); emit Hatch(msg.sender, _fishId, newFishGenes); } } abstract contract BitKoiAuction is BitKoiBreeding { // Tracks last 5 sale price of gen0 fish sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Cut contract owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut = 250; /// @param _ownerCut - update the percent cut the contract owner takes on each breed or hatch event, must be /// between 0-10,000. function setOwnerCut(uint256 _ownerCut) external onlyCEO { require(_ownerCut <= 10000); ownerCut = _ownerCut; } // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(address sellerId, uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev adds an auction to the list of open auctions. Also fires the AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(address _sellerId, uint256 _tokenId, Auction memory _auction, uint256 _auctionStarted) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 0 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( address(_sellerId), uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration), uint256(_auctionStarted) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId) internal { _removeAuction(_tokenId); emit AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = address(uint160(auction.seller)); // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 contractCut = _computeCut(price); uint256 sellerProceeds = price - contractCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) payable(cfoAddress).transfer(contractCut); payable(seller).transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. payable(msg.sender).transfer(bidExcess); // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (block.timestamp > _auction.startedAt) { secondsPassed = block.timestamp - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_startingPrice >= _endingPrice); require(msg.sender == bitKoiIndexToOwner[_tokenId]); Auction memory auction = Auction( address(_seller), uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(block.timestamp) ); _addAuction(_seller, _tokenId, auction, block.timestamp); } function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); //If not a gen0 auction, exit if (seller == address(this)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } _transfer(seller, msg.sender, _tokenId); } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title all functions related to creating fish (and their eggs) abstract contract BitKoiMinting is BitKoiAuction { // Limits the number of fish the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_EGG_CREATION_LIMIT = 45000; // Counts the number of fish the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; // Direct sale is not live to start bool public directSalePaused = true; //determine the price for minting a new BitKoi gen0 egg uint256 public gen0PromoPrice = 5000000000000000000 wei; uint256 public currentGen0Cap = 100; // allow direct sales of gen0 eggs function pauseDirectSale() external onlyCLevel { directSalePaused = true; } // stop direct sales of gen0 eggs function unpauseDirectSale() external onlyCLevel { directSalePaused = false; } // set current cap for sale - this can be raised later so new sales can be started w/ limits function setCurrentGen0Cap(uint256 val) external onlyCEO { currentGen0Cap = val; } // @dev Updates the minimum payment required for calling mintGen0Egg(). Can only /// be called by the CEO address. function setGen0PromoPrice(uint256 val) external onlyCEO { gen0PromoPrice = val; } function mintGen0Egg(address _owner) external payable { require (!directSalePaused); require (msg.value >= gen0PromoPrice); require (gen0CreatedCount < currentGen0Cap); require (gen0CreatedCount < GEN0_EGG_CREATION_LIMIT); //transfer the sale price less the pond cut to the CFO contract payable(address(cfoAddress)).transfer(msg.value); address bitKoiOwner = _owner; gen0CreatedCount++; _createBitKoi(0, 0, 0, 0, bitKoiOwner); } /// @dev we can create promo fish, up to a limit. Only callable by COO /// @param _genes the encoded genes of the fish to be created, any value is accepted /// @param _owner the future owner of the created fish. Default to contract COO function createPromoFish(uint256 _genes, address _owner) external onlyCOO { address bitKoiOwner = _owner; if (bitKoiOwner == address(0)) { bitKoiOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createBitKoi(0, 0, 0, _genes, bitKoiOwner); } } contract BitKoiCore is BitKoiMinting { constructor(address _proxyRegistryAddress) ERC721Tradable("BitKoi", "BITKOI", _proxyRegistryAddress) { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // the creator of the contract is also the initial COO cfoAddress = msg.sender; //start with an initial fish _createBitKoi(0, 0, 0, type(uint256).max, address(this)); } string baseURI = "https://www.bitkoi.co/api/nft/"; string contractMainURI = "https://www.bitkoi.co"; function baseTokenURI() public view returns (string memory) { return baseURI; } function setBaseTokenURI(string memory _newBaseURI) public onlyCEO { baseURI = _newBaseURI; } function setContractURI(string memory _newContractURI) public onlyCEO { contractMainURI = _newContractURI; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } function contractURI() public view returns (string memory) { return contractMainURI; } function unpause() override public onlyCEO whenPaused { require(address(bitKoiTraits) != address(0)); // Actually unpause the contract. super.unpause(); } /// @notice Returns all the relevant information about a specific fish. /// @param _id The ID of the fish we're looking up function getBitKoi(uint256 _id) external view returns ( bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 spawnTime, uint256 parent1Id, uint256 parent2Id, uint256 generation, uint256 cooldownEndBlock, uint256 genes ) { BitKoi storage fish = bitKoi[_id]; isReady = (fish.cooldownEndBlock <= block.number); cooldownIndex = uint256(fish.cooldownIndex); nextActionAt = uint256(fish.cooldownEndBlock); spawnTime = uint256(fish.spawnTime); parent1Id = uint256(fish.parent1Id); parent2Id = uint256(fish.parent2Id); generation = uint256(fish.generation); cooldownEndBlock = uint256(fish.cooldownEndBlock); genes = fish.genes; } }
_bid will throw if the bid or funds transfer fails _bid verifies token ID sizeIf not a gen0 auction, exit Track gen0 sale prices
function bid(uint256 _tokenId) external payable whenNotPaused { address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); if (seller == address(this)) { lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } _transfer(seller, msg.sender, _tokenId); }
11,765,514
pragma solidity ^0.4.23; /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. // -otherManagers: Contracts that need access to functions for gameplay /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // Contracts that require access for gameplay mapping(address => uint8) public otherManagers; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier onlyOtherManagers() { require(otherManagers[msg.sender] == 1); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled) function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } contract CSCNFTFactory { /** Public Functions */ function getAssetDetails(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner ); function getAssetDetailsURI(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner, string metaUriAddress ); function getAssetRawMeta(uint256 _assetId) public view returns( uint256 dataA, uint128 dataB ); function getAssetIdItemType(uint256 _assetId) public view returns( uint256 assetType ); function getAssetIdTypeSequenceId(uint256 _assetId) public view returns( uint256 assetTypeSequenceId ); function getIsNFTAttached( uint256 _tokenId) public view returns( uint256 isAttached ); function getAssetIdCreator(uint256 _assetId) public view returns( address creator ); function getAssetIdOwnerAndOIndex(uint256 _assetId) public view returns( address owner, uint256 ownerIndex ); function getAssetIdOwnerIndex(uint256 _assetId) public view returns( uint256 ownerIndex ); function getAssetIdOwner(uint256 _assetId) public view returns( address owner ); function isAssetIdOwnerOrApproved(address requesterAddress, uint256 _assetId) public view returns( bool ); /// @param _owner The owner whose ships tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire NFT owners array looking for NFT belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens); // Get the name of the Asset type function getTypeName (uint32 _type) public returns(string); function RequestDetachment( uint256 _tokenId ) public; function AttachAsset( uint256 _tokenId ) public; function BatchAttachAssets(uint256[10] _ids) public; function BatchDetachAssets(uint256[10] _ids) public; function RequestDetachmentOnPause (uint256 _tokenId) public; function burnAsset(uint256 _assetID) public; function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } contract CSCTimeSaleManager is ERC721Holder, OperationalControl { //DATATYPES & CONSTANTS struct CollectibleSale { // Current owner of NFT (ERC721) address seller; // Price (in wei) at beginning of sale (For Buying) uint256 startingPrice; // Price (in wei) at end of sale (For Buying) uint256 endingPrice; // Duration (in seconds) of sale, 2592000 = 30 days uint256 duration; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; // Flag denoting is the Sale still active bool isActive; // address of the wallet who bought the asset address buyer; // ERC721 AssetID uint256 tokenId; } struct PastSales { uint256[5] sales; } // CSCNTFAddress address public NFTAddress; // Map from token to their corresponding sale. mapping (uint256 => CollectibleSale) public tokenIdToSale; // Count of AssetType Sales mapping (uint256 => uint256) public assetTypeSaleCount; // Last 5 Prices of AssetType Sales mapping (uint256 => PastSales) internal assetTypeSalePrices; uint256 public avgSalesToCount = 5; // type to sales of type mapping(uint256 => uint256[]) public assetTypeSalesTokenId; event SaleWinner(address owner, uint256 collectibleId, uint256 buyingPrice); event SaleCreated(uint256 tokenID, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint64 startedAt); event SaleCancelled(address seller, uint256 collectibleId); constructor() public { require(msg.sender != address(0)); paused = true; error = false; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; } function setNFTAddress(address _address) public onlyManager { NFTAddress = _address; } function setAvgSalesCount(uint256 _count) public onlyManager { avgSalesToCount = _count; } /// @dev Creates and begins a new sale. function CreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { _createSale(_tokenId, _startingPrice, _endingPrice, _duration, _seller); } function BatchCreateSales(uint256[] _tokenIds, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { uint256 _tokenId; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; _createSale(_tokenId, _startingPrice, _endingPrice, _duration, _seller); } } function CreateSaleAvgPrice(uint256 _tokenId, uint256 _margin, uint _minPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { var cscNFT = CSCNFTFactory(NFTAddress); uint256 assetType = cscNFT.getAssetIdItemType(_tokenId); // Avg Price of last sales uint256 salePrice = GetAssetTypeAverageSalePrice(assetType); // 0-10,000 is mapped to 0%-100% - will be typically 12000 or 120% salePrice = salePrice * _margin / 10000; if(salePrice < _minPrice) { salePrice = _minPrice; } _createSale(_tokenId, salePrice, _endingPrice, _duration, _seller); } function BatchCreateSaleAvgPrice(uint256[] _tokenIds, uint256 _margin, uint _minPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { var cscNFT = CSCNFTFactory(NFTAddress); uint256 assetType; uint256 _tokenId; uint256 salePrice; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; assetType = cscNFT.getAssetIdItemType(_tokenId); // Avg Price of last sales salePrice = GetAssetTypeAverageSalePrice(assetType); // 0-10,000 is mapped to 0%-100% - will be typically 12000 or 120% salePrice = salePrice * _margin / 10000; if(salePrice < _minPrice) { salePrice = _minPrice; } _tokenId = _tokenIds[i]; _createSale(_tokenId, salePrice, _endingPrice, _duration, _seller); } } function BatchCancelSales(uint256[] _tokenIds) public anyOperator { uint256 _tokenId; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; _cancelSale(_tokenId); } } function CancelSale(uint256 _assetId) public anyOperator { _cancelSale(_assetId); } function GetCurrentSalePrice(uint256 _assetId) external view returns(uint256 _price) { CollectibleSale memory _sale = tokenIdToSale[_assetId]; return _currentPrice(_sale); } function GetCurrentTypeSalePrice(uint256 _assetType) external view returns(uint256 _price) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _currentPrice(_sale); } function GetCurrentTypeDuration(uint256 _assetType) external view returns(uint256 _duration) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _sale.duration; } function GetCurrentTypeStartTime(uint256 _assetType) external view returns(uint256 _startedAt) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _sale.startedAt; } function GetCurrentTypeSaleItem(uint256 _assetType) external view returns(address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, uint256 tokenId) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return ( _sale.seller, _sale.startingPrice, _sale.endingPrice, _sale.duration, _sale.startedAt, _sale.tokenId ); } function GetCurrentTypeSaleCount(uint256 _assetType) external view returns(uint256 _count) { return assetTypeSalesTokenId[_assetType].length; } function BuyCurrentTypeOfAsset(uint256 _assetType) external whenNotPaused payable { require(msg.sender != address(0)); require(msg.sender != address(this)); CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; require(_isOnSale(_sale)); _buy(_sale.tokenId, msg.sender, msg.value); } /// @dev BuyNow Function which call the interncal buy function /// after doing all the pre-checks required to initiate a buy function BuyAsset(uint256 _assetId) external whenNotPaused payable { require(msg.sender != address(0)); require(msg.sender != address(this)); CollectibleSale memory _sale = tokenIdToSale[_assetId]; require(_isOnSale(_sale)); //address seller = _sale.seller; _buy(_assetId, msg.sender, msg.value); } function GetAssetTypeAverageSalePrice(uint256 _assetType) public view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < avgSalesToCount; i++) { sum += assetTypeSalePrices[_assetType].sales[i]; } return sum / 5; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public anyOperator whenPaused { // Actually unpause the contract. super.unpause(); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT (ERC721) contract, but can be called either by /// the owner or the NFT (ERC721) contract. function withdrawBalance() public onlyBanker { // We are using this boolean method to make sure that even if one fails it will still work bankManager.transfer(address(this).balance); } /// @dev Returns sales info for an CSLCollectibles (ERC721) on sale. /// @param _assetId - ID of the token on sale function getSale(uint256 _assetId) external view returns (address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, bool isActive, address buyer, uint256 tokenId) { CollectibleSale memory sale = tokenIdToSale[_assetId]; require(_isOnSale(sale)); return ( sale.seller, sale.startingPrice, sale.endingPrice, sale.duration, sale.startedAt, sale.isActive, sale.buyer, sale.tokenId ); } /** Internal Functions */ function _createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) internal { var cscNFT = CSCNFTFactory(NFTAddress); require(cscNFT.isAssetIdOwnerOrApproved(this, _tokenId) == true); CollectibleSale memory onSale = tokenIdToSale[_tokenId]; require(onSale.isActive == false); // Sanity check that no inputs overflow how many bits we've allocated // to store them in the sale struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); //Transfer ownership if needed if(cscNFT.ownerOf(_tokenId) != address(this)) { require(cscNFT.isApprovedForAll(msg.sender, this) == true); cscNFT.safeTransferFrom(cscNFT.ownerOf(_tokenId), this, _tokenId); } CollectibleSale memory sale = CollectibleSale( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), true, address(0), uint256(_tokenId) ); _addSale(_tokenId, sale); } /// @dev Adds an sale to the list of open sales. Also fires the /// SaleCreated event. function _addSale(uint256 _assetId, CollectibleSale _sale) internal { // Require that all sales have a duration of // at least one minute. require(_sale.duration >= 1 minutes); tokenIdToSale[_assetId] = _sale; var cscNFT = CSCNFTFactory(NFTAddress); uint256 assetType = cscNFT.getAssetIdItemType(_assetId); assetTypeSalesTokenId[assetType].push(_assetId); SaleCreated( uint256(_assetId), uint256(_sale.startingPrice), uint256(_sale.endingPrice), uint256(_sale.duration), uint64(_sale.startedAt) ); } /// @dev Returns current price of a Collectible (ERC721) on sale. Broken into two /// functions (this one, that computes the duration from the sale /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(CollectibleSale memory _sale) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _sale.startedAt) { secondsPassed = now - _sale.startedAt; } return _computeCurrentPrice( _sale.startingPrice, _sale.endingPrice, _sale.duration, secondsPassed ); } /// @dev Computes the current price of an sale. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addSale()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the sale, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _buy(uint256 _assetId, address _buyer, uint256 _price) internal { CollectibleSale storage _sale = tokenIdToSale[_assetId]; // Check that the bid is greater than or equal to the current buyOut price uint256 currentPrice = _currentPrice(_sale); require(_price >= currentPrice); _sale.buyer = _buyer; _sale.isActive = false; _removeSale(_assetId); uint256 bidExcess = _price - currentPrice; _buyer.transfer(bidExcess); var cscNFT = CSCNFTFactory(NFTAddress); uint256 assetType = cscNFT.getAssetIdItemType(_assetId); _updateSaleAvgHistory(assetType, _price); cscNFT.safeTransferFrom(this, _buyer, _assetId); emit SaleWinner(_buyer, _assetId, _price); } function _cancelSale (uint256 _assetId) internal { CollectibleSale storage _sale = tokenIdToSale[_assetId]; require(_sale.isActive == true); address sellerAddress = _sale.seller; _removeSale(_assetId); var cscNFT = CSCNFTFactory(NFTAddress); cscNFT.safeTransferFrom(this, sellerAddress, _assetId); emit SaleCancelled(sellerAddress, _assetId); } /// @dev Returns true if the FT (ERC721) is on sale. function _isOnSale(CollectibleSale memory _sale) internal view returns (bool) { return (_sale.startedAt > 0 && _sale.isActive); } function _updateSaleAvgHistory(uint256 _assetType, uint256 _price) internal { assetTypeSaleCount[_assetType] += 1; assetTypeSalePrices[_assetType].sales[assetTypeSaleCount[_assetType] % avgSalesToCount] = _price; } /// @dev Removes an sale from the list of open sales. /// @param _assetId - ID of the token on sale function _removeSale(uint256 _assetId) internal { delete tokenIdToSale[_assetId]; var cscNFT = CSCNFTFactory(NFTAddress); uint256 assetType = cscNFT.getAssetIdItemType(_assetId); bool hasFound = false; for (uint i = 0; i < assetTypeSalesTokenId[assetType].length; i++) { if ( assetTypeSalesTokenId[assetType][i] == _assetId) { hasFound = true; } if(hasFound == true) { if(i+1 < assetTypeSalesTokenId[assetType].length) assetTypeSalesTokenId[assetType][i] = assetTypeSalesTokenId[assetType][i+1]; else delete assetTypeSalesTokenId[assetType][i]; } } assetTypeSalesTokenId[assetType].length--; } }
Avg Price of last sales 0-10,000 is mapped to 0%-100% - will be typically 12000 or 120%
function BatchCreateSaleAvgPrice(uint256[] _tokenIds, uint256 _margin, uint _minPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { var cscNFT = CSCNFTFactory(NFTAddress); uint256 assetType; uint256 _tokenId; uint256 salePrice; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; assetType = cscNFT.getAssetIdItemType(_tokenId); salePrice = GetAssetTypeAverageSalePrice(assetType); salePrice = salePrice * _margin / 10000; if(salePrice < _minPrice) { salePrice = _minPrice; } _tokenId = _tokenIds[i]; _createSale(_tokenId, salePrice, _endingPrice, _duration, _seller); } }
2,571,519
./full_match/80001/0xC983670234A6E4a2AB4A432cDBABC3F05274460e/sources/PolyApart/chef/PolyApartMasterChef.sol
Updating Emssion Rate
function updateEmissionRate(uint256 _apartPerBlock) external onlyOwner { require(_apartPerBlock <= MAX_EMISSION_RATE, "Too high"); massUpdatePools(); apartPerBlock = _apartPerBlock; emit UpdateEmissionRate(msg.sender, _apartPerBlock); }
9,512,010
./partial_match/1/0x6b3E82Ddc85710Ed9c32C61b317ADE1b2A80FC77/sources/LoanManager.sol
Query whether an address has been authorized to move any assets on behalf of someone else _operator the address that might be authorized _assetHolder the address that provided the authorization return bool true if the operator has been authorized to move any assets/
function isApprovedForAll( address _operator, address _assetHolder ) external view returns (bool) { return _isApprovedForAll(_operator, _assetHolder); }
2,884,757
./full_match/43114/0xbd86DdDf32923763F26A0eB051c35b6442c323fe/sources/benqiu.sol
Calculate the Accrued Rewards
function getHarvestable() external view returns (uint256, uint256) { uint rewardsQi = _calculateHarvestable(0, address(this)); uint rewardsAvax = _calculateHarvestable(1, address(this)); return (rewardsQi, rewardsAvax); }
4,511,829
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "./MoleculeScripter.sol"; import "../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "../node_modules/@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /// @title ChemScripts Contract /// @notice interface to get ElementBlocks owner addresses interface ElementBlocksInterface { function ownerOf(uint256 tokenId) external view returns (address owner); } /* ___ _ _ ___ __ __ ___ ___ ___ ___ ___ _____ ___ / __| || | __| \/ / __|/ __| _ \_ _| _ \_ _/ __| | (__| __ | _|| |\/| \__ \ (__| /| || _/ | | \__ \ \___|_||_|___|_| |_|___/\___|_|_\___|_| |_| |___/ This is an ode to the scientific and technological progress humanity has made. It is also a reminder of the importance of freedom and the decentralization of power. The contract allows creators to store generative art scripts that turn chemical molecules into artworks. Every molecule that has been discovered so far can be minted. Use this experimental software at your own risk. */ contract MoleculeSynthesizer is MoleculeScripter, ERC721 { //////////////////////////////////////////////////////////////////////////////////////// // SETUP // //////////////////////////////////////////////////////////////////////////////////////// /// @notice initiates the ElementBlocks contract ElementBlocksInterface elementBlocksContract; /// @notice sets up the token name, tracker and the ElementBlocks contract address constructor(address _elementsContract) ERC721("ChemScripts", "CHEMS") { elementBlocksContract = ElementBlocksInterface(_elementsContract); } /// @notice element short names to ElementBlocks tokenIDs mapping (string => uint) public elementToId; /// @notice allows contract owner to set the element's tokenIDs function setElementId (string memory _element, uint _elementId) public onlyOwner { elementToId[_element] = _elementId; } /// @notice gets element tokenIDs function getElementId (string memory _element) public view returns(uint) { return elementToId[_element]; } //////////////////////////////////////////////////////////////////////////////////////// // ERC721 MAGIC // //////////////////////////////////////////////////////////////////////////////////////// /// @notice apiURI stores the base URI to which the tokenID can be added for tokenURI string public apiURI; /// @notice contract owner can set and change the apiURI function setApiURI(string memory _apiURI) external onlyOwner { apiURI = _apiURI; } /// @notice returns the apiURI function _baseURI() internal view virtual override returns (string memory) { return apiURI; } //////////////////////////////////////////////////////////////////////////////////////// // NFT CHEMISTRY // //////////////////////////////////////////////////////////////////////////////////////// /// @notice event is emitted when a new molecule gets minted event NewMolecule(uint indexed moleculeId, string formula, string indexed key, string name, uint16 indexed scriptId); /// @notice stores molecule information /// @param formula is in InChI (international chemical Identifier) format /// @param key is a unique hash for each molecule /// @param name must be one of the molecules official names /// @param scriptId links to the generative art script that visualizes the molecule struct Molecule { string formula; string key; string name; uint16 scriptId; } /// @notice tokenIds to molecules mapping (uint => Molecule) public molecules; /// @notice keys to tokenIDs mapping (string => uint) public keys; /// @notice ensures that each molecule can only exist once per script function moleculeChecker (uint16 _scriptId, string memory _key) public view { if (keys[_key] > 0) { require(molecules[keys[_key]-1].scriptId != _scriptId, "molecule already minted"); } } /// @notice mints an ERC721 token and ties it to the molecule /// @param _formula requires everything after "InChI=" to at least one letter after the second slash function _createMolecule( string memory _formula, string memory _key, string memory _name, uint16 _scriptId ) internal mintableScript(_scriptId) returns (uint) { moleculeChecker(_scriptId, _key); uint id = _scriptId * 100000 + scripts[_scriptId].currentSupply; _safeMint(msg.sender, id); molecules[id] = Molecule(_formula, _key, _name, _scriptId); keys[_key] = id+1; scripts[_scriptId].currentSupply++; emit NewMolecule(id, _formula, _key, _name, _scriptId); return id; } /// @notice allows contract owner to re-assign wrong molecules when script not yet sealed function chemPolice( uint _moleculeId, string memory _formula, string memory _key, string memory _name) notSealed(molecules[_moleculeId].scriptId) onlyOwner external { Molecule storage wrongMolecule = molecules[_moleculeId]; wrongMolecule.formula = _formula; wrongMolecule.key = _key; wrongMolecule.name = _name; } //////////////////////////////////////////////////////////////////////////////////////// // MINTING & ROYALTIES // //////////////////////////////////////////////////////////////////////////////////////// /// @notice elementPercentage percentage that gets send to ElementBlocks holders uint public elementPercentage = 50; /// @notice allows contract owner to set percentage that flows to element holders function elementSetup(uint _elementPercentage) external onlyOwner { elementPercentage = _elementPercentage; } /// @notice element that currently gets the general royalties uint public royaltyHoldingElement = 1; /// @notice increments the royaltyHoldingElement and accounts for non-existent tokens function _nextRoyaltyHolder() internal { royaltyHoldingElement++; if (royaltyHoldingElement == 101) { royaltyHoldingElement++; } else if (royaltyHoldingElement == 107) { royaltyHoldingElement ++; } else if (royaltyHoldingElement == 121) { royaltyHoldingElement = 1; } } /// @notice gets current price and enables dutch auctions function getPrice(uint _scriptId) view public returns(uint) { uint duration = uint256(scripts[_scriptId].saleDuration) * 1 hours; if (!scripts[_scriptId].publicSale && !scripts[_scriptId].whitelistSale) { return 0; // allows creator and owner to test mint for free before the sale starts } else if ((block.timestamp - startingTime[_scriptId]) >= duration) { return scripts[_scriptId].endPrice; } else { return ((duration - (block.timestamp - startingTime[_scriptId])) * ((scripts[_scriptId].startPrice - scripts[_scriptId].endPrice) / duration) + scripts[_scriptId].endPrice); } } /// @notice distributes funds from minting to script creator and ElementBlock holders function _distributeFunds(uint _scriptId, string memory _formula, uint _numberOfElements) internal { if (msg.value > 0) { // script creator funds payable(scripts[_scriptId].creator).send( (msg.value - (msg.value*elementPercentage/100)) ); // specific elements royalties uint[] memory elementIds = formulaToElementIds(_formula, _numberOfElements); uint fundsPerElement = msg.value*elementPercentage/2/elementIds.length/100; for (uint i = 0; i < elementIds.length; i++) { payable(elementBlocksContract.ownerOf(elementIds[i])).send(fundsPerElement); } // general element royalties payable(elementBlocksContract.ownerOf(royaltyHoldingElement)).send(msg.value*elementPercentage/2/100); _nextRoyaltyHolder(); } } /// @notice returns tokenIds from all elements in a formula function formulaToElementIds(string memory _formula, uint _numberOfElements) public view returns(uint[] memory) { uint[] memory elementIds = new uint[](_numberOfElements); uint slashCounter = 0; uint elementsFound = 0; bytes memory moleculeBytes = bytes(_formula); for (uint i=1; i<moleculeBytes.length; i++) { if (bytes1("/") == moleculeBytes[i-1]) { slashCounter++; } if (slashCounter == 2) { if (_numberOfElements != elementsFound) { revert("Wrong elements nr"); } return elementIds; } if (slashCounter > 0) { string memory oneLetter = string(abi.encodePacked(moleculeBytes[i-1])); string memory twoLetters = string(abi.encodePacked(oneLetter, abi.encodePacked(moleculeBytes[i]))); if (elementToId[twoLetters] > 0) { uint element = elementToId[twoLetters]; elementIds[elementsFound] = element; elementsFound++; } else if (elementToId[oneLetter] > 0) { uint element = elementToId[oneLetter]; elementIds[elementsFound] = element; elementsFound++; } } } revert("Wrong formula"); } /// @notice mints a molecule /// @param _numberOfElements is the number of different elements in the formula /// @dev set the _numberOfElements to how often the element's letters occur in formula function mintMolecule( string memory _formula, string memory _key, string memory _name, uint16 _scriptId, uint _numberOfElements ) public payable { require(msg.value >= getPrice(_scriptId), "Insufficient funds"); require(scripts[_scriptId].publicSale || msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "No public sale"); _distributeFunds(_scriptId, _formula, _numberOfElements); _createMolecule(_formula, _key, _name, _scriptId); } /// @notice root for whitelist minting bytes32 public merkleRoot; /// @notice allows owner to set the merkleRoot for whitelist minting function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; } /// @notice counts the total amount of whitelisted mints across scripts per address mapping (address => uint) public mintCount; /// @notice mints a molecule when msg.sender is whitelisted /// @param _numberOfElements is the number of different elements in the formula /// @param _whitelisted the amount for which msg.sender is whitelisted /// @param _proof an array of proof hashes for the MerkleProof /// @dev set the _numberOfElements to how often the element's letters occur in formula function whitelistMint( string memory _formula, string memory _key, string memory _name, uint16 _scriptId, uint _numberOfElements, uint _whitelisted, bytes32[] memory _proof ) public payable { require(msg.value >= getPrice(_scriptId), "Insufficient funds"); require(scripts[_scriptId].whitelistSale || msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "No WL sale"); require(MerkleProof.verify(_proof, merkleRoot, keccak256(abi.encodePacked(msg.sender, _whitelisted))), "merkle proof failed"); require(mintCount[msg.sender]<_whitelisted, "max reached"); mintCount[msg.sender] += 1; _distributeFunds(_scriptId, _formula, _numberOfElements); _createMolecule(_formula, _key, _name, _scriptId); } /// @notice contract owner can withdraw ETH that was accidentally sent to this contract function rescueFunds() external onlyOwner { payable(owner()).transfer(address(this).balance); } } // 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; 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 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; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // 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) { 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.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.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; /** * @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 "../../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; 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}. 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 { } } // 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 () { 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.8.6; import "../node_modules/@openzeppelin/contracts/access/Ownable.sol"; /// @notice stores and manages generative art scripts contract MoleculeScripter is Ownable { /// @notice stores script data /// @param name is the script's title /// @param scriptCode stores all generative art code on chain /// @param creator is the artists address /// @param publicSale scripts can be minted to /// @param locked scripts cannot be changed anymore /// @param isSealed scripts lock all molecule's chemical data forever /// @param currentSupply shows how many molecules have been minted with that script /// @param totalSupply is the limit of molecules that can be minted with that script /// @param saleDuration is the time in hours of the dutch auction /// @param startPrice is the price in wei the dutch auction starts with /// @param endPrice is the price in wei minting stays at after the saleDuration ended struct Script { string name; string scriptCode; address creator; bool publicSale; bool whitelistSale; bool locked; bool isSealed; uint16 currentSupply; uint16 totalSupply; uint32 saleDuration; uint64 startPrice; uint64 endPrice; } /// @notice emits when a new script is created event NewScript( uint indexed scriptId, string name, string scriptCode, address creator, bool publicSale, bool whitelistSale, bool locked, bool isSealed, uint16 currentSupply, uint16 totalSupply, uint32 saleDuration, uint64 startPrice, uint64 endPrice ); /// @notice stores all scripts on chain Script[] public scripts; /// @notice number of scripts a creator can deploy mapping (address => uint) public allowedScripts; /// @notice script ids that belong to a creator mapping (uint => address) public scriptToCreator; /// @notice total number of scripts a creator has deployed mapping (address => uint) creatorScriptCount; /// @notice script IDs to timestamps of sales starts mapping (uint => uint) startingTime; /// @notice allow new creators in function allowCreator(address _creator, uint _scriptsAllowed) external onlyOwner { allowedScripts[_creator] = allowedScripts[_creator] + _scriptsAllowed; } /// @notice returns all script ids created by one creator function getScriptsByCreator(address _creator) external view returns(uint[] memory) { uint[] memory result = new uint[](creatorScriptCount[_creator]); uint counter = 0; for (uint i = 0; i < scripts.length; i++) { if (scriptToCreator[i] == _creator) { result[counter] = i; counter++; } } return result; } /// @notice checks if the artists is allowed to publish a script modifier onlyCreators(address _creator) { require(allowedScripts[_creator] > 0 || _creator == owner(), "Creator not allowed"); require(allowedScripts[_creator] > creatorScriptCount[_creator] || _creator == owner(), "Creator max scripts reached"); _; } /// @notice creates a new script function createScript( string memory _name, string memory _scriptCode, uint16 _totalSupply, uint32 _saleDuration, uint64 _startPrice, uint64 _endPrice ) external onlyCreators(msg.sender) { scripts.push(Script(_name, _scriptCode, msg.sender, false, false, false, false, 0, _totalSupply, _saleDuration, _startPrice, _endPrice)); uint id = scripts.length -1; creatorScriptCount[msg.sender]++; scriptToCreator[id] = msg.sender; emit NewScript(id, _name, _scriptCode, msg.sender, false, false, false, false, 0, _totalSupply, _saleDuration, _startPrice, _endPrice); } /// @notice allows to activate / deactivate a script and sets starting time for the sale function saleSwitch(uint _scriptId, bool _publicSale, bool _whitelistSale) external onlyScriptCreator(_scriptId) { scripts[_scriptId].publicSale = _publicSale; scripts[_scriptId].whitelistSale = _whitelistSale; if (_publicSale || _whitelistSale) { startingTime[_scriptId] = block.timestamp; } } /// @notice only script creator or owner can execute a function modifier onlyScriptCreator(uint _scriptId) { require(msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "Only script creator or owner"); _; } /// @notice checks if the script is below its total supply modifier mintableScript(uint _scriptId) { require(scripts[_scriptId].currentSupply+1 <= scripts[_scriptId].totalSupply, "Total supply reached"); _; } /// @notice only proceeds when the script is not locked modifier notLocked(uint _scriptId) { require(!scripts[_scriptId].locked, "Script locked"); _; } /// @notice permanently locks a script => price, supply, and code cannot be altered function lockScript(uint _scriptId) notLocked(_scriptId) onlyScriptCreator(_scriptId) external { scripts[_scriptId].locked = true; } /// @notice creators can update the script code when the script is not locked function updateScriptName(uint _scriptId, string memory _scriptName) notLocked(_scriptId) onlyScriptCreator(_scriptId) external { scripts[_scriptId].name = _scriptName; } /// @notice creators can update the script code when the script is not locked function updateScriptCode(uint _scriptId, string memory _scriptCode) notLocked(_scriptId) onlyScriptCreator(_scriptId) external { scripts[_scriptId].scriptCode = _scriptCode; } /// @notice updates total supply when the script is not locked function updateScriptTotalSupply(uint _scriptId, uint16 _totalSupply) notLocked(_scriptId) onlyScriptCreator(_scriptId) external { require(scripts[_scriptId].currentSupply <= _totalSupply, "Supply already exceeded"); scripts[_scriptId].totalSupply = _totalSupply; } /// @notice updates price per molecule when the script is not locked function updateScriptPrice(uint _scriptId, uint32 _saleDuration, uint64 _startPrice, uint64 _endPrice) notLocked(_scriptId) onlyScriptCreator(_scriptId) external { scripts[_scriptId].saleDuration = _saleDuration; scripts[_scriptId].startPrice = _startPrice; scripts[_scriptId].endPrice = _endPrice; } /// @notice only proceeds when the script is not sealed modifier notSealed(uint _scriptId) { require(!scripts[_scriptId].isSealed, "Script is sealed"); _; } /// @notice permanently seals a script => molecules cannot be altered anymore function sealScript(uint _scriptId) notSealed(_scriptId) onlyOwner external { scripts[_scriptId].isSealed = true; } }
updates total supply when the script is not locked
function updateScriptTotalSupply(uint _scriptId, uint16 _totalSupply) notLocked(_scriptId) onlyScriptCreator(_scriptId) external { require(scripts[_scriptId].currentSupply <= _totalSupply, "Supply already exceeded"); scripts[_scriptId].totalSupply = _totalSupply; }
12,791,464
./partial_match/42/0xd20CDFdDC003739229d04ad25feD331Da0442f63/sources/DFG.sol
Transfers fees to the Vaults Transfers fees to the Dev Fund Transfers fees to DFG holders REFLECT INTEGRATION HERE
function addRfiLiquidityLGE(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, uint256 inputRFIamount) public payable } dfgSilverKey.mint((address(msg.sender)), 1); } dfgGoldKey.mint((address(msg.sender)), 1); } dfgDiamondKey.mint((address(msg.sender)), 1); } dfgBronzeKey.mint((address(msg.sender)), 1); dfgSilverKey.mint((address(msg.sender)), 1); dfgGoldKey.mint((address(msg.sender)), 1); } dfgSilverKey.mint((address(msg.sender)), 1); dfgGoldKey.mint((address(msg.sender)), 1); dfgDiamondKey.mint((address(msg.sender)), 1); } dfgBronzeKey.mint((address(msg.sender)), 1); dfgSilverKey.mint((address(msg.sender)), 1); dfgGoldKey.mint((address(msg.sender)), 1); dfgDiamondKey.mint((address(msg.sender)), 1); dfgVaultKey.mint((address(msg.sender)), 1); } } } } } } } } } } } } } mapping(address => bool) public isMinter; } } } function transfer(address recipient, uint256 amount) public virtual override returns (bool) } function allowance(address owner, address spender) public virtual override view returns (uint256) } function approve(address spender, uint256 amount) public virtual override returns (bool) } } } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) } function setShouldTransferChecker(address _transferCheckerAddress) public onlyOwner } address public transferCheckerAddress; function setFeeDistributor(address _feeDistributor) public onlyOwner } address public feeDistributor; function _transfer( address sender, address recipient, uint256 amount if(transferToVaultAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToVaultAmount); _balances[devFundAddr] = _balances[devFundAddr].add(transferToDevFundAmount); emit Transfer(sender, feeDistributor, transferToVaultAmount); if(feeDistributor != address(0)){ IDfgVault(feeDistributor).addPendingRewards(transferToVaultAmount); } }
3,472,485
./full_match/1/0x9dAbAE7274D28A45F0B65Bf8ED201A5731492ca0/sources/contracts/FeeProvider.sol
Update withdraw fee/
function updateWithdrawFee(uint256 newWithdrawFee_) external onlyGovernor { if (newWithdrawFee_ > MAX_FEE_VALUE) revert FeeIsGreaterThanTheMax(); uint256 _currentWithdrawFee = withdrawFee; if (newWithdrawFee_ == _currentWithdrawFee) revert NewValueIsSameAsCurrent(); emit WithdrawFeeUpdated(_currentWithdrawFee, newWithdrawFee_); withdrawFee = newWithdrawFee_; }
3,170,371
./full_match/4/0xA9D9Ced6fe3fcd823Cc92dc0A0bbd4E8159D196E/sources/contract.sol
provide URI for token metadata tokenId - Id of the token return URI of the the token metadata/
function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return _baseURI(); }
12,329,191
./full_match/1/0x960093a8cc1bbeE3767C1d4A0345e18fa510606c/sources/browser/AssGuarD.sol
Check if farming is started
function _checkFarming() internal { require(farmingStartTimestamp != 0, 'Please wait until farming starts'); if (!farmingStarted) { farmingStarted = true; floodingTimestamp = block.timestamp.add(drift); lastUpdateTimestamp = block.timestamp; } }
3,098,511
pragma solidity ^0.6.0; // SPDX-License-Identifier: UNLICENSED // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function TOTALSUPPLY572() public virtual view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF708(address tokenOwner) public virtual view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE480(address tokenOwner, address spender) public virtual view returns (uint256 remaining); //inject NONSTANDARD NAMING function TRANSFER994(address to, uint256 tokens) public virtual returns (bool success); //inject NONSTANDARD NAMING function APPROVE348(address spender, uint256 tokens) public virtual returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM644(address from, address to, uint256 tokens) public virtual returns (bool success); //inject NONSTANDARD NAMING event TRANSFER514(address indexed from, address indexed to, uint256 tokens); //inject NONSTANDARD NAMING event APPROVAL335(address indexed tokenOwner, address indexed spender, uint256 tokens); //inject NONSTANDARD NAMING } library SafeMath { function MUL879(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function DIV1000(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function SUB348(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b <= a); return a - b; } function ADD74(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; assert(c >= a); return c; } function CEIL359(uint a, uint m) internal pure returns (uint r) { //inject NONSTANDARD NAMING return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OWNERSHIPTRANSFERRED45(address indexed _from, address indexed _to); //inject NONSTANDARD NAMING constructor() public { owner = msg.sender; } modifier ONLYOWNER910 { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP407(address payable _newOwner) public ONLYOWNER910 { //inject NONSTANDARD NAMING owner = _newOwner; emit OWNERSHIPTRANSFERRED45(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // 'JAFAR' token contract // Symbol : JAFAR // Name : Jafar // Total supply: 2048 // Decimals : 18 // ---------------------------------------------------------------------------- contract Token is ERC20Interface, Owned{ using SafeMath for uint256; string public symbol = "JAFAR"; string public name = "Jafar"; uint256 public decimals = 18; uint256 _totalSupply = 2048 * 10 ** decimals; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(address preSaleContract) public { owner = msg.sender; balances[preSaleContract] = 1408 * 10 ** (decimals); emit TRANSFER514(address(0), preSaleContract, 1408 * 10 ** (decimals)); balances[owner] = 640 * 10 ** (decimals); emit TRANSFER514(address(0), owner, 640 * 10 ** (decimals)); } function TOTALSUPPLY572() public override view returns (uint256){ //inject NONSTANDARD NAMING return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function BALANCEOF708(address tokenOwner) public override view returns (uint256 balance) { //inject NONSTANDARD NAMING return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function TRANSFER994(address to, uint256 tokens) public override returns (bool success) { //inject NONSTANDARD NAMING // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[msg.sender] >= tokens); require(balances[to] + tokens >= balances[to]); balances[msg.sender] = balances[msg.sender].SUB348(tokens); balances[to] = balances[to].ADD74(tokens); emit TRANSFER514(msg.sender,to,tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function APPROVE348(address spender, uint256 tokens) public override returns (bool success){ //inject NONSTANDARD NAMING allowed[msg.sender][spender] = tokens; emit APPROVAL335(msg.sender,spender,tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function TRANSFERFROM644(address from, address to, uint256 tokens) public override returns (bool success){ //inject NONSTANDARD NAMING require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); require(balances[to] + tokens >= balances[to]); balances[from] = balances[from].SUB348(tokens); balances[to] = balances[to].ADD74(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].SUB348(tokens); emit TRANSFER514(from,to,tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function ALLOWANCE480(address tokenOwner, address spender) public override view returns (uint256 remaining) { //inject NONSTANDARD NAMING return allowed[tokenOwner][spender]; } // ----------------------------------------------------------------------------- // @dev function that burns an amount of the token from caller account // @param _amount The amount that will be burnt // can be used from account owner // ----------------------------------------------------------------------------- function BURNTOKENS275(uint256 _amount) external{ //inject NONSTANDARD NAMING require(balances[msg.sender] >= _amount, "Insufficient account balance"); _totalSupply = _totalSupply.SUB348(_amount); balances[msg.sender] = balances[msg.sender].SUB348(_amount); emit TRANSFER514(msg.sender, address(0), _amount); } }
inject NONSTANDARD NAMING
function ADD74(uint256 a, uint256 b) internal pure returns (uint256) {
13,023,852
./partial_match/1/0x06a1A9D831590Fa7074E16B53B855364D7e0f5bB/sources/MAXXStaking.sol
update time left in stake
function calculateTimeRemain() internal { PWRDPoolTimeRemain = PWRDPoolExp - block.timestamp; }
2,625,304
./partial_match/1/0x1F12CBD283889e4E464D51A8E621037515560552/sources/EverythingisFineErc.sol
exclude from paying fees or having max transaction amount
constructor() ERC20() { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyRevShareFee = 8; uint256 _buyLiquidityFee = 0; uint256 _buyTeamFee = 2; uint256 _sellRevShareFee = 8; uint256 _sellLiquidityFee = 0; uint256 _sellTeamFee = 2; uint256 totalSupply = 999 * 1e18; buyRevShareFee = _buyRevShareFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee; sellRevShareFee = _sellRevShareFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee; revShareWallet = address(0x672C87aD64B7De0d3bb9b614AA4F0493513166Fa); teamWallet = address(0xa83F9A674069889Ae717062F001CB7aaa3626de6); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
9,233,395
pragma solidity 0.4.25; /// @title provides subject to role checking logic contract IAccessPolicy { //////////////////////// // Public functions //////////////////////// /// @notice We don't make this function constant to allow for state-updating access controls such as rate limiting. /// @dev checks if subject belongs to requested role for particular object /// @param subject address to be checked against role, typically msg.sender /// @param role identifier of required role /// @param object contract instance context for role checking, typically contract requesting the check /// @param verb additional data, in current AccessControll implementation msg.sig /// @return if subject belongs to a role function allowed( address subject, bytes32 role, address object, bytes4 verb ) public returns (bool); } /// @title enables access control in implementing contract /// @dev see AccessControlled for implementation contract IAccessControlled { //////////////////////// // Events //////////////////////// /// @dev must log on access policy change event LogAccessPolicyChanged( address controller, IAccessPolicy oldPolicy, IAccessPolicy newPolicy ); //////////////////////// // Public functions //////////////////////// /// @dev allows to change access control mechanism for this contract /// this method must be itself access controlled, see AccessControlled implementation and notice below /// @notice it is a huge issue for Solidity that modifiers are not part of function signature /// then interfaces could be used for example to control access semantics /// @param newPolicy new access policy to controll this contract /// @param newAccessController address of ROLE_ACCESS_CONTROLLER of new policy that can set access to this contract function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController) public; function accessPolicy() public constant returns (IAccessPolicy); } contract StandardRoles { //////////////////////// // Constants //////////////////////// // @notice Soldity somehow doesn't evaluate this compile time // @dev role which has rights to change permissions and set new policy in contract, keccak256("AccessController") bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da; } /// @title Granular code execution permissions /// @notice Intended to replace existing Ownable pattern with more granular permissions set to execute smart contract functions /// for each function where 'only' modifier is applied, IAccessPolicy implementation is called to evaluate if msg.sender belongs to required role for contract being called. /// Access evaluation specific belong to IAccessPolicy implementation, see RoleBasedAccessPolicy for details. /// @dev Should be inherited by a contract requiring such permissions controll. IAccessPolicy must be provided in constructor. Access policy may be replaced to a different one /// by msg.sender with ROLE_ACCESS_CONTROLLER role contract AccessControlled is IAccessControlled, StandardRoles { //////////////////////// // Mutable state //////////////////////// IAccessPolicy private _accessPolicy; //////////////////////// // Modifiers //////////////////////// /// @dev limits function execution only to senders assigned to required 'role' modifier only(bytes32 role) { require(_accessPolicy.allowed(msg.sender, role, this, msg.sig)); _; } //////////////////////// // Constructor //////////////////////// constructor(IAccessPolicy policy) internal { require(address(policy) != 0x0); _accessPolicy = policy; } //////////////////////// // Public functions //////////////////////// // // Implements IAccessControlled // function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController) public only(ROLE_ACCESS_CONTROLLER) { // ROLE_ACCESS_CONTROLLER must be present // under the new policy. This provides some // protection against locking yourself out. require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig)); // We can now safely set the new policy without foot shooting. IAccessPolicy oldPolicy = _accessPolicy; _accessPolicy = newPolicy; // Log event emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy); } function accessPolicy() public constant returns (IAccessPolicy) { return _accessPolicy; } } /// @title standard access roles of the Platform /// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap contract AccessRoles { //////////////////////// // Constants //////////////////////// // NOTE: All roles are set to the keccak256 hash of the // CamelCased role name, i.e. // ROLE_LOCKED_ACCOUNT_ADMIN = keccak256("LockedAccountAdmin") // May issue (generate) Neumarks bytes32 internal constant ROLE_NEUMARK_ISSUER = 0x921c3afa1f1fff707a785f953a1e197bd28c9c50e300424e015953cbf120c06c; // May burn Neumarks it owns bytes32 internal constant ROLE_NEUMARK_BURNER = 0x19ce331285f41739cd3362a3ec176edffe014311c0f8075834fdd19d6718e69f; // May create new snapshots on Neumark bytes32 internal constant ROLE_SNAPSHOT_CREATOR = 0x08c1785afc57f933523bc52583a72ce9e19b2241354e04dd86f41f887e3d8174; // May enable/disable transfers on Neumark bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19; // may reclaim tokens/ether from contracts supporting IReclaimable interface bytes32 internal constant ROLE_RECLAIMER = 0x0542bbd0c672578966dcc525b30aa16723bb042675554ac5b0362f86b6e97dc5; // represents legally platform operator in case of forks and contracts with legal agreement attached. keccak256("PlatformOperatorRepresentative") bytes32 internal constant ROLE_PLATFORM_OPERATOR_REPRESENTATIVE = 0xb2b321377653f655206f71514ff9f150d0822d062a5abcf220d549e1da7999f0; // allows to deposit EUR-T and allow addresses to send and receive EUR-T. keccak256("EurtDepositManager") bytes32 internal constant ROLE_EURT_DEPOSIT_MANAGER = 0x7c8ecdcba80ce87848d16ad77ef57cc196c208fc95c5638e4a48c681a34d4fe7; // allows to register identities and change associated claims keccak256("IdentityManager") bytes32 internal constant ROLE_IDENTITY_MANAGER = 0x32964e6bc50f2aaab2094a1d311be8bda920fc4fb32b2fb054917bdb153a9e9e; // allows to replace controller on euro token and to destroy tokens without withdraw kecckak256("EurtLegalManager") bytes32 internal constant ROLE_EURT_LEGAL_MANAGER = 0x4eb6b5806954a48eb5659c9e3982d5e75bfb2913f55199877d877f157bcc5a9b; // allows to change known interfaces in universe kecckak256("UniverseManager") bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738; // allows to exchange gas for EUR-T keccak("GasExchange") bytes32 internal constant ROLE_GAS_EXCHANGE = 0x9fe43636e0675246c99e96d7abf9f858f518b9442c35166d87f0934abef8a969; // allows to set token exchange rates keccak("TokenRateOracle") bytes32 internal constant ROLE_TOKEN_RATE_ORACLE = 0xa80c3a0c8a5324136e4c806a778583a2a980f378bdd382921b8d28dcfe965585; } contract IEthereumForkArbiter { //////////////////////// // Events //////////////////////// event LogForkAnnounced( string name, string url, uint256 blockNumber ); event LogForkSigned( uint256 blockNumber, bytes32 blockHash ); //////////////////////// // Public functions //////////////////////// function nextForkName() public constant returns (string); function nextForkUrl() public constant returns (string); function nextForkBlockNumber() public constant returns (uint256); function lastSignedBlockNumber() public constant returns (uint256); function lastSignedBlockHash() public constant returns (bytes32); function lastSignedTimestamp() public constant returns (uint256); } /** * @title legally binding smart contract * @dev General approach to paring legal and smart contracts: * 1. All terms and agreement are between two parties: here between smart conctract legal representation and platform investor. * 2. Parties are represented by public Ethereum addresses. Platform investor is and address that holds and controls funds and receives and controls Neumark token * 3. Legal agreement has immutable part that corresponds to smart contract code and mutable part that may change for example due to changing regulations or other externalities that smart contract does not control. * 4. There should be a provision in legal document that future changes in mutable part cannot change terms of immutable part. * 5. Immutable part links to corresponding smart contract via its address. * 6. Additional provision should be added if smart contract supports it * a. Fork provision * b. Bugfixing provision (unilateral code update mechanism) * c. Migration provision (bilateral code update mechanism) * * Details on Agreement base class: * 1. We bind smart contract to legal contract by storing uri (preferably ipfs or hash) of the legal contract in the smart contract. It is however crucial that such binding is done by smart contract legal representation so transaction establishing the link must be signed by respective wallet ('amendAgreement') * 2. Mutable part of agreement may change. We should be able to amend the uri later. Previous amendments should not be lost and should be retrievable (`amendAgreement` and 'pastAgreement' functions). * 3. It is up to deriving contract to decide where to put 'acceptAgreement' modifier. However situation where there is no cryptographic proof that given address was really acting in the transaction should be avoided, simplest example being 'to' address in `transfer` function of ERC20. * **/ contract IAgreement { //////////////////////// // Events //////////////////////// event LogAgreementAccepted( address indexed accepter ); event LogAgreementAmended( address contractLegalRepresentative, string agreementUri ); /// @dev should have access restrictions so only contractLegalRepresentative may call function amendAgreement(string agreementUri) public; /// returns information on last amendment of the agreement /// @dev MUST revert if no agreements were set function currentAgreement() public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ); /// returns information on amendment with index /// @dev MAY revert on non existing amendment, indexing starts from 0 function pastAgreement(uint256 amendmentIndex) public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ); /// returns the number of block at wchich `signatory` signed agreement /// @dev MUST return 0 if not signed function agreementSignedAtBlock(address signatory) public constant returns (uint256 blockNo); /// returns number of amendments made by contractLegalRepresentative function amendmentsCount() public constant returns (uint256); } /** * @title legally binding smart contract * @dev read IAgreement for details **/ contract Agreement is IAgreement, AccessControlled, AccessRoles { //////////////////////// // Type declarations //////////////////////// /// @notice agreement with signature of the platform operator representative struct SignedAgreement { address contractLegalRepresentative; uint256 signedBlockTimestamp; string agreementUri; } //////////////////////// // Immutable state //////////////////////// IEthereumForkArbiter private ETHEREUM_FORK_ARBITER; //////////////////////// // Mutable state //////////////////////// // stores all amendments to the agreement, first amendment is the original SignedAgreement[] private _amendments; // stores block numbers of all addresses that signed the agreement (signatory => block number) mapping(address => uint256) private _signatories; //////////////////////// // Modifiers //////////////////////// /// @notice logs that agreement was accepted by platform user /// @dev intended to be added to functions that if used make 'accepter' origin to enter legally binding agreement modifier acceptAgreement(address accepter) { acceptAgreementInternal(accepter); _; } modifier onlyLegalRepresentative(address legalRepresentative) { require(mCanAmend(legalRepresentative)); _; } //////////////////////// // Constructor //////////////////////// constructor(IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter) AccessControlled(accessPolicy) internal { require(forkArbiter != IEthereumForkArbiter(0x0)); ETHEREUM_FORK_ARBITER = forkArbiter; } //////////////////////// // Public functions //////////////////////// function amendAgreement(string agreementUri) public onlyLegalRepresentative(msg.sender) { SignedAgreement memory amendment = SignedAgreement({ contractLegalRepresentative: msg.sender, signedBlockTimestamp: block.timestamp, agreementUri: agreementUri }); _amendments.push(amendment); emit LogAgreementAmended(msg.sender, agreementUri); } function ethereumForkArbiter() public constant returns (IEthereumForkArbiter) { return ETHEREUM_FORK_ARBITER; } function currentAgreement() public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ) { require(_amendments.length > 0); uint256 last = _amendments.length - 1; SignedAgreement storage amendment = _amendments[last]; return ( amendment.contractLegalRepresentative, amendment.signedBlockTimestamp, amendment.agreementUri, last ); } function pastAgreement(uint256 amendmentIndex) public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ) { SignedAgreement storage amendment = _amendments[amendmentIndex]; return ( amendment.contractLegalRepresentative, amendment.signedBlockTimestamp, amendment.agreementUri, amendmentIndex ); } function agreementSignedAtBlock(address signatory) public constant returns (uint256 blockNo) { return _signatories[signatory]; } function amendmentsCount() public constant returns (uint256) { return _amendments.length; } //////////////////////// // Internal functions //////////////////////// /// provides direct access to derived contract function acceptAgreementInternal(address accepter) internal { if(_signatories[accepter] == 0) { require(_amendments.length > 0); _signatories[accepter] = block.number; emit LogAgreementAccepted(accepter); } } // // MAgreement Internal interface (todo: extract) // /// default amend permission goes to ROLE_PLATFORM_OPERATOR_REPRESENTATIVE function mCanAmend(address legalRepresentative) internal returns (bool) { return accessPolicy().allowed(legalRepresentative, ROLE_PLATFORM_OPERATOR_REPRESENTATIVE, this, msg.sig); } } contract IsContract { //////////////////////// // Internal functions //////////////////////// function isContract(address addr) internal constant returns (bool) { uint256 size; // takes 700 gas assembly { size := extcodesize(addr) } return size > 0; } } contract ITokenMetadata { //////////////////////// // Public functions //////////////////////// function symbol() public constant returns (string); function name() public constant returns (string); function decimals() public constant returns (uint8); } /// @title adds token metadata to token contract /// @dev see Neumark for example implementation contract TokenMetadata is ITokenMetadata { //////////////////////// // Immutable state //////////////////////// // The Token's name: e.g. DigixDAO Tokens string private NAME; // An identifier: e.g. REP string private SYMBOL; // Number of decimals of the smallest unit uint8 private DECIMALS; // An arbitrary versioning scheme string private VERSION; //////////////////////// // Constructor //////////////////////// /// @notice Constructor to set metadata /// @param tokenName Name of the new token /// @param decimalUnits Number of decimals of the new token /// @param tokenSymbol Token Symbol for the new token /// @param version Token version ie. when cloning is used constructor( string tokenName, uint8 decimalUnits, string tokenSymbol, string version ) public { NAME = tokenName; // Set the name SYMBOL = tokenSymbol; // Set the symbol DECIMALS = decimalUnits; // Set the decimals VERSION = version; } //////////////////////// // Public functions //////////////////////// function name() public constant returns (string) { return NAME; } function symbol() public constant returns (string) { return SYMBOL; } function decimals() public constant returns (uint8) { return DECIMALS; } function version() public constant returns (string) { return VERSION; } } contract IBasicToken { //////////////////////// // Events //////////////////////// event Transfer( address indexed from, address indexed to, uint256 amount ); //////////////////////// // Public functions //////////////////////// /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint256); /// @param owner The address that's balance is being requested /// @return The balance of `owner` at the current block function balanceOf(address owner) public constant returns (uint256 balance); /// @notice Send `amount` tokens to `to` from `msg.sender` /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address to, uint256 amount) public returns (bool success); } contract IERC20Allowance { //////////////////////// // Events //////////////////////// event Approval( address indexed owner, address indexed spender, uint256 amount ); //////////////////////// // Public functions //////////////////////// /// @dev This function makes it easy to read the `allowed[]` map /// @param owner The address of the account that owns the token /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of owner that spender is allowed /// to spend function allowance(address owner, address spender) public constant returns (uint256 remaining); /// @notice `msg.sender` approves `spender` to spend `amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param spender The address of the account able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address spender, uint256 amount) public returns (bool success); /// @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 True if the transfer was successful function transferFrom(address from, address to, uint256 amount) public returns (bool success); } contract IERC20Token is IBasicToken, IERC20Allowance { } contract IERC677Callback { //////////////////////// // Public functions //////////////////////// // NOTE: This call can be initiated by anyone. You need to make sure that // it is send by the token (`require(msg.sender == token)`) or make sure // amount is valid (`require(token.allowance(this) >= amount)`). function receiveApproval( address from, uint256 amount, address token, // IERC667Token bytes data ) public returns (bool success); } contract IERC677Allowance is IERC20Allowance { //////////////////////// // Public functions //////////////////////// /// @notice `msg.sender` approves `spender` to send `amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param spender The address of the contract able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address spender, uint256 amount, bytes extraData) public returns (bool success); } contract IERC677Token is IERC20Token, IERC677Allowance { } contract Math { //////////////////////// // Internal functions //////////////////////// // absolute difference: |v1 - v2| function absDiff(uint256 v1, uint256 v2) internal pure returns(uint256) { return v1 > v2 ? v1 - v2 : v2 - v1; } // divide v by d, round up if remainder is 0.5 or more function divRound(uint256 v, uint256 d) internal pure returns(uint256) { return add(v, d/2) / d; } // computes decimal decimalFraction 'frac' of 'amount' with maximum precision (multiplication first) // both amount and decimalFraction must have 18 decimals precision, frac 10**18 represents a whole (100% of) amount // mind loss of precision as decimal fractions do not have finite binary expansion // do not use instead of division function decimalFraction(uint256 amount, uint256 frac) internal pure returns(uint256) { // it's like 1 ether is 100% proportion return proportion(amount, frac, 10**18); } // computes part/total of amount with maximum precision (multiplication first) // part and total must have the same units function proportion(uint256 amount, uint256 part, uint256 total) internal pure returns(uint256) { return divRound(mul(amount, part), total); } // // Open Zeppelin Math library below // function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } } /// @title internal token transfer function /// @dev see BasicSnapshotToken for implementation contract MTokenTransfer { //////////////////////// // Internal functions //////////////////////// /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @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 /// @dev reverts if transfer was not successful function mTransfer( address from, address to, uint256 amount ) internal; } /// @title controls token transfers /// @dev BasicSnapshotToken observes this interface, Neumark contract implements it contract MTokenTransferController { //////////////////////// // Internal functions //////////////////////// /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param from The origin of the transfer /// @param to The destination of the transfer /// @param amount The amount of the transfer /// @return False if the controller does not authorize the transfer function mOnTransfer( address from, address to, uint256 amount ) internal returns (bool allow); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is MTokenTransfer, MTokenTransferController, IBasicToken, Math { //////////////////////// // Mutable state //////////////////////// mapping(address => uint256) internal _balances; uint256 internal _totalSupply; //////////////////////// // Public functions //////////////////////// /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param amount The amount to be transferred. */ function transfer(address to, uint256 amount) public returns (bool) { mTransfer(msg.sender, to, amount); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint256) { return _totalSupply; } /** * @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 constant returns (uint256 balance) { return _balances[owner]; } //////////////////////// // Internal functions //////////////////////// // // Implements MTokenTransfer // function mTransfer(address from, address to, uint256 amount) internal { require(to != address(0)); require(mOnTransfer(from, to, amount)); _balances[from] = sub(_balances[from], amount); _balances[to] = add(_balances[to], amount); emit Transfer(from, to, amount); } } /// @title controls spending approvals /// @dev TokenAllowance observes this interface, Neumark contract implements it contract MTokenAllowanceController { //////////////////////// // Internal functions //////////////////////// /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param owner The address that calls `approve()` /// @param spender The spender in the `approve()` call /// @param amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function mOnApprove( address owner, address spender, uint256 amount ) internal returns (bool allow); /// @notice Allows to override allowance approved by the owner /// Primary role is to enable forced transfers, do not override if you do not like it /// Following behavior is expected in the observer /// approve() - should revert if mAllowanceOverride() > 0 /// allowance() - should return mAllowanceOverride() if set /// transferFrom() - should override allowance if mAllowanceOverride() > 0 /// @param owner An address giving allowance to spender /// @param spender An address getting a right to transfer allowance amount from the owner /// @return current allowance amount function mAllowanceOverride( address owner, address spender ) internal constant returns (uint256 allowance); } /// @title token spending approval and transfer /// @dev implements token approval and transfers and exposes relevant part of ERC20 and ERC677 approveAndCall /// may be mixed in with any basic token (implementing mTransfer) like BasicSnapshotToken or MintableSnapshotToken to add approval mechanism /// observes MTokenAllowanceController interface /// observes MTokenTransfer contract TokenAllowance is MTokenTransfer, MTokenAllowanceController, IERC20Allowance, IERC677Token { //////////////////////// // Mutable state //////////////////////// // `allowed` tracks rights to spends others tokens as per ERC20 // owner => spender => amount mapping (address => mapping (address => uint256)) private _allowed; //////////////////////// // Constructor //////////////////////// constructor() internal { } //////////////////////// // Public functions //////////////////////// // // Implements IERC20Token // /// @dev This function makes it easy to read the `allowed[]` map /// @param owner The address of the account that owns the token /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address owner, address spender) public constant returns (uint256 remaining) { uint256 override = mAllowanceOverride(owner, spender); if (override > 0) { return override; } return _allowed[owner][spender]; } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// where allowance per spender must be 0 to allow change of such allowance /// @param spender The address of the account able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True or reverts, False is never returned function approve(address spender, uint256 amount) public returns (bool success) { // Alerts the token controller of the approve function call require(mOnApprove(msg.sender, spender, amount)); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((amount == 0 || _allowed[msg.sender][spender] == 0) && mAllowanceOverride(msg.sender, spender) == 0); _allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, 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 True if the transfer was successful, reverts in any other case function transferFrom(address from, address to, uint256 amount) public returns (bool success) { uint256 allowed = mAllowanceOverride(from, msg.sender); if (allowed == 0) { // The standard ERC 20 transferFrom functionality allowed = _allowed[from][msg.sender]; // yes this will underflow but then we'll revert. will cost gas however so don't underflow _allowed[from][msg.sender] -= amount; } require(allowed >= amount); mTransfer(from, to, amount); return true; } // // Implements IERC677Token // /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param spender The address of the contract able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True or reverts, False is never returned function approveAndCall( address spender, uint256 amount, bytes extraData ) public returns (bool success) { require(approve(spender, amount)); success = IERC677Callback(spender).receiveApproval( msg.sender, amount, this, extraData ); require(success); return true; } //////////////////////// // Internal functions //////////////////////// // // Implements default MTokenAllowanceController // // no override in default implementation function mAllowanceOverride( address /*owner*/, address /*spender*/ ) internal constant returns (uint256) { return 0; } } /** * @title Standard ERC20 token * * @dev Implementation of the standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is IERC20Token, BasicToken, TokenAllowance { } /// @title uniquely identifies deployable (non-abstract) platform contract /// @notice cheap way of assigning implementations to knownInterfaces which represent system services /// unfortunatelly ERC165 does not include full public interface (ABI) and does not provide way to list implemented interfaces /// EIP820 still in the making /// @dev ids are generated as follows keccak256("neufund-platform:<contract name>") /// ids roughly correspond to ABIs contract IContractId { /// @param id defined as above /// @param version implementation version function contractId() public pure returns (bytes32 id, uint256 version); } /// @title current ERC223 fallback function /// @dev to be used in all future token contract /// @dev NEU and ICBMEtherToken (obsolete) are the only contracts that still uses IERC223LegacyCallback contract IERC223Callback { //////////////////////// // Public functions //////////////////////// function tokenFallback(address from, uint256 amount, bytes data) public; } contract IERC223Token is IERC20Token, ITokenMetadata { /// @dev Departure: We do not log data, it has no advantage over a standard /// log event. By sticking to the standard log event we /// stay compatible with constracts that expect and ERC20 token. // event Transfer( // address indexed from, // address indexed to, // uint256 amount, // bytes data); /// @dev Departure: We do not use the callback on regular transfer calls to /// stay compatible with constracts that expect and ERC20 token. // function transfer(address to, uint256 amount) // public // returns (bool); //////////////////////// // Public functions //////////////////////// function transfer(address to, uint256 amount, bytes data) public returns (bool); } /// @title granular token controller based on MSnapshotToken observer pattern contract ITokenController { //////////////////////// // Public functions //////////////////////// /// @notice see MTokenTransferController /// @dev additionally passes broker that is executing transaction between from and to /// for unbrokered transfer, broker == from function onTransfer(address broker, address from, address to, uint256 amount) public constant returns (bool allow); /// @notice see MTokenAllowanceController function onApprove(address owner, address spender, uint256 amount) public constant returns (bool allow); /// @notice see MTokenMint function onGenerateTokens(address sender, address owner, uint256 amount) public constant returns (bool allow); /// @notice see MTokenMint function onDestroyTokens(address sender, address owner, uint256 amount) public constant returns (bool allow); /// @notice controls if sender can change controller to newController /// @dev for this to succeed TYPICALLY current controller must be already migrated to a new one function onChangeTokenController(address sender, address newController) public constant returns (bool); /// @notice overrides spender allowance /// @dev may be used to implemented forced transfers in which token controller may override approved allowance /// with any > 0 value and then use transferFrom to execute such transfer /// This by definition creates non-trustless token so do not implement this call if you do not need trustless transfers! /// Implementer should not allow approve() to be executed if there is an overrride // Implemented should return allowance() taking into account override function onAllowance(address owner, address spender) public constant returns (uint256 allowanceOverride); } /// @title hooks token controller to token contract and allows to replace it contract ITokenControllerHook { //////////////////////// // Events //////////////////////// event LogChangeTokenController( address oldController, address newController, address by ); //////////////////////// // Public functions //////////////////////// /// @notice replace current token controller /// @dev please note that this process is also controlled by existing controller function changeTokenController(address newController) public; /// @notice returns current controller function tokenController() public constant returns (address currentController); } contract IWithdrawableToken { //////////////////////// // Public functions //////////////////////// /// @notice withdraws from a token holding assets /// @dev amount of asset should be returned to msg.sender and corresponding balance burned function withdraw(uint256 amount) public; } contract EuroToken is Agreement, IERC677Token, StandardToken, IWithdrawableToken, ITokenControllerHook, TokenMetadata, IERC223Token, IsContract, IContractId { //////////////////////// // Constants //////////////////////// string private constant NAME = "Euro Token"; string private constant SYMBOL = "EUR-T"; uint8 private constant DECIMALS = 18; //////////////////////// // Mutable state //////////////////////// ITokenController private _tokenController; //////////////////////// // Events //////////////////////// /// on each deposit (increase of supply) of EUR-T /// 'by' indicates account that executed the deposit function for 'to' (typically bank connector) event LogDeposit( address indexed to, address by, uint256 amount, bytes32 reference ); // proof of requested deposit initiated by token holder event LogWithdrawal( address indexed from, uint256 amount ); // proof of settled deposit event LogWithdrawSettled( address from, address by, // who settled uint256 amount, // settled amount, after fees, negative interest rates etc. uint256 originalAmount, // original amount withdrawn bytes32 withdrawTxHash, // hash of withdraw transaction bytes32 reference // reference number of withdraw operation at deposit manager ); /// on destroying the tokens without withdraw (see `destroyTokens` function below) event LogDestroy( address indexed from, address by, uint256 amount ); //////////////////////// // Modifiers //////////////////////// modifier onlyIfDepositAllowed(address to, uint256 amount) { require(_tokenController.onGenerateTokens(msg.sender, to, amount)); _; } modifier onlyIfWithdrawAllowed(address from, uint256 amount) { require(_tokenController.onDestroyTokens(msg.sender, from, amount)); _; } //////////////////////// // Constructor //////////////////////// constructor( IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter, ITokenController tokenController ) Agreement(accessPolicy, forkArbiter) StandardToken() TokenMetadata(NAME, DECIMALS, SYMBOL, "") public { require(tokenController != ITokenController(0x0)); _tokenController = tokenController; } //////////////////////// // Public functions //////////////////////// /// @notice deposit 'amount' of EUR-T to address 'to', attaching correlating `reference` to LogDeposit event /// @dev deposit may happen only in case 'to' can receive transfer in token controller /// by default KYC is required to receive deposits function deposit(address to, uint256 amount, bytes32 reference) public only(ROLE_EURT_DEPOSIT_MANAGER) onlyIfDepositAllowed(to, amount) acceptAgreement(to) { require(to != address(0)); _balances[to] = add(_balances[to], amount); _totalSupply = add(_totalSupply, amount); emit LogDeposit(to, msg.sender, amount, reference); emit Transfer(address(0), to, amount); } /// @notice runs many deposits within one transaction /// @dev deposit may happen only in case 'to' can receive transfer in token controller /// by default KYC is required to receive deposits function depositMany(address[] to, uint256[] amount, bytes32[] reference) public { require(to.length == amount.length); require(to.length == reference.length); for (uint256 i = 0; i < to.length; i++) { deposit(to[i], amount[i], reference[i]); } } /// @notice withdraws 'amount' of EUR-T by burning required amount and providing a proof of whithdrawal /// @dev proof is provided in form of log entry. based on that proof deposit manager will make a bank transfer /// by default controller will check the following: KYC and existence of working bank account function withdraw(uint256 amount) public onlyIfWithdrawAllowed(msg.sender, amount) acceptAgreement(msg.sender) { destroyTokensPrivate(msg.sender, amount); emit LogWithdrawal(msg.sender, amount); } /// @notice issued by deposit manager when withdraw request was settled. typicaly amount that could be settled will be lower /// than amount withdrawn: banks charge negative interest rates and various fees that must be deduced /// reference number is attached that may be used to identify withdraw operation at deposit manager function settleWithdraw(address from, uint256 amount, uint256 originalAmount, bytes32 withdrawTxHash, bytes32 reference) public only(ROLE_EURT_DEPOSIT_MANAGER) { emit LogWithdrawSettled(from, msg.sender, amount, originalAmount, withdrawTxHash, reference); } /// @notice this method allows to destroy EUR-T belonging to any account /// note that EURO is fiat currency and is not trustless, EUR-T is also /// just internal currency of Neufund platform, not general purpose stable coin /// we need to be able to destroy EUR-T if ordered by authorities function destroy(address owner, uint256 amount) public only(ROLE_EURT_LEGAL_MANAGER) { destroyTokensPrivate(owner, amount); emit LogDestroy(owner, msg.sender, amount); } // // Implements ITokenControllerHook // function changeTokenController(address newController) public { require(_tokenController.onChangeTokenController(msg.sender, newController)); _tokenController = ITokenController(newController); emit LogChangeTokenController(_tokenController, newController, msg.sender); } function tokenController() public constant returns (address) { return _tokenController; } // // Implements IERC223Token // function transfer(address to, uint256 amount, bytes data) public returns (bool success) { return ierc223TransferInternal(msg.sender, to, amount, data); } /// @notice convenience function to deposit and immediately transfer amount /// @param depositTo which account to deposit to and then transfer from /// @param transferTo where to transfer after deposit /// @param depositAmount amount to deposit /// @param transferAmount total amount to transfer, must be <= balance after deposit /// @dev intended to deposit from bank account and invest in ETO function depositAndTransfer( address depositTo, address transferTo, uint256 depositAmount, uint256 transferAmount, bytes data, bytes32 reference ) public returns (bool success) { deposit(depositTo, depositAmount, reference); return ierc223TransferInternal(depositTo, transferTo, transferAmount, data); } // // Implements IContractId // function contractId() public pure returns (bytes32 id, uint256 version) { return (0xfb5c7e43558c4f3f5a2d87885881c9b10ff4be37e3308579c178bf4eaa2c29cd, 0); } //////////////////////// // Internal functions //////////////////////// // // Implements MTokenController // function mOnTransfer( address from, address to, uint256 amount ) internal acceptAgreement(from) returns (bool allow) { address broker = msg.sender; if (broker != from) { // if called by the depositor (deposit and send), ignore the broker flag bool isDepositor = accessPolicy().allowed(msg.sender, ROLE_EURT_DEPOSIT_MANAGER, this, msg.sig); // this is not very clean but alternative (give brokerage rights to all depositors) is maintenance hell if (isDepositor) { broker = from; } } return _tokenController.onTransfer(broker, from, to, amount); } function mOnApprove( address owner, address spender, uint256 amount ) internal acceptAgreement(owner) returns (bool allow) { return _tokenController.onApprove(owner, spender, amount); } function mAllowanceOverride( address owner, address spender ) internal constant returns (uint256) { return _tokenController.onAllowance(owner, spender); } // // Observes MAgreement internal interface // /// @notice euro token is legally represented by separate entity ROLE_EURT_LEGAL_MANAGER function mCanAmend(address legalRepresentative) internal returns (bool) { return accessPolicy().allowed(legalRepresentative, ROLE_EURT_LEGAL_MANAGER, this, msg.sig); } //////////////////////// // Private functions //////////////////////// function destroyTokensPrivate(address owner, uint256 amount) private { require(_balances[owner] >= amount); _balances[owner] = sub(_balances[owner], amount); _totalSupply = sub(_totalSupply, amount); emit Transfer(owner, address(0), amount); } /// @notice internal transfer function that checks permissions and calls the tokenFallback function ierc223TransferInternal(address from, address to, uint256 amount, bytes data) private returns (bool success) { BasicToken.mTransfer(from, to, amount); // Notify the receiving contract. if (isContract(to)) { // in case of re-entry (1) transfer is done (2) msg.sender is different IERC223Callback(to).tokenFallback(from, amount, data); } return true; } }
This function makes it easy to get the total number of tokens return The total number of tokens
function totalSupply() public constant returns (uint256) { return _totalSupply; }
5,522,262
// SPDX-License-Identifier: MIT // File: contracts/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: contracts/IWhitelistable.sol /** * Author: Lambdalf the White * Edit : Squeebo */ pragma solidity 0.8.10; abstract contract IWhitelistable { // Errors error IWhitelistable_NOT_SET(); error IWhitelistable_CONSUMED(); error IWhitelistable_FORBIDDEN(); error IWhitelistable_NO_ALLOWANCE(); bytes32 private _root; mapping( address => uint256 ) private _consumed; modifier isWhitelisted( address account_, bytes32[] memory proof_, uint256 passMax_, uint256 qty_ ) { if ( qty_ > passMax_ ) { revert IWhitelistable_FORBIDDEN(); } uint256 _allowed_ = _checkWhitelistAllowance( account_, proof_, passMax_ ); if ( _allowed_ < qty_ ) { revert IWhitelistable_FORBIDDEN(); } _; } /** * @dev Sets the pass to protect the whitelist. */ function _setWhitelist( bytes32 root_ ) internal virtual { _root = root_; } /** * @dev Returns the amount that `account_` is allowed to access from the whitelist. * * Requirements: * * - `_root` must be set. * * See {IWhitelistable-_consumeWhitelist}. */ function _checkWhitelistAllowance( address account_, bytes32[] memory proof_, uint256 passMax_ ) internal view returns ( uint256 ) { if ( _root == 0 ) { revert IWhitelistable_NOT_SET(); } if ( _consumed[ account_ ] >= passMax_ ) { revert IWhitelistable_CONSUMED(); } if ( ! _computeProof( account_, proof_ ) ) { revert IWhitelistable_FORBIDDEN(); } uint256 _res_; unchecked { _res_ = passMax_ - _consumed[ account_ ]; } return _res_; } function _computeProof( address account_, bytes32[] memory proof_ ) private view returns ( bool ) { bytes32 leaf = keccak256(abi.encodePacked(account_)); return MerkleProof.processProof( proof_, leaf ) == _root; } /** * @dev Consumes `amount_` pass passes from `account_`. * * Note: Before calling this function, eligibility should be checked through {IWhitelistable-checkWhitelistAllowance}. */ function _consumeWhitelist( address account_, uint256 qty_ ) internal { unchecked { _consumed[ account_ ] += qty_; } } } // File: contracts/ITradable.sol /** * Author: Lambdalf the White */ pragma solidity 0.8.10; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping( address => OwnableDelegateProxy ) public proxies; } abstract contract ITradable { // OpenSea proxy registry address address[] internal _proxyRegistries; function _setProxyRegistry( address proxyRegistryAddress_ ) internal { _proxyRegistries.push( proxyRegistryAddress_ ); } /** * @dev Checks if `operator_` is the registered proxy for `tokenOwner_`. * * Note: Use this function to allow whitelisting of registered proxy. */ function _isRegisteredProxy( address tokenOwner_, address operator_ ) internal view returns ( bool ) { for ( uint256 i; i < _proxyRegistries.length; i++ ) { ProxyRegistry _proxyRegistry_ = ProxyRegistry( _proxyRegistries[ i ] ); if ( address( _proxyRegistry_.proxies( tokenOwner_ ) ) == operator_ ) { return true; } } return false; } } // File: contracts/IPausable.sol /** * Author: Lambdalf the White */ pragma solidity 0.8.10; abstract contract IPausable { // Errors error IPausable_SALE_NOT_CLOSED(); error IPausable_SALE_NOT_OPEN(); error IPausable_PRESALE_NOT_OPEN(); // Enum to represent the sale state, defaults to ``CLOSED``. enum SaleState { CLOSED, PRESALE, SALE } // The current state of the contract SaleState public saleState; /** * @dev Emitted when the sale state changes */ event SaleStateChanged( SaleState indexed previousState, SaleState indexed newState ); /** * @dev Sale state can have one of 3 values, ``CLOSED``, ``PRESALE``, or ``SALE``. */ function _setSaleState( SaleState newState_ ) internal virtual { SaleState _previousState_ = saleState; saleState = newState_; emit SaleStateChanged( _previousState_, newState_ ); } /** * @dev Throws if sale state is not ``CLOSED``. */ modifier saleClosed { if ( saleState != SaleState.CLOSED ) { revert IPausable_SALE_NOT_CLOSED(); } _; } /** * @dev Throws if sale state is not ``SALE``. */ modifier saleOpen { if ( saleState != SaleState.SALE ) { revert IPausable_SALE_NOT_OPEN(); } _; } /** * @dev Throws if sale state is not ``PRESALE``. */ modifier presaleOpen { if ( saleState != SaleState.PRESALE ) { revert IPausable_PRESALE_NOT_OPEN(); } _; } } // File: contracts/IOwnable.sol /** * Author: Lambdalf the White */ pragma solidity 0.8.10; /** * @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 IOwnable { // Errors error IOwnable_NOT_OWNER(); // The owner of the contract address private _owner; /** * @dev Emitted when contract ownership changes. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function _initIOwnable( address owner_ ) internal { _owner = owner_; } /** * @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() { if ( owner() != msg.sender ) { revert IOwnable_NOT_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 { address _oldOwner_ = _owner; _owner = newOwner_; emit OwnershipTransferred( _oldOwner_, newOwner_ ); } } // File: contracts/IERC2981.sol pragma solidity 0.8.10; interface IERC2981 { /** * @dev ERC165 bytes to add to interface array - set in parent contract * implementing this standard * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; * _registerInterface(_INTERFACE_ID_ERC2981); * * @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 _salePrice - 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 _salePrice */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: contracts/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: contracts/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: contracts/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity 0.8.10; /** * @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/ERC2981Base.sol /** * Author: Lambdalf the White */ pragma solidity 0.8.10; abstract contract ERC2981Base is IERC165, IERC2981 { // Errors error IERC2981_INVALID_ROYALTIES(); // Royalty rate is stored out of 10,000 instead of a percentage to allow for // up to two digits below the unit such as 2.5% or 1.25%. uint private constant ROYALTY_BASE = 10000; // Represents the percentage of royalties on each sale on secondary markets. // Set to 0 to have no royalties. uint256 private _royaltyRate; // Address of the recipient of the royalties. address private _royaltyRecipient; function _initERC2981Base( address royaltyRecipient_, uint256 royaltyRate_ ) internal { _setRoyaltyInfo( royaltyRecipient_, royaltyRate_ ); } /** * @dev See {IERC2981-royaltyInfo}. * * Note: This function should be overriden to revert on a query for non existent token. */ function royaltyInfo( uint256, uint256 salePrice_ ) public view virtual override returns ( address, uint256 ) { if ( salePrice_ == 0 || _royaltyRate == 0 ) { return ( _royaltyRecipient, 0 ); } uint256 _royaltyAmount_ = _royaltyRate * salePrice_ / ROYALTY_BASE; return ( _royaltyRecipient, _royaltyAmount_ ); } /** * @dev Sets the royalty rate to `royaltyRate_` and the royalty recipient to `royaltyRecipient_`. * * Requirements: * * - `royaltyRate_` cannot be higher than `ROYALTY_BASE`; */ function _setRoyaltyInfo( address royaltyRecipient_, uint256 royaltyRate_ ) internal virtual { if ( royaltyRate_ > ROYALTY_BASE ) { revert IERC2981_INVALID_ROYALTIES(); } _royaltyRate = royaltyRate_; _royaltyRecipient = royaltyRecipient_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId_ ) public view virtual override returns ( bool ) { return interfaceId_ == type( IERC2981 ).interfaceId || interfaceId_ == type( IERC165 ).interfaceId; } } // File: contracts/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: contracts/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/ERC721Batch.sol /** * Author: Lambdalf the White */ pragma solidity 0.8.10; /** * @dev Required interface of an ERC721 compliant contract. */ abstract contract ERC721Batch is Context, IERC721Metadata { // Errors error IERC721_APPROVE_OWNER(); error IERC721_APPROVE_CALLER(); error IERC721_CALLER_NOT_APPROVED(); error IERC721_NONEXISTANT_TOKEN(); error IERC721_NON_ERC721_RECEIVER(); error IERC721_NULL_ADDRESS_BALANCE(); error IERC721_NULL_ADDRESS_TRANSFER(); // Token name string private _name; // Token symbol string private _symbol; // Token Base URI string private _baseURI; // Token IDs uint256 private _numTokens; // List of owner addresses mapping( uint256 => address ) private _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 Ensures the token exist. * A token exists if it has been minted and is not owned by the null address. * * @param tokenId_ uint256 ID of the token to verify */ modifier exists( uint256 tokenId_ ) { if ( ! _exists( tokenId_ ) ) { revert IERC721_NONEXISTANT_TOKEN(); } _; } // ************************************** // ***** INTERNAL ***** // ************************************** /** * @dev Internal function returning the number of tokens in `tokenOwner_`'s account. */ function _balanceOf( address tokenOwner_ ) internal view virtual returns ( uint256 ) { if ( tokenOwner_ == address( 0 ) ) { return 0; } uint256 _supplyMinted_ = _supplyMinted(); uint256 _count_ = 0; address _currentTokenOwner_; for ( uint256 i; i < _supplyMinted_; i++ ) { if ( _owners[ i ] != address( 0 ) ) { _currentTokenOwner_ = _owners[ i ]; } if ( tokenOwner_ == _currentTokenOwner_ ) { _count_++; } } return _count_; } /** * @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_ ) internal virtual 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. // // IMPORTANT // It is unsafe to assume that an address not flagged by this method // is an externally-owned account (EOA) and not a contract. // // Among others, the following types of addresses will not be flagged: // // - 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 uint256 _size_; assembly { _size_ := extcodesize( to_ ) } // If address is a contract, check that it is aware of how to handle ERC721 tokens if ( _size_ > 0 ) { 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 IERC721_NON_ERC721_RECEIVER(); } else { assembly { revert( add( 32, reason ), mload( reason ) ) } } } } else { return true; } } /** * @dev Internal function returning whether a token exists. * A token exists if it has been minted and is not owned by the null address. * * @param tokenId_ uint256 ID of the token to verify * * @return bool whether the token exists */ function _exists( uint256 tokenId_ ) internal view virtual returns ( bool ) { return tokenId_ < _numTokens; } /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function _initERC721BatchMetadata( string memory name_, string memory symbol_ ) internal { _name = name_; _symbol = symbol_; } /** * @dev Internal function returning whether `operator_` is allowed * to manage tokens on behalf of `tokenOwner_`. * * @param tokenOwner_ address that owns tokens * @param operator_ address that tries to manage tokens * * @return bool whether `operator_` is allowed to handle the token */ function _isApprovedForAll( address tokenOwner_, address operator_ ) internal view virtual returns ( bool ) { return _operatorApprovals[ tokenOwner_ ][ operator_ ]; } /** * @dev Internal function returning whether `operator_` is allowed to handle `tokenId_` * * Note: To avoid multiple checks for the same data, it is assumed that existence of `tokeId_` * has been verified prior via {_exists} * If it hasn't been verified, this function might panic * * @param operator_ address that tries to handle the token * @param tokenId_ uint256 ID of the token to be handled * * @return bool whether `operator_` is allowed to handle the token */ function _isApprovedOrOwner( address tokenOwner_, address operator_, uint256 tokenId_ ) internal view virtual returns ( bool ) { bool _isApproved_ = operator_ == tokenOwner_ || operator_ == _tokenApprovals[ tokenId_ ] || _isApprovedForAll( tokenOwner_, operator_ ); return _isApproved_; } /** * @dev Mints `qty_` tokens and transfers them to `to_`. * * This internal function can be used to perform token minting. * * Emits a {ConsecutiveTransfer} event. */ function _mint( address to_, uint256 qty_ ) internal virtual { uint256 _firstToken_ = _numTokens; uint256 _lastToken_ = _firstToken_ + qty_ - 1; _owners[ _firstToken_ ] = to_; if ( _lastToken_ > _firstToken_ ) { _owners[ _lastToken_ ] = to_; } for ( uint256 i; i < qty_; i ++ ) { emit Transfer( address( 0 ), to_, _firstToken_ + i ); } _numTokens = _lastToken_ + 1; } /** * @dev Internal function returning the owner of the `tokenId_` token. * * @param tokenId_ uint256 ID of the token to verify * * @return address the address of the token owner */ function _ownerOf( uint256 tokenId_ ) internal view virtual returns ( address ) { uint256 _tokenId_ = tokenId_; address _tokenOwner_ = _owners[ _tokenId_ ]; while ( _tokenOwner_ == address( 0 ) ) { _tokenId_ --; _tokenOwner_ = _owners[ _tokenId_ ]; } return _tokenOwner_; } /** * @dev Internal function used to set the base URI of the collection. */ function _setBaseURI( string memory baseURI_ ) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function returning the total number of tokens minted * * @return uint256 the number of tokens that have been minted so far */ function _supplyMinted() internal view virtual returns ( uint256 ) { return _numTokens; } /** * @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 Transfers `tokenId_` from `from_` to `to_`. * * This internal function can be used to implement alternative mechanisms to perform * token transfer, such as signature-based, or token burning. * * Emits a {Transfer} event. */ function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual { _tokenApprovals[ tokenId_ ] = address( 0 ); uint256 _previousId_ = tokenId_ > 0 ? tokenId_ - 1 : 0; uint256 _nextId_ = tokenId_ + 1; bool _previousShouldUpdate_ = _previousId_ < tokenId_ && _exists( _previousId_ ) && _owners[ _previousId_ ] == address( 0 ); bool _nextShouldUpdate_ = _exists( _nextId_ ) && _owners[ _nextId_ ] == address( 0 ); if ( _previousShouldUpdate_ ) { _owners[ _previousId_ ] = from_; } if ( _nextShouldUpdate_ ) { _owners[ _nextId_ ] = from_; } _owners[ tokenId_ ] = to_; emit Transfer( from_, to_, tokenId_ ); } // ************************************** // ***** PUBLIC ***** // ************************************** /** * @dev See {IERC721-approve}. */ function approve( address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) { address _operator_ = _msgSender(); address _tokenOwner_ = _ownerOf( tokenId_ ); bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ ); if ( ! _isApproved_ ) { revert IERC721_CALLER_NOT_APPROVED(); } if ( to_ == _tokenOwner_ ) { revert IERC721_APPROVE_OWNER(); } _tokenApprovals[ tokenId_ ] = to_; emit Approval( _tokenOwner_, to_, tokenId_ ); } /** * @dev See {IERC721-safeTransferFrom}. * * Note: We can ignore `from_` as we can compare everything to the actual token owner, * but we cannot remove this parameter to stay in conformity with IERC721 */ function safeTransferFrom( address, address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) { address _operator_ = _msgSender(); address _tokenOwner_ = _ownerOf( tokenId_ ); bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ ); if ( ! _isApproved_ ) { revert IERC721_CALLER_NOT_APPROVED(); } if ( to_ == address( 0 ) ) { revert IERC721_NULL_ADDRESS_TRANSFER(); } _transfer( _tokenOwner_, to_, tokenId_ ); if ( ! _checkOnERC721Received( _tokenOwner_, to_, tokenId_, "" ) ) { revert IERC721_NON_ERC721_RECEIVER(); } } /** * @dev See {IERC721-safeTransferFrom}. * * Note: We can ignore `from_` as we can compare everything to the actual token owner, * but we cannot remove this parameter to stay in conformity with IERC721 */ function safeTransferFrom( address, address to_, uint256 tokenId_, bytes calldata data_ ) external virtual exists( tokenId_ ) { address _operator_ = _msgSender(); address _tokenOwner_ = _ownerOf( tokenId_ ); bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ ); if ( ! _isApproved_ ) { revert IERC721_CALLER_NOT_APPROVED(); } if ( to_ == address( 0 ) ) { revert IERC721_NULL_ADDRESS_TRANSFER(); } _transfer( _tokenOwner_, to_, tokenId_ ); if ( ! _checkOnERC721Received( _tokenOwner_, to_, tokenId_, data_ ) ) { revert IERC721_NON_ERC721_RECEIVER(); } } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll( address operator_, bool approved_ ) public virtual override { address _account_ = _msgSender(); if ( operator_ == _account_ ) { revert IERC721_APPROVE_CALLER(); } _operatorApprovals[ _account_ ][ operator_ ] = approved_; emit ApprovalForAll( _account_, operator_, approved_ ); } /** * @dev See {IERC721-transferFrom}. * * Note: We can ignore `from_` as we can compare everything to the actual token owner, * but we cannot remove this parameter to stay in conformity with IERC721 */ function transferFrom( address, address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) { address _operator_ = _msgSender(); address _tokenOwner_ = _ownerOf( tokenId_ ); bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ ); if ( ! _isApproved_ ) { revert IERC721_CALLER_NOT_APPROVED(); } if ( to_ == address( 0 ) ) { revert IERC721_NULL_ADDRESS_TRANSFER(); } _transfer( _tokenOwner_, to_, tokenId_ ); } // ************************************** // ***** VIEW ***** // ************************************** /** * @dev Returns the number of tokens in `tokenOwner_`'s account. */ function balanceOf( address tokenOwner_ ) external view virtual returns ( uint256 ) { return _balanceOf( tokenOwner_ ); } /** * @dev Returns the account approved for `tokenId_` token. * * Requirements: * * - `tokenId_` must exist. */ function getApproved( uint256 tokenId_ ) external view virtual exists( tokenId_ ) returns ( address ) { return _tokenApprovals[ tokenId_ ]; } /** * @dev Returns if the `operator_` is allowed to manage all of the assets of `tokenOwner_`. * * See {setApprovalForAll} */ function isApprovedForAll( address tokenOwner_, address operator_ ) external view virtual returns ( bool ) { return _isApprovedForAll( tokenOwner_, operator_ ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns ( string memory ) { return _name; } /** * @dev Returns the owner of the `tokenId_` token. * * Requirements: * * - `tokenId_` must exist. */ function ownerOf( uint256 tokenId_ ) external view virtual exists( tokenId_ ) returns ( address ) { return _ownerOf( tokenId_ ); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId_ ) public view virtual override returns ( bool ) { return interfaceId_ == type( IERC721Metadata ).interfaceId || interfaceId_ == type( IERC721 ).interfaceId || interfaceId_ == type( IERC165 ).interfaceId; } /** * @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 exists( tokenId_ ) returns ( string memory ) { return bytes( _baseURI ).length > 0 ? string( abi.encodePacked( _baseURI, _toString( tokenId_ ) ) ) : _toString( tokenId_ ); } } // File: contracts/ERC721BatchStakable.sol /** * Author: Lambdalf the White */ pragma solidity 0.8.10; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension and the Enumerable extension. * * Note: This implementation is only compatible with a sequential order of tokens minted. * If you need to mint tokens in a random order, you will need to override the following functions: * Note also that this implementations is fairly inefficient and as such, * those functions should be avoided inside non-view functions. */ abstract contract ERC721BatchStakable is ERC721Batch, IERC721Receiver { // Mapping of tokenId to stakeholder address mapping( uint256 => address ) internal _stakedOwners; // ************************************** // ***** INTERNAL ***** // ************************************** /** * @dev Internal function returning the number of tokens staked by `tokenOwner_`. */ function _balanceOfStaked( address tokenOwner_ ) internal view virtual returns ( uint256 ) { if ( tokenOwner_ == address( 0 ) ) { return 0; } uint256 _supplyMinted_ = _supplyMinted(); uint256 _count_ = 0; for ( uint256 i; i < _supplyMinted_; i++ ) { if ( _stakedOwners[ i ] == tokenOwner_ ) { _count_++; } } return _count_; } /** * @dev Internal function that mints `qtyMinted_` tokens and stakes `qtyStaked_` of them to the count of `tokenOwner_`. */ function _mintAndStake( address tokenOwner_, uint256 qtyMinted_, uint256 qtyStaked_ ) internal { uint256 _qtyNotStaked_; uint256 _qtyStaked_ = qtyStaked_; if ( qtyStaked_ > qtyMinted_ ) { _qtyStaked_ = qtyMinted_; } else if ( qtyStaked_ < qtyMinted_ ) { _qtyNotStaked_ = qtyMinted_ - qtyStaked_; } if ( _qtyStaked_ > 0 ) { _mintInContract( tokenOwner_, _qtyStaked_ ); } if ( _qtyNotStaked_ > 0 ) { _mint( tokenOwner_, _qtyNotStaked_ ); } } /** * @dev Internal function that mints `qtyStaked_` tokens and stakes them to the count of `tokenOwner_`. */ function _mintInContract( address tokenOwner_, uint256 qtyStaked_ ) internal { uint256 _currentToken_ = _supplyMinted(); uint256 _lastToken_ = _currentToken_ + qtyStaked_ - 1; while ( _currentToken_ <= _lastToken_ ) { _stakedOwners[ _currentToken_ ] = tokenOwner_; _currentToken_ ++; } _mint( address( this ), qtyStaked_ ); } /** * @dev Internal function returning the owner of the staked token number `tokenId_`. * * Requirements: * * - `tokenId_` must exist. */ function _ownerOfStaked( uint256 tokenId_ ) internal view virtual returns ( address ) { return _stakedOwners[ tokenId_ ]; } /** * @dev Internal function that stakes the token number `tokenId_` to the count of `tokenOwner_`. */ function _stake( address tokenOwner_, uint256 tokenId_ ) internal { _stakedOwners[ tokenId_ ] = tokenOwner_; _transfer( tokenOwner_, address( this ), tokenId_ ); } /** * @dev Internal function that unstakes the token `tokenId_` and transfers it back to `tokenOwner_`. */ function _unstake( address tokenOwner_, uint256 tokenId_ ) internal { _transfer( address( this ), tokenOwner_, tokenId_ ); delete _stakedOwners[ tokenId_ ]; } // ************************************** // ************************************** // ***** PUBLIC ***** // ************************************** /** * @dev Stakes the token `tokenId_` to the count of its owner. * * Requirements: * * - Caller must be allowed to manage `tokenId_` or its owner's tokens. * - `tokenId_` must exist. */ function stake( uint256 tokenId_ ) external exists( tokenId_ ) { address _operator_ = _msgSender(); address _tokenOwner_ = _ownerOf( tokenId_ ); bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ ); if ( ! _isApproved_ ) { revert IERC721_CALLER_NOT_APPROVED(); } _stake( _tokenOwner_, tokenId_ ); } /** * @dev Unstakes the token `tokenId_` and returns it to its owner. * * Requirements: * * - Caller must be allowed to manage `tokenId_` or its owner's tokens. * - `tokenId_` must exist. */ function unstake( uint256 tokenId_ ) external exists( tokenId_ ) { address _operator_ = _msgSender(); address _tokenOwner_ = _ownerOfStaked( tokenId_ ); bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ ); if ( ! _isApproved_ ) { revert IERC721_CALLER_NOT_APPROVED(); } _unstake( _tokenOwner_, tokenId_ ); } // ************************************** // ************************************** // ***** VIEW ***** // ************************************** /** * @dev Returns the number of tokens owned by `tokenOwner_`. */ function balanceOf( address tokenOwner_ ) public view virtual override returns ( uint256 balance ) { return _balanceOfStaked( tokenOwner_ ) + _balanceOf( tokenOwner_ ); } /** * @dev Returns the number of tokens staked by `tokenOwner_`. */ function balanceOfStaked( address tokenOwner_ ) public view virtual returns ( uint256 ) { return _balanceOfStaked( tokenOwner_ ); } /** * @dev Returns the owner of token number `tokenId_`. * * Requirements: * * - `tokenId_` must exist. */ function ownerOf( uint256 tokenId_ ) public view virtual override exists( tokenId_ ) returns ( address ) { address _tokenOwner_ = _ownerOf( tokenId_ ); if ( _tokenOwner_ == address( this ) ) { return _ownerOfStaked( tokenId_ ); } return _tokenOwner_; } /** * @dev Returns the owner of staked token number `tokenId_`. * * Requirements: * * - `tokenId_` must exist. */ function ownerOfStaked( uint256 tokenId_ ) public view virtual exists( tokenId_ ) returns ( address ) { return _ownerOfStaked( tokenId_ ); } // ************************************** // ************************************** // ***** PURE ***** // ************************************** /** * @dev Signals that this contract knows how to handle ERC721 tokens. */ function onERC721Received( address, address, uint256, bytes memory ) public override pure returns ( bytes4 ) { return type( IERC721Receiver ).interfaceId; } // ************************************** } // File: contracts/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) 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); /** * @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: contracts/ERC721BatchEnumerable.sol /** * Author: Lambdalf the White */ pragma solidity 0.8.10; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension and the Enumerable extension. * * Note: This implementation is only compatible with a sequential order of tokens minted. * If you need to mint tokens in a random order, you will need to override the following functions: * Note also that this implementations is fairly inefficient and as such, * those functions should be avoided inside non-view functions. */ abstract contract ERC721BatchEnumerable is ERC721Batch, IERC721Enumerable { // Errors error IERC721Enumerable_OWNER_INDEX_OUT_OF_BOUNDS(); error IERC721Enumerable_INDEX_OUT_OF_BOUNDS(); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId_ ) public view virtual override(IERC165, ERC721Batch) returns ( bool ) { return interfaceId_ == type( IERC721Enumerable ).interfaceId || super.supportsInterface( interfaceId_ ); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex( uint256 index_ ) public view virtual override returns ( uint256 ) { if ( index_ >= _supplyMinted() ) { revert IERC721Enumerable_INDEX_OUT_OF_BOUNDS(); } return index_; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex( address tokenOwner_, uint256 index_ ) public view virtual override returns ( uint256 tokenId ) { uint256 _supplyMinted_ = _supplyMinted(); if ( index_ >= _balanceOf( tokenOwner_ ) ) { revert IERC721Enumerable_OWNER_INDEX_OUT_OF_BOUNDS(); } uint256 _count_ = 0; for ( uint256 i = 0; i < _supplyMinted_; i++ ) { if ( _exists( i ) && tokenOwner_ == _ownerOf( i ) ) { if ( index_ == _count_ ) { return i; } _count_++; } } } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns ( uint256 ) { uint256 _supplyMinted_ = _supplyMinted(); uint256 _count_ = 0; for ( uint256 i; i < _supplyMinted_; i++ ) { if ( _exists( i ) ) { _count_++; } } return _count_; } } // File: contracts/CCFoundersKeys.sol /** * Author: Lambdalf the White */ pragma solidity 0.8.10; contract CCFoundersKeys is ERC721BatchEnumerable, ERC721BatchStakable, ERC2981Base, IOwnable, IPausable, ITradable, IWhitelistable { // Events event PaymentReleased( address indexed from, address[] indexed tos, uint256[] indexed amounts ); // Errors error CCFoundersKeys_ARRAY_LENGTH_MISMATCH(); error CCFoundersKeys_FORBIDDEN(); error CCFoundersKeys_INCORRECT_PRICE(); error CCFoundersKeys_INSUFFICIENT_KEY_BALANCE(); error CCFoundersKeys_MAX_BATCH(); error CCFoundersKeys_MAX_RESERVE(); error CCFoundersKeys_MAX_SUPPLY(); error CCFoundersKeys_NO_ETHER_BALANCE(); error CCFoundersKeys_TRANSFER_FAIL(); // Founders Key whitelist mint price uint public immutable WL_MINT_PRICE; // = 0.069 ether; // Founders Key public mint price uint public immutable PUBLIC_MINT_PRICE; // = 0.1 ether; // Max supply uint public immutable MAX_SUPPLY; // Max TX uint public immutable MAX_BATCH; // 2C Safe wallet ~ 90% address private immutable _CC_SAFE; // 2C Operations wallet ~ 5% address private immutable _CC_CHARITY; // 2C Founders wallet ~ 2.5% address private immutable _CC_FOUNDERS; // 2C Community wallet ~ 2.5% address private immutable _CC_COMMUNITY; // Mapping of Anon holders to amount of free key claimable mapping( address => uint256 ) public anonClaimList; uint256 private _reserve; constructor( uint256 reserve_, uint256 maxBatch_, uint256 maxSupply_, uint256 royaltyRate_, uint256 wlMintPrice_, uint256 publicMintPrice_, string memory name_, string memory symbol_, string memory baseURI_, // address devAddress_, address[] memory wallets_ ) { address _contractOwner_ = _msgSender(); _initIOwnable( _contractOwner_ ); _initERC2981Base( _contractOwner_, royaltyRate_ ); _initERC721BatchMetadata( name_, symbol_ ); _setBaseURI( baseURI_ ); _CC_SAFE = wallets_[ 0 ]; _CC_CHARITY = wallets_[ 1 ]; _CC_FOUNDERS = wallets_[ 2 ]; _CC_COMMUNITY = wallets_[ 3 ]; _reserve = reserve_; MAX_BATCH = maxBatch_; MAX_SUPPLY = maxSupply_; WL_MINT_PRICE = wlMintPrice_; PUBLIC_MINT_PRICE = publicMintPrice_; // _mintAndStake( devAddress_, 5 ); } // ************************************** // ***** INTERNAL ***** // ************************************** /** * @dev Internal function returning whether `operator_` is allowed to manage tokens on behalf of `tokenOwner_`. * * @param tokenOwner_ address that owns tokens * @param operator_ address that tries to manage tokens * * @return bool whether `operator_` is allowed to manage the token */ function _isApprovedForAll( address tokenOwner_, address operator_ ) internal view virtual override returns ( bool ) { return _isRegisteredProxy( tokenOwner_, operator_ ) || super._isApprovedForAll( tokenOwner_, operator_ ); } /** * @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 { if ( address( this ).balance < amount_ ) { revert CCFoundersKeys_INCORRECT_PRICE(); } ( bool _success_, ) = recipient_.call{ value: amount_ }( "" ); if ( ! _success_ ) { revert CCFoundersKeys_TRANSFER_FAIL(); } } // ************************************** // ************************************** // ***** PUBLIC ***** // ************************************** /** * @dev Mints `qty_` tokens and transfers them to the caller. * * Requirements: * * - Sale state must be {SaleState.PRESALE}. * - There must be enough tokens left to mint outside of the reserve. * - Caller must be whitelisted. */ function claim( uint256 qty_ ) external presaleOpen { address _account_ = _msgSender(); if ( qty_ > anonClaimList[ _account_ ] ) { revert CCFoundersKeys_FORBIDDEN(); } uint256 _endSupply_ = _supplyMinted() + qty_; if ( _endSupply_ > MAX_SUPPLY - _reserve ) { revert CCFoundersKeys_MAX_SUPPLY(); } unchecked { anonClaimList[ _account_ ] -= qty_; } _mint( _account_, qty_ ); } /** * @dev Mints `qty_` tokens, stakes `qtyStaked_` of them to the count of the caller, and transfers the remaining to them. * * Requirements: * * - Sale state must be {SaleState.PRESALE}. * - There must be enough tokens left to mint outside of the reserve. * - Caller must be whitelisted. * - If `qtyStaked_` is higher than `qty_`, only `qty_` tokens are staked. */ function claimAndStake( uint256 qty_, uint256 qtyStaked_ ) external presaleOpen { address _account_ = _msgSender(); if ( qty_ > anonClaimList[ _account_ ] ) { revert CCFoundersKeys_FORBIDDEN(); } uint256 _endSupply_ = _supplyMinted() + qty_; if ( _endSupply_ > MAX_SUPPLY - _reserve ) { revert CCFoundersKeys_MAX_SUPPLY(); } unchecked { anonClaimList[ _account_ ] -= qty_; } _mintAndStake( _account_, qty_, qtyStaked_ ); } /** * @dev Mints a token and transfers it to the caller. * * Requirements: * * - Sale state must be {SaleState.PRESALE}. * - There must be enough tokens left to mint outside of the reserve. * - Caller must send enough ether to pay for 1 token at presale price. * - Caller must be whitelisted. */ function mintPreSale( bytes32[] memory proof_ ) external payable presaleOpen isWhitelisted( _msgSender(), proof_, 1, 1 ) { if ( _supplyMinted() + 1 > MAX_SUPPLY - _reserve ) { revert CCFoundersKeys_MAX_SUPPLY(); } if ( WL_MINT_PRICE != msg.value ) { revert CCFoundersKeys_INCORRECT_PRICE(); } address _account_ = _msgSender(); _consumeWhitelist( _account_, 1 ); _mint( _account_, 1 ); } /** * @dev Mints a token and stakes it to the count of the caller. * * Requirements: * * - Sale state must be {SaleState.PRESALE}. * - There must be enough tokens left to mint outside of the reserve. * - Caller must send enough ether to pay for 1 token at presale price. * - Caller must be whitelisted. */ function mintPreSaleAndStake( bytes32[] memory proof_ ) external payable presaleOpen isWhitelisted( _msgSender(), proof_, 1, 1 ) { if ( _supplyMinted() + 1 > MAX_SUPPLY - _reserve ) { revert CCFoundersKeys_MAX_SUPPLY(); } if ( WL_MINT_PRICE != msg.value ) { revert CCFoundersKeys_INCORRECT_PRICE(); } address _account_ = _msgSender(); _consumeWhitelist( _account_, 1 ); _mintAndStake( _account_, 1, 1 ); } /** * @dev Mints `qty_` tokens and transfers them to the caller. * * Requirements: * * - Sale state must be {SaleState.SALE}. * - There must be enough tokens left to mint outside of the reserve. * - Caller must send enough ether to pay for `qty_` tokens at public sale price. */ function mint( uint256 qty_ ) external payable saleOpen { if ( qty_ > MAX_BATCH ) { revert CCFoundersKeys_MAX_BATCH(); } uint256 _endSupply_ = _supplyMinted() + qty_; if ( _endSupply_ > MAX_SUPPLY - _reserve ) { revert CCFoundersKeys_MAX_SUPPLY(); } if ( qty_ * PUBLIC_MINT_PRICE != msg.value ) { revert CCFoundersKeys_INCORRECT_PRICE(); } address _account_ = _msgSender(); _mint( _account_, qty_ ); } /** * @dev Mints `qty_` tokens, stakes `qtyStaked_` of them to the count of the caller, and transfers the remaining to them. * * Requirements: * * - Sale state must be {SaleState.SALE}. * - There must be enough tokens left to mint outside of the reserve. * - Caller must send enough ether to pay for `qty_` tokens at public sale price. * - If `qtyStaked_` is higher than `qty_`, only `qty_` tokens are staked. */ function mintAndStake( uint256 qty_, uint256 qtyStaked_ ) external payable saleOpen { if ( qty_ > MAX_BATCH ) { revert CCFoundersKeys_MAX_BATCH(); } uint256 _endSupply_ = _supplyMinted() + qty_; if ( _endSupply_ > MAX_SUPPLY - _reserve ) { revert CCFoundersKeys_MAX_SUPPLY(); } if ( qty_ * PUBLIC_MINT_PRICE != msg.value ) { revert CCFoundersKeys_INCORRECT_PRICE(); } address _account_ = _msgSender(); _mintAndStake( _account_, qty_, qtyStaked_ ); } // ************************************** // ************************************** // ***** CONTRACT_OWNER ***** // ************************************** /** * @dev Mints `amounts_` tokens and transfers them to `accounts_`. * * Requirements: * * - Caller must be the contract owner. * - `accounts_` and `amounts_` must have the same length. * - There must be enough tokens left in the reserve. */ function airdrop( address[] memory accounts_, uint256[] memory amounts_ ) external onlyOwner { uint256 _len_ = amounts_.length; if ( _len_ != accounts_.length ) { revert CCFoundersKeys_ARRAY_LENGTH_MISMATCH(); } uint _totalQty_; for ( uint256 i = _len_; i > 0; i -- ) { _totalQty_ += amounts_[ i - 1 ]; } if ( _totalQty_ > _reserve ) { revert CCFoundersKeys_MAX_RESERVE(); } unchecked { _reserve -= _totalQty_; } for ( uint256 i = _len_; i > 0; i -- ) { _mint( accounts_[ i - 1], amounts_[ i - 1] ); } } /** * @dev Saves `accounts_` in the anon claim list. * * Requirements: * * - Caller must be the contract owner. * - Sale state must be {SaleState.CLOSED}. * - `accounts_` and `amounts_` must have the same length. */ function setAnonClaimList( address[] memory accounts_, uint256[] memory amounts_ ) external onlyOwner saleClosed { uint256 _len_ = amounts_.length; if ( _len_ != accounts_.length ) { revert CCFoundersKeys_ARRAY_LENGTH_MISMATCH(); } for ( uint256 i; i < _len_; i ++ ) { anonClaimList[ accounts_[ i ] ] = amounts_[ i ]; } } /** * @dev See {ITradable-setProxyRegistry}. * * Requirements: * * - Caller must be the contract owner. */ function setProxyRegistry( address proxyRegistryAddress_ ) external onlyOwner { _setProxyRegistry( proxyRegistryAddress_ ); } /** * @dev Updates the royalty recipient and rate. * * Requirements: * * - Caller must be the contract owner. */ function setRoyaltyInfo( address royaltyRecipient_, uint256 royaltyRate_ ) external onlyOwner { _setRoyaltyInfo( royaltyRecipient_, royaltyRate_ ); } /** * @dev See {IPausable-setSaleState}. * * Requirements: * * - Caller must be the contract owner. */ function setSaleState( SaleState newState_ ) external onlyOwner { _setSaleState( newState_ ); } /** * @dev See {IWhitelistable-setWhitelist}. * * Requirements: * * - Caller must be the contract owner. * - Sale state must be {SaleState.CLOSED}. */ function setWhitelist( bytes32 root_ ) external onlyOwner saleClosed { _setWhitelist( root_ ); } /** * @dev Withdraws all the money stored in the contract and splits it amongst the set wallets. * * Requirements: * * - Caller must be the contract owner. */ function withdraw() external onlyOwner { uint256 _balance_ = address(this).balance; if ( _balance_ == 0 ) { revert CCFoundersKeys_NO_ETHER_BALANCE(); } uint256 _safeShare_ = _balance_ * 900 / 1000; uint256 _charityShare_ = _balance_ * 50 / 1000; uint256 _othersShare_ = _charityShare_ / 2; _sendValue( payable( _CC_COMMUNITY ), _othersShare_ ); _sendValue( payable( _CC_FOUNDERS ), _othersShare_ ); _sendValue( payable( _CC_CHARITY ), _charityShare_ ); _sendValue( payable( _CC_SAFE ), _safeShare_ ); address[] memory _tos_ = new address[]( 4 ); _tos_[ 0 ] = _CC_COMMUNITY; _tos_[ 1 ] = _CC_FOUNDERS; _tos_[ 2 ] = _CC_CHARITY; _tos_[ 3 ] = _CC_SAFE; uint256[] memory _amounts_ = new uint256[]( 4 ); _amounts_[ 0 ] = _othersShare_; _amounts_[ 1 ] = _othersShare_; _amounts_[ 2 ] = _charityShare_; _amounts_[ 3 ] = _safeShare_; emit PaymentReleased( address( this ), _tos_, _amounts_ ); } // ************************************** // ************************************** // ***** VIEW ***** // ************************************** /** * @dev Returns the number of tokens owned by `tokenOwner_`. */ function balanceOf( address tokenOwner_ ) public view virtual override(ERC721Batch, ERC721BatchStakable) returns ( uint256 balance ) { return ERC721BatchStakable.balanceOf( tokenOwner_ ); } /** * @dev Returns the owner of token number `tokenId_`. * * Requirements: * * - `tokenId_` must exist. */ function ownerOf( uint256 tokenId_ ) public view virtual override(ERC721Batch, ERC721BatchStakable) exists( tokenId_ ) returns ( address ) { return ERC721BatchStakable.ownerOf( tokenId_ ); } /** * @dev See {IERC2981-royaltyInfo}. * * Requirements: * * - `tokenId_` must exist. */ function royaltyInfo( uint256 tokenId_, uint256 salePrice_ ) public view virtual override exists( tokenId_ ) returns ( address, uint256 ) { return super.royaltyInfo( tokenId_, salePrice_ ); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId_ ) public view virtual override(ERC721BatchEnumerable, ERC721Batch, ERC2981Base) returns ( bool ) { return interfaceId_ == type( IERC2981 ).interfaceId || ERC721Batch.supportsInterface( interfaceId_ ) || ERC721BatchEnumerable.supportsInterface( interfaceId_ ); } // ************************************** }
Returns the number of tokens staked by `tokenOwner_`./
function balanceOfStaked( address tokenOwner_ ) public view virtual returns ( uint256 ) { return _balanceOfStaked( tokenOwner_ ); }
14,920,238
./partial_match/3/0xC8543af5736557994C47607dc3Df9a051F62DB72/sources/EternityVesting.sol
Get Total Token return {uint256} totalToken/
function getTotalToken() public view returns (uint256) { return _token.balanceOf(address(this)); }
5,088,335
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; /** * @dev TinySeed ERC-1155 contract: */ contract TinySeed is ERC1155, Ownable, Pausable, ERC1155Burnable, ERC1155Supply, PaymentSplitter { /** * @dev Constants for token types: */ uint256 public constant SERIES1 = 0; uint256 public constant REFILL = 1; uint256 public constant PLATINUM = 2; /** * @dev Constants, token supply bands and associated USD pricing: * =========================================== * MUST BE UPDATED / VALIDATED PRIOR TO DEPLOY * =========================================== */ uint256 public constant SERIES1_SUPPLY1 = 100; uint256 public constant SERIES1_SUPPLY2 = 250; uint256 public constant SERIES1_SUPPLY3 = 500; uint256 public constant SERIES1_USD1 = 220; uint256 public constant SERIES1_USD2 = 230; uint256 public constant SERIES1_USD3 = 240; uint256 public constant SERIES1_USD4 = 250; uint256 public constant REFILL_USD = 250; uint256 public constant PLATINUM_USD = 4600; /** * @dev Add name and symbol for consistency with ERC-721 NFTs. Note that ERC-721 stores * these variables on-chain, but as they can only be set on the constructor we may as well * save the gas and have them as constants in the bytecode. */ string private constant NAME = "TinySeed"; string private constant SYMBOL = "TINYSEED"; AggregatorV3Interface internal priceFeed; /** * @dev saleOpen - when set to false it stays false. This is how the mint * is permanently closed at the end. Pause is different, as it can be set and unset * and also controls token transfer. */ bool public saleOpen; bool public developerAllocationComplete; address private developer; /** * @dev Price buffer above and below the passed amount of ETH that will be accepted. This function * will be used to set the price for items in the UI, but there is always the possibility of price * fluctuations beween the display and the mint. These parameters determine as an amount per thousance * how high above or below the price the passed amount of ETH can be and still make a valid sale. The * stored values are in the following format: * - priceBufferUp: amount as a proportion of 1,000. For example, if you set this to 1005 you allow the * price to be up to 1005 / 1000 of the actual price, i.e. not exceeding 0.5% greater. * - priceBufferDown: amount as a proportion of 1,000. For example, if you set this to 995 you allow the * price to be up to 995 / 1000 of the actual price i.e. not exceeding 0.5% less. */ uint256 private priceBufferUp; uint256 private priceBufferDown; /** * @dev Contract events: */ event SaleClosedSet(address account); event PriceBufferUpSet(uint256 priceBuffer); event PriceBufferDownSet(uint256 priceBuffer); event DeveloperAllocationCompleteSet(address account); event tinySeedMinted( address account, uint256 TiQuantity, uint256 RefillQuantity, uint256 PtQuantity, uint256 TiSupply, uint256 RefillSupply, uint256 PtSupply, uint256 cost ); /** * @dev Constructor must be passed an array of shareholders for the payment splitter, the first * array holding addresses and the second the corresponding shares. For example, you could have the following: * - _payees[beneficiaryAddress, developerAddress] * - _shares[90,10] * In this example the beneficiary address passed in can claim 90% of total ETH, the developer 10% */ constructor( uint256 _priceBufferUp, uint256 _priceBufferDown, address[] memory _payees, uint256[] memory _shares, address _developer ) ERC1155( "https://arweave.net/jGEbN3EEPoKqTwzkPD4rBf7ujmtBFtZIkwD_T9242hQ/{id}.json" ) PaymentSplitter(_payees, _shares) { setPriceBufferUp(_priceBufferUp); setPriceBufferDown(_priceBufferDown); developer = _developer; saleOpen = true; developerAllocationComplete = false; _pause(); /** * @dev Contract address for pricefeed data. * ============================================== * MUST BE SET TO MAINNET ADDRESS PRIOR TO DEPLOY * ============================================== * MAINNET: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 * RINKEBY: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e */ priceFeed = AggregatorV3Interface( 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 ); } /** * @dev The sale being open depends on the saleOpen bool. This is set to true * in the constructor and can be set to closed by the owner. Once closed it is closed * forever. Minting cannot occur, token transfers are still allows. These can be paused * by using _pause. */ modifier whenSaleOpen() { require(saleOpen, "Sale is closed"); _; } modifier whenSaleClosed() { require(!saleOpen, "Sale is open"); _; } modifier whenDeveloperAllocationAvailable() { require(!developerAllocationComplete, "Developer allocation is complete"); _; } /** * @dev admin functions: */ function setPriceBufferUp(uint256 _priceBufferUpToSet) public onlyOwner returns (bool) { priceBufferUp = _priceBufferUpToSet; emit PriceBufferUpSet(priceBufferUp); return true; } function setPriceBufferDown(uint256 _priceBufferDownToSet) public onlyOwner returns (bool) { priceBufferDown = _priceBufferDownToSet; emit PriceBufferDownSet(priceBufferDown); return true; } function setSaleClosed() external onlyOwner whenSaleOpen { saleOpen = false; emit SaleClosedSet(msg.sender); } function setDeveloperAllocationComplete() external onlyOwner whenSaleClosed { developerAllocationComplete = true; emit DeveloperAllocationCompleteSet(msg.sender); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function getCurrentRate() external view returns (uint256) { return (uint256(getLatestPrice())); } function getDollarValueInWei(uint256 _dollarValue) external view returns (uint256) { uint256 latestPrice = uint256(getLatestPrice()); return (performConversion(latestPrice, _dollarValue)); } function getCurrentETHPriceById(uint256 _id) external view returns (uint256 priceInETH) { uint256 latestPrice = uint256(getLatestPrice()); if (_id == SERIES1) { return (performConversion(latestPrice, getCurrentTitaniumUSD())); } if (_id == REFILL) { return (performConversion(latestPrice, REFILL_USD)); } if (_id == PLATINUM) { return (performConversion(latestPrice, PLATINUM_USD)); } } function getAllCurrentETHPrices() public view returns ( uint256 titanium, uint256 refiller, uint256 platinum ) { uint256 latestPrice = uint256(getLatestPrice()); uint256 seriesOnePrice = performConversion( latestPrice, getCurrentTitaniumUSD() ); uint256 refillPrice = performConversion(latestPrice, REFILL_USD); uint256 platinumPrice = performConversion(latestPrice, PLATINUM_USD); return ((seriesOnePrice), (refillPrice), (platinumPrice)); } function getTotalMinted() external view returns ( uint256 seriesOne, uint256 refiller, uint256 platinum ) { return (totalSupply(SERIES1), totalSupply(REFILL), totalSupply(PLATINUM)); } function getAccountMinted(address _account) external view returns ( uint256 seriesOne, uint256 refiller, uint256 platinum ) { return ( balanceOf(_account, SERIES1), balanceOf(_account, REFILL), balanceOf(_account, PLATINUM) ); } function getBuffers() external view onlyOwner returns (uint256 bufferUp, uint256 bufferDown) { return (priceBufferUp, priceBufferDown); } /** * @dev Add name, symbol and total supply for consistency with ERC-721 NFTs. */ function name() public pure returns (string memory) { return NAME; } function symbol() public pure returns (string memory) { return SYMBOL; } function totalSupply() public view returns (uint256) { return (totalSupply(SERIES1) + totalSupply(REFILL) + totalSupply(PLATINUM)); } /** * Returns the latest USD price to 8DP of 1 ETH */ function getLatestPrice() public view returns (int256) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } /** * @dev perform price conversion USD to Wei at the prescribed number of significant figures (i.e. DP in ETH) */ function performConversion(uint256 _price, uint256 _value) internal pure returns (uint256 convertedValue) { require(_price > 0 && _price < 9999999999999, "Pricing Error"); // The USD figure from the price feed is one eth in USD to 8 DP. We need the value of one dollar in wei/ // The price feed has 8DP so lets add that exponent to our wei figure to give us the value of $1 in wei uint256 oneUSDInWei = ((10**26) / _price); // 2) Mutiply our dollar value by that to get our value in wei: uint256 valueInWei = oneUSDInWei * _value; // 3) And then roundup that number to 4DP of eth by removing 10**14 digits, adding 1, then multiplying by 10**14: valueInWei = ((valueInWei / (10**14)) + 1) * (10**14); return (valueInWei); } /** * @dev This function is called from the UI to mint NFTs for the user. Can only be called when the sale is open * and the contract isn't paused. It must be passed three quantities, one for each of the token types: */ function buyTinySeed( uint256 _quantitySeriesOne, uint256 _quantityRefiller, uint256 _quantityPlatinum ) external payable whenSaleOpen whenNotPaused { require( _quantitySeriesOne != 0 || _quantityRefiller != 0 || _quantityPlatinum != 0, "Order must be for an item" ); uint256 orderPrice = priceOrder( _quantitySeriesOne, _quantityRefiller, _quantityPlatinum ); checkPaymentToPrice(msg.value, orderPrice); // To reach here the price check must have passed. Mint the items: processMint( msg.sender, _quantitySeriesOne, _quantityRefiller, _quantityPlatinum, msg.value ); // Events are emitted per order in the mint function. } /** * @dev Get the current price of this order in the same way that it will have been assembled in the UI, * i.e. get the current price of each token type in ETH (including the rounding to 4DP of ETH) and then * multiply that by the total quantity ordered. */ function priceOrder( uint256 _quantitySeriesOne, uint256 _quantityRefiller, uint256 _quantityPlatinum ) internal view returns (uint256 price) { uint256 orderCostInETH = 0; ( uint256 seriesOnePrice, uint256 refillPrice, uint256 platinumPrice ) = getAllCurrentETHPrices(); orderCostInETH = ((seriesOnePrice * _quantitySeriesOne) + (refillPrice * _quantityRefiller) + (platinumPrice * _quantityPlatinum)); return (orderCostInETH); } /** * @dev This function allows the developer allocation mint. It is closed when the bool developerAllocationComplete is set to true */ function mintDeveloperAllocation( uint256 _quantitySeriesOne, uint256 _quantityRefiller, uint256 _quantityPlatinum ) external payable onlyOwner whenSaleClosed whenDeveloperAllocationAvailable { processMint( developer, _quantitySeriesOne, _quantityRefiller, _quantityPlatinum, 0 ); } /** * @dev Unified proccessing for mint operation: */ function processMint( address _recipient, uint256 _quantitySeriesOne, uint256 _quantityRefiller, uint256 _quantityPlatinum, uint256 _cost ) internal { // Series one (titanium) items: if (_quantitySeriesOne > 0) { _mint(_recipient, SERIES1, _quantitySeriesOne, ""); } // Refiller items: if (_quantityRefiller > 0) { _mint(_recipient, REFILL, _quantityRefiller, ""); } // Platinum items: if (_quantityPlatinum > 0) { _mint(_recipient, PLATINUM, _quantityPlatinum, ""); } emit tinySeedMinted( _recipient, _quantitySeriesOne, _quantityRefiller, _quantityPlatinum, totalSupply(SERIES1), totalSupply(REFILL), totalSupply(PLATINUM), _cost ); } /** * @dev Get the current series One price. */ function getCurrentTitaniumUSD() internal view returns (uint256 _currentPrice) { uint256 nextTitanium = totalSupply(SERIES1) + 1; // For efficiency first check if we exceed the highest tier, as presumably most // units will be sold at the standard post-tier price: if (nextTitanium > SERIES1_SUPPLY3) { return (SERIES1_USD4); } if (nextTitanium <= SERIES1_SUPPLY1) { return (SERIES1_USD1); } if (nextTitanium <= SERIES1_SUPPLY2) { return (SERIES1_USD2); } if (nextTitanium <= SERIES1_SUPPLY3) { return (SERIES1_USD3); } } /** * @dev Determine if the passed cost is within bounds of current price: */ function checkPaymentToPrice(uint256 _passedETH, uint256 _orderPrice) internal view { // Establish upper and lower bands of price buffer and check uint256 orderPriceLower = (_orderPrice * priceBufferDown) / 1000; require(_passedETH >= orderPriceLower, "Insufficient ETH passed for order"); uint256 orderPriceUpper = (_orderPrice * priceBufferUp) / 1000; require(_passedETH <= orderPriceUpper, "Too much ETH passed for order"); } /** * @dev The fallback function is executed on a call to the contract if * none of the other functions match the given function signature. */ fallback() external payable { revert(); } /** * @dev revert any random ETH: */ receive() external payable override { revert(); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override(ERC1155, ERC1155Supply) whenNotPaused { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // 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/Pausable.sol) pragma solidity ^0.8.0; import "../utils/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() { _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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @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_); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // 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); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/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 // 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); }
xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_burn}. Requirements: - `ids` and `amounts` must have the same length./
function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); }
11,473
pragma solidity ^0.4.24; import "./Events.sol"; // Interface contracts are interface layers to the main contracts which defines // a function and its input/output parameters. // Use in conjuction to real contract's address, you can interact with external // contract's functions using this interface layer contract TrackerInterface { function internalContribute (address _from, address _to, uint _amount) public returns (bool); function internalRedeemFunds ( address _listingAddress, address _seller, uint _amount) public returns (bool); function getBalance(address _wallet) public returns (uint); function internalArbitrate(string _reason, address _requestedBy) public returns (address); } contract Asset is Events { TrackerInterface public tracker; address public seller; address[] listOfMarketPlaces; bytes12 public assetId; uint public term; uint public amountFunded = 0; uint public totalCost; uint public expirationDate; uint public kickbackAmount; bool public isContract = true; string public title; uint initialStakeAmount; uint totalStakeAmount; mapping(address => uint) contributions; enum report{ SPAM, BROKEN, NOTRECIEVED, NOREASON } address arbitrateAddr = 0x0; //User must have enough funds to call functions modifier onlyHasEnoughFunds(address _reporter) { uint balance = tracker.getBalance(_reporter); require(balance >= initialStakeAmount); _; } //only user gets to call certain functions modifier onlySeller(address _seller) { require(seller == _seller); _; } constructor( bytes12 _assetId, uint _term, address _seller, string _title, uint _totalCost, uint _expirationDate, address _mpAddress, uint _mpAmount, uint _stakeAmount) public { assetId = _assetId; term = _term; seller = _seller; title = _title; totalCost = _totalCost; expirationDate = _expirationDate; kickbackAmount = _mpAmount; listOfMarketPlaces.push(_mpAddress); tracker = TrackerInterface(msg.sender); initialStakeAmount = _stakeAmount; totalStakeAmount = _stakeAmount; } function getAssetConfig() public view returns( bytes32, uint, address, uint, string, bool, bool, uint, uint, address, uint) { return ( assetId, term, seller, amountFunded, title, isFunded(), isExpired(), totalCost, expirationDate, listOfMarketPlaces[0], kickbackAmount); } // Getter function. returns a users's total contributions so far for this asset. function getMyContributions(address _contributor) public view returns (uint) { return contributions[_contributor]; } // Checks to see if asset is open for contributions or not // Based on expired or not, and if incoming contribution will overflow the asset or not function isOpenForContribution(uint _contributing) public view returns (bool) { if(arbitrateAddr != 0x0) return false; if (isExpired()) return false; uint willGoOverBoard = _contributing + amountFunded; if (willGoOverBoard > totalCost) return false; if (arbitrateAddr != 0x000) return false; return true; } // Getter function. returns if asset is fully funded or not function isFunded() public view returns (bool) { return amountFunded >= totalCost; } // Getter function. returns if listing is expired or not function isExpired() public view returns (bool) { return expirationDate <= now; } // Getter function. returns if asset is fractional or not based on term function isFractional() public view returns (bool) { if (term > 0) return true; return false; } // Handles multi/single contribuitons function contribute(address _marketPlace, address _contributor, uint _contributing) public { if (!isOpenForContribution(_contributing)) revert(); bool result; uint userBalance = tracker.getBalance(_contributor); if (userBalance < _contributing) revert(); listOfMarketPlaces.push(_marketPlace); if (isFractional()) { result = tracker.internalContribute(_contributor, this, _contributing); if(result == true) addToContributions(_contributor, _contributing); releaseFunds(); } else if (_contributing >= totalCost) { uint mpGets; uint sellerGets; (mpGets, sellerGets) = calcDistribution(); tracker.internalContribute(_contributor, seller, sellerGets); addToContributions(_contributor, _contributing); if(mpGets > 0) for(uint i = 0; i < listOfMarketPlaces.length; i++) tracker.internalContribute(_contributor, listOfMarketPlaces[i], mpGets); } else revert(); } // Calculate how much seller gets after kickbacks taken out function calcDistribution() public view returns (uint, uint) { uint kickbackWitheld = kickbackAmount / listOfMarketPlaces.length; uint sellerGets = totalCost - kickbackWitheld * listOfMarketPlaces.length; return (kickbackWitheld, sellerGets); } // Updates this contract's metadata function addToContributions(address _contributor, uint _contributing) private { amountFunded += _contributing; contributions[_contributor] += _contributing; } // This is specifically for fractional sellers // It will release funds to seller if listing is fully funded and the listing is expired function releaseFunds() public { if (isFunded()) { TrackerInterface trackerContract = TrackerInterface(tracker); uint mpGets; uint sellerGets; (mpGets, sellerGets) = calcDistribution(); trackerContract.internalRedeemFunds(this, seller, sellerGets); for (uint i = 0; i < listOfMarketPlaces.length; i++) trackerContract.internalRedeemFunds(this, listOfMarketPlaces[i], mpGets); } } // report spam assets // start refund process function arbitrate(string _reason, address _reporter) public onlyHasEnoughFunds(_reporter) returns (bool) { // create arbitrate contract and append pause process to all functions. arbitrateAddr = tracker.internalArbitrate(_reason, _reporter); //report stakes the same amount so inital stake amount should be 2x now tracker.internalContribute (_reporter, this, initialStakeAmount); totalStakeAmount+=initialStakeAmount; //double take amount emit Success(3, arbitrateAddr); return true; } // dispute reported spam // only seller can call function disputeReportedSpam(address _seller) public onlySeller(_seller) onlyHasEnoughFunds(_seller) returns (bool) { tracker.internalContribute (_seller, this, initialStakeAmount); totalStakeAmount+=initialStakeAmount; //double take amount emit Success(4, arbitrateAddr); return true; } }
Getter function. returns if asset is fully funded or not
function isFunded() public view returns (bool) { return amountFunded >= totalCost; }
12,693,611
// SPDX-License-Identifier: MIT pragma solidity >=0.6.10 <0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../utils/SafeDecimalMath.sol"; import "../utils/CoreUtility.sol"; import "../interfaces/IFund.sol"; import "../interfaces/IChessSchedule.sol"; import "../interfaces/ITrancheIndex.sol"; import "../interfaces/IPrimaryMarket.sol"; interface IChessController { function getFundRelativeWeight(address account, uint256 timestamp) external view returns (uint256); } abstract contract Staking is ITrancheIndex, CoreUtility { /// @dev Reserved storage slots for future sibling contract upgrades uint256[32] private _reservedSlots; using Math for uint256; using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; event Deposited(uint256 tranche, address account, uint256 amount); event Withdrawn(uint256 tranche, address account, uint256 amount); uint256 private constant MAX_ITERATIONS = 500; uint256 private constant REWARD_WEIGHT_A = 4; uint256 private constant REWARD_WEIGHT_B = 2; uint256 private constant REWARD_WEIGHT_M = 3; IFund public immutable fund; IERC20 private immutable tokenM; IERC20 private immutable tokenA; IERC20 private immutable tokenB; /// @notice The Chess release schedule contract. IChessSchedule public immutable chessSchedule; uint256 public immutable guardedLaunchStart; uint256 private _rate; /// @notice The controller contract. IChessController public immutable chessController; /// @notice Quote asset for the exchange. Each exchange only handles one quote asset address public immutable quoteAssetAddress; /// @dev Total amount of user shares, i.e. sum of all entries in `_availableBalances` and /// `_lockedBalances`. Note that these values can be smaller than the amount of /// share tokens held by this contract, because shares locked in unsettled trades /// are not included in total supplies or any user's balance. uint256[TRANCHE_COUNT] private _totalSupplies; /// @dev Rebalance version of `_totalSupplies`. uint256 private _totalSupplyVersion; /// @dev Amount of shares that can be withdrawn or traded by each user. mapping(address => uint256[TRANCHE_COUNT]) private _availableBalances; /// @dev Amount of shares that are locked in ask orders. mapping(address => uint256[TRANCHE_COUNT]) private _lockedBalances; /// @dev Rebalance version mapping for `_availableBalances`. mapping(address => uint256) private _balanceVersions; /// @dev 1e27 * ∫(rate(t) / totalWeight(t) dt) from the latest rebalance till checkpoint. uint256 private _invTotalWeightIntegral; /// @dev Final `_invTotalWeightIntegral` before each rebalance. /// These values are accessed in a loop in `_userCheckpoint()` with bounds checking. /// So we store them in a fixed-length array, in order to make compiler-generated /// bounds checking on every access cheaper. The actual length of this array is stored in /// `_historicalIntegralSize` and should be explicitly checked when necessary. uint256[65535] private _historicalIntegrals; /// @dev Actual length of the `_historicalIntegrals` array, which always equals to the number of /// historical rebalances after `checkpoint()` is called. uint256 private _historicalIntegralSize; /// @dev Timestamp when checkpoint() is called. uint256 private _checkpointTimestamp; /// @dev Snapshot of `_invTotalWeightIntegral` per user. mapping(address => uint256) private _userIntegrals; /// @dev Mapping of account => claimable rewards. mapping(address => uint256) private _claimableRewards; constructor( address fund_, address chessSchedule_, address chessController_, address quoteAssetAddress_, uint256 guardedLaunchStart_ ) public { fund = IFund(fund_); tokenM = IERC20(IFund(fund_).tokenM()); tokenA = IERC20(IFund(fund_).tokenA()); tokenB = IERC20(IFund(fund_).tokenB()); chessSchedule = IChessSchedule(chessSchedule_); chessController = IChessController(chessController_); quoteAssetAddress = quoteAssetAddress_; _checkpointTimestamp = block.timestamp; guardedLaunchStart = guardedLaunchStart_; _rate = IChessSchedule(chessSchedule_).getRate(block.timestamp); } /// @notice Return weight of given balance with respect to rewards. /// @param amountM Amount of Token M /// @param amountA Amount of Token A /// @param amountB Amount of Token B /// @return Rewarding weight of the balance function rewardWeight( uint256 amountM, uint256 amountA, uint256 amountB ) public pure returns (uint256) { return amountM.mul(REWARD_WEIGHT_M).add(amountA.mul(REWARD_WEIGHT_A)).add( amountB.mul(REWARD_WEIGHT_B) ) / REWARD_WEIGHT_M; } function totalSupply(uint256 tranche) external view returns (uint256) { uint256 totalSupplyM = _totalSupplies[TRANCHE_M]; uint256 totalSupplyA = _totalSupplies[TRANCHE_A]; uint256 totalSupplyB = _totalSupplies[TRANCHE_B]; uint256 version = _totalSupplyVersion; uint256 rebalanceSize = fund.getRebalanceSize(); if (version < rebalanceSize) { (totalSupplyM, totalSupplyA, totalSupplyB) = fund.batchRebalance( totalSupplyM, totalSupplyA, totalSupplyB, version, rebalanceSize ); } if (tranche == TRANCHE_M) { return totalSupplyM; } else if (tranche == TRANCHE_A) { return totalSupplyA; } else { return totalSupplyB; } } function availableBalanceOf(uint256 tranche, address account) external view returns (uint256) { uint256 amountM = _availableBalances[account][TRANCHE_M]; uint256 amountA = _availableBalances[account][TRANCHE_A]; uint256 amountB = _availableBalances[account][TRANCHE_B]; if (tranche == TRANCHE_M) { if (amountM == 0 && amountA == 0 && amountB == 0) return 0; } else if (tranche == TRANCHE_A) { if (amountA == 0) return 0; } else { if (amountB == 0) return 0; } uint256 version = _balanceVersions[account]; uint256 rebalanceSize = fund.getRebalanceSize(); if (version < rebalanceSize) { (amountM, amountA, amountB) = fund.batchRebalance( amountM, amountA, amountB, version, rebalanceSize ); } if (tranche == TRANCHE_M) { return amountM; } else if (tranche == TRANCHE_A) { return amountA; } else { return amountB; } } function lockedBalanceOf(uint256 tranche, address account) external view returns (uint256) { uint256 amountM = _lockedBalances[account][TRANCHE_M]; uint256 amountA = _lockedBalances[account][TRANCHE_A]; uint256 amountB = _lockedBalances[account][TRANCHE_B]; if (tranche == TRANCHE_M) { if (amountM == 0 && amountA == 0 && amountB == 0) return 0; } else if (tranche == TRANCHE_A) { if (amountA == 0) return 0; } else { if (amountB == 0) return 0; } uint256 version = _balanceVersions[account]; uint256 rebalanceSize = fund.getRebalanceSize(); if (version < rebalanceSize) { (amountM, amountA, amountB) = fund.batchRebalance( amountM, amountA, amountB, version, rebalanceSize ); } if (tranche == TRANCHE_M) { return amountM; } else if (tranche == TRANCHE_A) { return amountA; } else { return amountB; } } function balanceVersion(address account) external view returns (uint256) { return _balanceVersions[account]; } /// @dev Deposit to get rewards /// @param tranche Tranche of the share /// @param amount The amount to deposit function deposit(uint256 tranche, uint256 amount) public { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(msg.sender, rebalanceSize); if (tranche == TRANCHE_M) { tokenM.safeTransferFrom(msg.sender, address(this), amount); } else if (tranche == TRANCHE_A) { tokenA.safeTransferFrom(msg.sender, address(this), amount); } else { tokenB.safeTransferFrom(msg.sender, address(this), amount); } _availableBalances[msg.sender][tranche] = _availableBalances[msg.sender][tranche].add( amount ); _totalSupplies[tranche] = _totalSupplies[tranche].add(amount); emit Deposited(tranche, msg.sender, amount); } /// @dev Claim settled Token M from the primary market and deposit to get rewards /// @param primaryMarket The primary market to claim shares from function claimAndDeposit(address primaryMarket) external { (uint256 createdShares, ) = IPrimaryMarket(primaryMarket).claim(msg.sender); deposit(TRANCHE_M, createdShares); } /// @dev Withdraw /// @param tranche Tranche of the share /// @param amount The amount to deposit function withdraw(uint256 tranche, uint256 amount) external { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(msg.sender, rebalanceSize); _availableBalances[msg.sender][tranche] = _availableBalances[msg.sender][tranche].sub( amount, "Insufficient balance to withdraw" ); _totalSupplies[tranche] = _totalSupplies[tranche].sub(amount); if (tranche == TRANCHE_M) { tokenM.safeTransfer(msg.sender, amount); } else if (tranche == TRANCHE_A) { tokenA.safeTransfer(msg.sender, amount); } else { tokenB.safeTransfer(msg.sender, amount); } emit Withdrawn(tranche, msg.sender, amount); } /// @notice Transform share balance to a given rebalance version, or to the latest version /// if `targetVersion` is zero. /// @param account Account of the balance to rebalance /// @param targetVersion The target rebalance version, or zero for the latest version function refreshBalance(address account, uint256 targetVersion) external { uint256 rebalanceSize = fund.getRebalanceSize(); if (targetVersion == 0) { targetVersion = rebalanceSize; } else { require(targetVersion <= rebalanceSize, "Target version out of bound"); } _checkpoint(rebalanceSize); _userCheckpoint(account, targetVersion); } /// @notice Return claimable rewards of an account till now. /// /// This function should be call as a "view" function off-chain to get /// the return value, e.g. using `contract.claimableRewards.call(account)` in web3 /// or `contract.callStatic.claimableRewards(account)` in ethers.js. /// @param account Address of an account /// @return Amount of claimable rewards function claimableRewards(address account) external returns (uint256) { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); return _claimableRewards[account]; } /// @notice Claim the rewards for an account. /// @param account Account to claim its rewards function claimRewards(address account) external { require( block.timestamp >= guardedLaunchStart + 15 days, "Cannot claim during guarded launch" ); uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); _claim(account); } /// @dev Transfer shares from the sender to the contract internally /// @param tranche Tranche of the share /// @param sender Sender address /// @param amount The amount to transfer function _tradeAvailable( uint256 tranche, address sender, uint256 amount ) internal { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(sender, rebalanceSize); _availableBalances[sender][tranche] = _availableBalances[sender][tranche].sub(amount); _totalSupplies[tranche] = _totalSupplies[tranche].sub(amount); } function _rebalanceAndClearTrade( address account, uint256 amountM, uint256 amountA, uint256 amountB, uint256 amountVersion ) internal returns ( uint256, uint256, uint256 ) { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); if (amountVersion < rebalanceSize) { (amountM, amountA, amountB) = fund.batchRebalance( amountM, amountA, amountB, amountVersion, rebalanceSize ); } uint256[TRANCHE_COUNT] storage available = _availableBalances[account]; if (amountM > 0) { available[TRANCHE_M] = available[TRANCHE_M].add(amountM); _totalSupplies[TRANCHE_M] = _totalSupplies[TRANCHE_M].add(amountM); } if (amountA > 0) { available[TRANCHE_A] = available[TRANCHE_A].add(amountA); _totalSupplies[TRANCHE_A] = _totalSupplies[TRANCHE_A].add(amountA); } if (amountB > 0) { available[TRANCHE_B] = available[TRANCHE_B].add(amountB); _totalSupplies[TRANCHE_B] = _totalSupplies[TRANCHE_B].add(amountB); } return (amountM, amountA, amountB); } function _lock( uint256 tranche, address account, uint256 amount ) internal { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); _availableBalances[account][tranche] = _availableBalances[account][tranche].sub( amount, "Insufficient balance to lock" ); _lockedBalances[account][tranche] = _lockedBalances[account][tranche].add(amount); } function _rebalanceAndUnlock( address account, uint256 amountM, uint256 amountA, uint256 amountB, uint256 amountVersion ) internal { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); if (amountVersion < rebalanceSize) { (amountM, amountA, amountB) = fund.batchRebalance( amountM, amountA, amountB, amountVersion, rebalanceSize ); } uint256[TRANCHE_COUNT] storage available = _availableBalances[account]; uint256[TRANCHE_COUNT] storage locked = _lockedBalances[account]; if (amountM > 0) { available[TRANCHE_M] = available[TRANCHE_M].add(amountM); locked[TRANCHE_M] = locked[TRANCHE_M].sub(amountM); } if (amountA > 0) { available[TRANCHE_A] = available[TRANCHE_A].add(amountA); locked[TRANCHE_A] = locked[TRANCHE_A].sub(amountA); } if (amountB > 0) { available[TRANCHE_B] = available[TRANCHE_B].add(amountB); locked[TRANCHE_B] = locked[TRANCHE_B].sub(amountB); } } function _tradeLocked( uint256 tranche, address account, uint256 amount ) internal { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); _lockedBalances[account][tranche] = _lockedBalances[account][tranche].sub(amount); _totalSupplies[tranche] = _totalSupplies[tranche].sub(amount); } /// @dev Transfer claimable rewards to an account. Rewards since the last user checkpoint /// is not included. This function should always be called after `_userCheckpoint()`, /// in order for the user to get all rewards till now. /// @param account Address of the account function _claim(address account) internal { chessSchedule.mint(account, _claimableRewards[account]); _claimableRewards[account] = 0; } /// @dev Transform total supplies to the latest rebalance version and make a global reward checkpoint. /// @param rebalanceSize The number of existing rebalances. It must be the same as /// `fund.getRebalanceSize()`. function _checkpoint(uint256 rebalanceSize) private { uint256 timestamp = _checkpointTimestamp; if (timestamp >= block.timestamp) { return; } uint256 integral = _invTotalWeightIntegral; uint256 endWeek = _endOfWeek(timestamp); uint256 weeklyPercentage = chessController.getFundRelativeWeight(address(this), endWeek - 1 weeks); uint256 version = _totalSupplyVersion; uint256 rebalanceTimestamp; if (version < rebalanceSize) { rebalanceTimestamp = fund.getRebalanceTimestamp(version); } else { rebalanceTimestamp = type(uint256).max; } uint256 rate = _rate; uint256 totalSupplyM = _totalSupplies[TRANCHE_M]; uint256 totalSupplyA = _totalSupplies[TRANCHE_A]; uint256 totalSupplyB = _totalSupplies[TRANCHE_B]; uint256 weight = rewardWeight(totalSupplyM, totalSupplyA, totalSupplyB); uint256 timestamp_ = timestamp; // avoid stack too deep for (uint256 i = 0; i < MAX_ITERATIONS && timestamp_ < block.timestamp; i++) { uint256 endTimestamp = rebalanceTimestamp.min(endWeek).min(block.timestamp); if (weight > 0) { integral = integral.add( rate .mul(endTimestamp.sub(timestamp_)) .multiplyDecimal(weeklyPercentage) .divideDecimalPrecise(weight) ); } if (endTimestamp == rebalanceTimestamp) { uint256 oldSize = _historicalIntegralSize; _historicalIntegrals[oldSize] = integral; _historicalIntegralSize = oldSize + 1; integral = 0; (totalSupplyM, totalSupplyA, totalSupplyB) = fund.doRebalance( totalSupplyM, totalSupplyA, totalSupplyB, version ); version++; weight = rewardWeight(totalSupplyM, totalSupplyA, totalSupplyB); if (version < rebalanceSize) { rebalanceTimestamp = fund.getRebalanceTimestamp(version); } else { rebalanceTimestamp = type(uint256).max; } } if (endTimestamp == endWeek) { rate = chessSchedule.getRate(endWeek); weeklyPercentage = chessController.getFundRelativeWeight(address(this), endWeek); endWeek += 1 weeks; } timestamp_ = endTimestamp; } _checkpointTimestamp = block.timestamp; _invTotalWeightIntegral = integral; if (_rate != rate) { _rate = rate; } if (_totalSupplyVersion != rebalanceSize) { _totalSupplies[TRANCHE_M] = totalSupplyM; _totalSupplies[TRANCHE_A] = totalSupplyA; _totalSupplies[TRANCHE_B] = totalSupplyB; _totalSupplyVersion = rebalanceSize; } } /// @dev Transform a user's balance to a given rebalance version and update this user's rewards. /// /// In most cases, the target version is the latest version and this function cumulates /// rewards till now. When this function is called from `refreshBalance()`, /// `targetVersion` can be an older version, in which case rewards are cumulated till /// the end of that version (i.e. timestamp of the transaction triggering the rebalance /// with index `targetVersion`). /// /// This function should always be called after `_checkpoint()` is called, so that /// the global reward checkpoint is guarenteed up to date. /// @param account Account to update /// @param targetVersion The target rebalance version function _userCheckpoint(address account, uint256 targetVersion) private { uint256 oldVersion = _balanceVersions[account]; if (oldVersion > targetVersion) { return; } uint256 userIntegral = _userIntegrals[account]; uint256 integral; // This scope is to avoid the "stack too deep" error. { // We assume that this function is always called immediately after `_checkpoint()`, // which guarantees that `_historicalIntegralSize` equals to the number of historical // rebalances. uint256 rebalanceSize = _historicalIntegralSize; integral = targetVersion == rebalanceSize ? _invTotalWeightIntegral : _historicalIntegrals[targetVersion]; } if (userIntegral == integral && oldVersion == targetVersion) { // Return immediately when the user's rewards have already been updated to // the target version. return; } uint256[TRANCHE_COUNT] storage available = _availableBalances[account]; uint256[TRANCHE_COUNT] storage locked = _lockedBalances[account]; uint256 availableM = available[TRANCHE_M]; uint256 availableA = available[TRANCHE_A]; uint256 availableB = available[TRANCHE_B]; uint256 lockedM = locked[TRANCHE_M]; uint256 lockedA = locked[TRANCHE_A]; uint256 lockedB = locked[TRANCHE_B]; uint256 rewards = _claimableRewards[account]; for (uint256 i = oldVersion; i < targetVersion; i++) { uint256 weight = rewardWeight( availableM.add(lockedM), availableA.add(lockedA), availableB.add(lockedB) ); rewards = rewards.add( weight.multiplyDecimalPrecise(_historicalIntegrals[i].sub(userIntegral)) ); if (availableM != 0 || availableA != 0 || availableB != 0) { (availableM, availableA, availableB) = fund.doRebalance( availableM, availableA, availableB, i ); } if (lockedM != 0 || lockedA != 0 || lockedB != 0) { (lockedM, lockedA, lockedB) = fund.doRebalance(lockedM, lockedA, lockedB, i); } userIntegral = 0; } uint256 weight = rewardWeight(availableM.add(lockedM), availableA.add(lockedA), availableB.add(lockedB)); rewards = rewards.add(weight.multiplyDecimalPrecise(integral.sub(userIntegral))); address account_ = account; // Fix the "stack too deep" error _claimableRewards[account_] = rewards; _userIntegrals[account_] = integral; if (oldVersion < targetVersion) { if (available[TRANCHE_M] != availableM) { available[TRANCHE_M] = availableM; } if (available[TRANCHE_A] != availableA) { available[TRANCHE_A] = availableA; } if (available[TRANCHE_B] != availableB) { available[TRANCHE_B] = availableB; } if (locked[TRANCHE_M] != lockedM) { locked[TRANCHE_M] = lockedM; } if (locked[TRANCHE_A] != lockedA) { locked[TRANCHE_A] = lockedA; } if (locked[TRANCHE_B] != lockedB) { locked[TRANCHE_B] = lockedB; } _balanceVersions[account_] = targetVersion; } } }
Transform a user's balance to a given rebalance version and update this user's rewards. In most cases, the target version is the latest version and this function cumulates rewards till now. When this function is called from `refreshBalance()`, `targetVersion` can be an older version, in which case rewards are cumulated till the end of that version (i.e. timestamp of the transaction triggering the rebalance with index `targetVersion`). This function should always be called after `_checkpoint()` is called, so that the global reward checkpoint is guarenteed up to date. account Account to update targetVersion The target rebalance version This scope is to avoid the "stack too deep" error. We assume that this function is always called immediately after `_checkpoint()`, which guarantees that `_historicalIntegralSize` equals to the number of historical rebalances. Return immediately when the user's rewards have already been updated to the target version.
function _userCheckpoint(address account, uint256 targetVersion) private { uint256 oldVersion = _balanceVersions[account]; if (oldVersion > targetVersion) { return; } uint256 userIntegral = _userIntegrals[account]; uint256 integral; { uint256 rebalanceSize = _historicalIntegralSize; integral = targetVersion == rebalanceSize ? _invTotalWeightIntegral : _historicalIntegrals[targetVersion]; } if (userIntegral == integral && oldVersion == targetVersion) { return; } uint256[TRANCHE_COUNT] storage available = _availableBalances[account]; uint256[TRANCHE_COUNT] storage locked = _lockedBalances[account]; uint256 availableM = available[TRANCHE_M]; uint256 availableA = available[TRANCHE_A]; uint256 availableB = available[TRANCHE_B]; uint256 lockedM = locked[TRANCHE_M]; uint256 lockedA = locked[TRANCHE_A]; uint256 lockedB = locked[TRANCHE_B]; uint256 rewards = _claimableRewards[account]; for (uint256 i = oldVersion; i < targetVersion; i++) { uint256 weight = rewardWeight( availableM.add(lockedM), availableA.add(lockedA), availableB.add(lockedB) ); rewards = rewards.add( weight.multiplyDecimalPrecise(_historicalIntegrals[i].sub(userIntegral)) ); if (availableM != 0 || availableA != 0 || availableB != 0) { (availableM, availableA, availableB) = fund.doRebalance( availableM, availableA, availableB, i ); } if (lockedM != 0 || lockedA != 0 || lockedB != 0) { (lockedM, lockedA, lockedB) = fund.doRebalance(lockedM, lockedA, lockedB, i); } userIntegral = 0; } uint256 weight = rewardWeight(availableM.add(lockedM), availableA.add(lockedA), availableB.add(lockedB)); rewards = rewards.add(weight.multiplyDecimalPrecise(integral.sub(userIntegral))); _claimableRewards[account_] = rewards; _userIntegrals[account_] = integral; if (oldVersion < targetVersion) { if (available[TRANCHE_M] != availableM) { available[TRANCHE_M] = availableM; } if (available[TRANCHE_A] != availableA) { available[TRANCHE_A] = availableA; } if (available[TRANCHE_B] != availableB) { available[TRANCHE_B] = availableB; } if (locked[TRANCHE_M] != lockedM) { locked[TRANCHE_M] = lockedM; } if (locked[TRANCHE_A] != lockedA) { locked[TRANCHE_A] = lockedA; } if (locked[TRANCHE_B] != lockedB) { locked[TRANCHE_B] = lockedB; } _balanceVersions[account_] = targetVersion; } }
12,885,425
pragma solidity ^0.5.11; import '../../zeppeline/crowdsale/Crowdsale.sol'; import "../../zeppeline/utils/ReentrancyGuard.sol"; import "../../zeppeline/math/SafeMath.sol"; import "../../zeppeline/GSN/Context.sol"; import "../../zeppeline/token/ERC721/IERC721Enumerable.sol"; import "../../zeppeline/drafts/Counters.sol"; import './Ticket721.sol'; contract TokenSale721 is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // using Counters for Counters.Counter; // The token being sold Ticket721 public _token; //event_id uint256 public _event_id; // ticket type uint public _ticket_type = 1; // maximum amount of tickets to sale // Counters.Counter public _current_limit; uint _sale_limit; // how much have been already sold uint public _sold_count = 0; // Address where funds are collected address payable public _wallet; // Address where we collect comission address payable public treasure_fund; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; // service comission fee uint public percent_fee = 5; /** * 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 TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event CalculatedFees(uint256 initial_value, uint256 fees, uint256 transfered_amount); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor (uint256 rate, address payable wallet, Ticket721 token, uint sale_limit, string memory jid, address payable _treasure_fund) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; treasure_fund = _treasure_fund; _token = token; _sale_limit = sale_limit * (1 ether); _event_id = _token.reserveEventId(_wallet,jid); } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function() external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (Ticket721) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } function event_id() public view returns (uint256) { return _event_id; } function sale_limit() public view returns (uint) { return _sale_limit; } function ticket_type() public view returns (uint) { return _ticket_type; } function sold_count() public view returns (uint) { return _sold_count; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); _preValidatePurchase(beneficiary, weiAmount, tokens); // update state _weiRaised = _weiRaised.add(weiAmount); _sold_count = _sold_count.add(tokens); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount, uint256 tokens) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); uint sc = _sold_count * (1 ether); uint limit = sc + tokens; require(limit <= _sale_limit, "tokens amount should not exceed sale_limit"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.buyTicket(beneficiary,tokenAmount, _event_id, _ticket_type); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { // require(condition, message); require(weiAmount >= _rate, "wei amount should be bigger or equal of rate"); // uint256 ta = SafeMath.mul(weiAmount, _rate); uint256 ta = (weiAmount / (1 ether)) / (_rate / (1 ether)); return ta; // return weiAmount.mul(_rate); //FIXME: round result to int, check math } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { uint256 amount = msg.value; uint256 scale = 100; uint256 fees = calculateFee(amount,scale); amount = amount - fees; _wallet.transfer(amount); treasure_fund.transfer(fees); uint256 r = amount - fees; emit CalculatedFees(amount,fees,r); } /* * EXAMPLE OF TAKING FEE (BASIC OPERATORS) * // calculate percent -- amount * percent / 100 function calculateFee(uint256 amount, uint256 scale) internal view returns (uint256) { uint a = amount / scale; uint b = amount % scale; uint c = percent_fee / scale; uint d = percent_fee % scale; // Calculate fee with ROUND DOWN // return a * c * scale + a * d + b * c + b * d / scale; // calculate fee with ROUND UP // return a * c * scale + a * d + b * c + (b * d + scale - 1) / scale; //calculate fee with CLOSESTS INTEGER return a * c * scale + a * d + b * c + (b * d + scale / 2) / scale; } */ /* * Calculate fee (SafeMath) */ function calculateFee(uint256 amount, uint256 scale) internal view returns (uint256) { uint256 a = SafeMath.div(amount, scale); uint256 b = SafeMath.mod(amount, scale); uint256 c = SafeMath.div(percent_fee, scale); uint256 d = SafeMath.mod(percent_fee, scale); // Calculate fee with ROUND DOWN // return a * c * scale + a * d + b * c + b * d / scale; // calculate fee with ROUND UP // return a * c * scale + a * d + b * c + (b * d + scale - 1) / scale; //calculate fee with CLOSESTS INTEGER // return a * c * scale + a * d + b * c + (b * d + scale / 2) / scale; uint256 m1 = SafeMath.mul(SafeMath.mul(a,c), scale); uint256 m2 = SafeMath.mul(a,d); uint256 m3 = SafeMath.mul(b,c); uint m4 = SafeMath.mul(b,d); uint256 d1 = SafeMath.div(scale,2); uint256 a1 = SafeMath.add(m4,d1); uint256 d2 = SafeMath.div(a1,scale); uint256 a2 = SafeMath.add(m1,m2); uint256 a3 = SafeMath.add(a2,m3); uint256 a4 = SafeMath.add(a3,d2); return a4; } }
low level token purchase DO NOT OVERRIDE This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. beneficiary Recipient of the token purchase/ calculate token amount to be created update state
function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount); _preValidatePurchase(beneficiary, weiAmount, tokens); _weiRaised = _weiRaised.add(weiAmount); _sold_count = _sold_count.add(tokens); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); }
916,160
// SPDX-License-Identifier:MIT pragma solidity 0.8.10; import "./IERC20.sol"; contract CredefiToken is IERC20 { // bytes32 private constant EIP712DOMAIN_HASH = // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") bytes32 private constant EIP712DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; // bytes32 private constant NAME_HASH = keccak256("Credi") bytes32 private constant NAME_HASH = 0x3c5eac0879bc46be0fe2a2701e57d8e6edcaa427c79074f4513eb9572ff50507; // bytes32 private constant VERSION_HASH = keccak256("1") bytes32 private constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; // bytes32 public constant PERMIT_TYPEHASH = // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"); bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; string public constant name = "CREDI"; string public constant symbol = "CREDI"; uint8 public constant decimals = 18; address public timelock; uint256 public override totalSupply; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) public override allowance; // ERC-2612, ERC-3009 state mapping(address => uint256) public nonces; mapping(address => mapping(bytes32 => bool)) public authorizationState; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event TimelockUpdated(address indexed timelock); modifier onlyTimelock() { require(msg.sender == address(timelock), "CREDI:NOT_TIMELOCK"); _; } constructor(address _timelock) { _changeTimelock(_timelock); } function changeTimelock(address _timelock) external onlyTimelock { _changeTimelock(_timelock); } function mint(address to, uint256 value) external onlyTimelock returns (bool) { _mint(to, value); return true; } function burn(uint256 value) external returns (bool) { _burn(msg.sender, value); return true; } function approve(address spender, uint256 value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external override returns (bool) { uint256 fromAllowance = allowance[from][msg.sender]; if (fromAllowance != type(uint256).max) { // Allowance is implicitly checked with Solidity's underflow protection allowance[from][msg.sender] = fromAllowance - value; } _transfer(from, to, value); return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "CREDI:AUTH_EXPIRED"); bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner], deadline)); nonces[owner] = nonces[owner] + 1; _validateSignedData(owner, encodeData, v, r, s); _approve(owner, spender, value); } function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { require(block.timestamp > validAfter, "CREDI:AUTH_NOT_YET_VALID"); require(block.timestamp < validBefore, "CREDI:AUTH_EXPIRED"); require(!authorizationState[from][nonce], "CREDI:AUTH_ALREADY_USED"); bytes32 encodeData = keccak256( abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce) ); _validateSignedData(from, encodeData, v, r, s); authorizationState[from][nonce] = true; emit AuthorizationUsed(from, nonce); _transfer(from, to, value); } function getChainId() public view returns (uint256 chainId) { // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } function getDomainSeparator() public view returns (bytes32) { return keccak256(abi.encode(EIP712DOMAIN_HASH, NAME_HASH, VERSION_HASH, getChainId(), address(this))); } function _changeTimelock(address _timelock) internal { timelock = _timelock; emit TimelockUpdated(_timelock); } function _validateSignedData( address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s ) internal view { bytes32 digest = keccak256(abi.encodePacked("\x19\x01", getDomainSeparator(), encodeData)); address recoveredAddress = ecrecover(digest, v, r, s); // Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages require(recoveredAddress != address(0) && recoveredAddress == signer, "CREDI:INVALID_SIGNATURE"); } function _mint(address to, uint256 value) internal { totalSupply = totalSupply + value; balanceOf[to] = balanceOf[to] + value; emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { // Balance is implicitly checked with Solidity's underflow protection balanceOf[from] = balanceOf[from] - value; totalSupply = totalSupply - value; emit Transfer(from, address(0), value); } function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer( address from, address to, uint256 value ) private { require(to != address(this) && to != address(0), "CREDI:RECEIVER_IS_TOKEN_OR_ZERO"); // Balance is implicitly checked with Solidity's underflow protection balanceOf[from] = balanceOf[from] - value; balanceOf[to] = balanceOf[to] + value; emit Transfer(from, to, value); } }
Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
function _validateSignedData( address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s ) internal view { bytes32 digest = keccak256(abi.encodePacked("\x19\x01", getDomainSeparator(), encodeData)); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == signer, "CREDI:INVALID_SIGNATURE"); }
199,467
//SPDX-License-Identifier: MIT pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct Airline { bool registered; string name; address airlineAddress; } struct Flight { string name; bool registered; address airline; uint256 statusCode; uint256 timestamp; } struct Insurance{ address passenger; uint256 amount; Flight flight; } uint256 private airlineCount = 0; uint256 private insuranceCount = 0; bytes32[] private flightKeys = new bytes32[](0); //Array to track the keys of all registered Flights address[] private insurees = new address[](0); //Array to track all passengers that have purchased insurance mapping(bytes32=>Flight) private flights; //Mapping for keeping track of flights by flightKeys mapping(address => Airline) private airlines; //Mapping for keeping track of airlines mapping(uint => Insurance) private insurances; //Mapping for keeping track of insurances mapping(address => uint256) private payouts; // Mapping for storing insurance refund payouts mapping(address => uint256) private funds; // Mapping for storing funds mapping(address => uint256) private authorizedContracts; //Mapping for storing authorizedContracts that can call this contract. uint256 public constant MAX_INSURANCE_VALUE = 1 ether; //highest value of purchasing flight insurance uint256 public constant MIN_AIRLINE_FUND = 10 ether; //minimum value for airlines to participate in contract /********************************************************************************************/ /* EVENT DEFINITIONS & CONSTRUCTOR */ /********************************************************************************************/ event InsureeCredited(address insuree, uint credit, uint total); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier to check whether function was called from authorized contract */ modifier isAuthorizedCaller(){ require(authorizedContracts[msg.sender] == 1, "Caller is not authorized"); _; } /** * @dev Modifier to check whether insuree is paying within the accurate range of 0 - 1 ether */ modifier accurateInsureePayment(){ require(msg.value > 0 && msg.value <= MAX_INSURANCE_VALUE, "Insuree payment should be between 0 - 1 ether"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /** * @dev Authorizes an external contract to call this contract */ function authorizeCaller(address caller) public view requireContractOwner { require(authorizedContracts[caller] == 0, "Caller already authorized"); authorizedContracts[caller] == 1; } /** * @dev Deauthorizes an external contract to call this contract */ function deauthorizeCaller(address caller) public view requireContractOwner { require(authorizedContracts[caller] == 1, "Caller not initially authorized"); authorizedContracts[caller] == 0; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( string name, address airlineAddress ) external isAuthorizedCaller requireIsOperational { require(!airlines[airlineAddress].registered, "Airline is already registered"); airlines[airlineAddress] = Airline({name: name, registered: true, airlineAddress: airlineAddress}); airlineCount = airlineCount.add(1); } /** * @dev To get the number of airlines registered */ function getAirlineCount() public view returns (uint256) { return airlineCount; } /** * @dev To check whether the specific airline is registered */ function isAirlineRegistered(address wallet) external view returns (bool) { return airlines[wallet].registered; } /** * @dev To check whether the specific airline meets the minimum funds requirement */ function isAirlineFunded(address wallet) external view returns (bool) { return funds[wallet] >= MIN_AIRLINE_FUND; } /** * @dev To check whether the specific flight is already registered */ function isFlightRegistered(string memory name, uint256 timestamp, address airline) public view returns (bool) { bytes32 id = getFlightKey(airline, name, timestamp); return flights[id].registered; } /** * @dev To register flights */ function registerFlight(string name, uint256 timestamp, address airline) external isAuthorizedCaller { bool registered = isFlightRegistered(name, timestamp, airline); require(!registered, "Flight is already registered"); bytes32 id = getFlightKey(airline, name, timestamp); require(!flights[id].registered, "Flight is already registered."); flights[id].name = name; flights[id].registered = true; flights[id].airline = airline; flights[id].statusCode = 0; flights[id].timestamp = timestamp; flightKeys.push(id); } /** * @dev To get the information about the specific airline (this function can be requested from front-end) */ function getFlights() external view returns (string[] memory, address[] memory, uint256[] memory) { uint l = flightKeys.length; string[] memory names = new string[](l); address[] memory airline_addr = new address[](l); uint256[] memory timestamps = new uint256[](l); for (uint i = 0; i < l; ++i) { bytes32 key = flightKeys[i]; names[i] = flights[key].name; airline_addr[i] = flights[key].airline; timestamps[i] = flights[key].timestamp; } return (names, airline_addr, timestamps); } /** * @dev To check any funds owed to the passenger */ function checkFunds(address insuree) external view returns (uint){ return payouts[insuree]; } /** * @dev Buy insurance for a flight * */ function buy ( string flight, uint256 timestamp, address airline, address insuree ) external payable isAuthorizedCaller accurateInsureePayment requireIsOperational { bytes32 id = getFlightKey(airline, flight, timestamp); require(flights[id].registered, "Flight does not exist"); uint insurance_amount = 0; if(msg.value >= MAX_INSURANCE_VALUE){ insurance_amount = MAX_INSURANCE_VALUE; } else { insurance_amount = msg.value; } insurances[insuranceCount].flight = flights[id]; insurances[insuranceCount].passenger = insuree; insurances[insuranceCount].amount = insurance_amount; insuranceCount = insuranceCount.add(1); insurees.push(insuree); } /** * @dev Credits payouts to insurees */ function creditInsurees ( string flight, uint256 timestamp, address airline ) external requireIsOperational { bytes32 id = getFlightKey(airline, flight, timestamp); for (uint i = 0; i < insurees.length; ++i) { address insuree = insurances[i].passenger; bytes32 id2 = getFlightKey(insurances[i].flight.airline, insurances[i].flight.name, insurances[i].flight.timestamp); if(insurances[i].amount == 0) continue; if (id == id2) { uint256 value = insurances[i].amount; uint256 half = value.div(2); insurances[i].amount = 0; uint256 refund = value.add(half); payouts[insuree] = payouts[insuree].add(refund); emit InsureeCredited(insuree, refund, payouts[insuree]); } } } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address insuree ) external isAuthorizedCaller { uint256 refund = payouts[insuree]; payouts[insuree] = 0; insuree.transfer(refund); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address sender ) public payable { require(msg.value > 0, "Funds must be greater than 0"); funds[sender] = funds[sender].add(msg.value); } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function () external payable { require(msg.value > 0, "No funds are not allowed"); fund(msg.sender); } }
To get the number of airlines registered/
function getAirlineCount() public view returns (uint256) { return airlineCount; }
1,842,608
./partial_match/1/0x874b5d6476F214e37f042Cfc555C07fE99c6D83E/sources/StablePlaza.sol
@inheritdoc IStablePlaza/ collect data reusing the function designed for swap data apply binomial series as in {getLPsFromInput} but now for value below 1 calculate minimum amount of LP tokens to be burnt
function getLPsFromOutput( uint256 tokenIndex, uint256 outputAmount ) public view override returns(uint256 minLPamount) { (uint256 R, uint256 d, Config memory c) = _getReservesAndConfig(tokenIndex); outputAmount = (outputAmount - 1) / d + 1; minLPamount = (R_ * LP_FACTOR_REMOVE * (totalSupply() + c.unclaimedRewards) / NORMALIZE_FACTOR >> 128) + 1; }
3,966,650
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./INFTGemMultiToken.sol"; interface INFTGemPoolData { // pool is inited with these parameters. Once inited, all // but ethPrice are immutable. ethPrice only increases. ONLY UP function symbol() external view returns (string memory); function name() external view returns (string memory); function ethPrice() external view returns (uint256); function minTime() external view returns (uint256); function maxTime() external view returns (uint256); function difficultyStep() external view returns (uint256); function maxClaims() external view returns (uint256); // these describe the pools created contents over time. This is where // you query to get information about a token that a pool created function claimedCount() external view returns (uint256); function claimAmount(uint256 claimId) external view returns (uint256); function claimQuantity(uint256 claimId) external view returns (uint256); function mintedCount() external view returns (uint256); function totalStakedEth() external view returns (uint256); function tokenId(uint256 tokenHash) external view returns (uint256); function tokenType(uint256 tokenHash) external view returns (INFTGemMultiToken.TokenType); function allTokenHashesLength() external view returns (uint256); function allTokenHashes(uint256 ndx) external view returns (uint256); function nextClaimHash() external view returns (uint256); function nextGemHash() external view returns (uint256); function nextGemId() external view returns (uint256); function nextClaimId() external view returns (uint256); function claimUnlockTime(uint256 claimId) external view returns (uint256); function claimTokenAmount(uint256 claimId) external view returns (uint256); function stakedToken(uint256 claimId) external view returns (address); function allowedTokensLength() external view returns (uint256); function allowedTokens(uint256 idx) external view returns (address); function isTokenAllowed(address token) external view returns (bool); function addAllowedToken(address token) external; function removeAllowedToken(address token) external; }
pool is inited with these parameters. Once inited, all but ethPrice are immutable. ethPrice only increases. ONLY UP these describe the pools created contents over time. This is where you query to get information about a token that a pool created
interface INFTGemPoolData { function symbol() external view returns (string memory); function name() external view returns (string memory); function ethPrice() external view returns (uint256); function minTime() external view returns (uint256); function maxTime() external view returns (uint256); function difficultyStep() external view returns (uint256); function maxClaims() external view returns (uint256); function claimedCount() external view returns (uint256); function claimAmount(uint256 claimId) external view returns (uint256); function claimQuantity(uint256 claimId) external view returns (uint256); function mintedCount() external view returns (uint256); function totalStakedEth() external view returns (uint256); function tokenId(uint256 tokenHash) external view returns (uint256); function tokenType(uint256 tokenHash) external view returns (INFTGemMultiToken.TokenType); function allTokenHashesLength() external view returns (uint256); function allTokenHashes(uint256 ndx) external view returns (uint256); function nextClaimHash() external view returns (uint256); function nextGemHash() external view returns (uint256); function nextGemId() external view returns (uint256); function nextClaimId() external view returns (uint256); function claimUnlockTime(uint256 claimId) external view returns (uint256); function claimTokenAmount(uint256 claimId) external view returns (uint256); function stakedToken(uint256 claimId) external view returns (address); function allowedTokensLength() external view returns (uint256); function allowedTokens(uint256 idx) external view returns (address); function isTokenAllowed(address token) external view returns (bool); function addAllowedToken(address token) external; function removeAllowedToken(address token) external; pragma solidity >=0.8.0; }
6,385,408
./full_match/80001/0xd3cFB1CE690B52006c90d8425D4EbAa9c86aBC77/sources/contracts/module/RewardVault.sol
Allows the DEFAULT_ADMIN_ROLE to set a new address to the DEFAULT_ADMIN_ROLE. _address The address to which the DEFAULT_ADMIN_ROLE will be granted./
function setRole(address _address) external onlyRole(DEFAULT_ADMIN_ROLE){ _setupRole(DEFAULT_ADMIN_ROLE, _address); }
5,581,736
pragma solidity ^0.5.16; // Inheritance import "./PerpsV2SettingsMixin.sol"; import "./interfaces/IPerpsV2Market.sol"; // Libraries import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "./SignedSafeMath.sol"; import "./SignedSafeDecimalMath.sol"; import "./SafeDecimalMath.sol"; // Internal references import "./interfaces/IExchangeCircuitBreaker.sol"; import "./interfaces/IExchangeRates.sol"; import "./interfaces/IExchanger.sol"; import "./interfaces/ISystemStatus.sol"; import "./interfaces/IERC20.sol"; /* * */ interface IFuturesMarketManagerInternal { function issueSUSD(address account, uint amount) external; function burnSUSD(address account, uint amount) external returns (uint postReclamationAmount); function payFee(uint amount, bytes32 trackingCode) external; } contract PerpsV2MarketBase is PerpsV2SettingsMixin, IPerpsV2BaseTypes { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SignedSafeMath for int; using SignedSafeDecimalMath for int; using SafeDecimalMath for uint; /* ========== CONSTANTS ========== */ // This is the same unit as used inside `SignedSafeDecimalMath`. int private constant _UNIT = int(10**uint(18)); //slither-disable-next-line naming-convention bytes32 internal constant sUSD = "sUSD"; /* ========== STATE VARIABLES ========== */ // The market identifier in the system (manager + settings). Multiple markets can co-exist // for the same asset in order to allow migrations. bytes32 public marketKey; // The asset being traded in this market. This should be a valid key into the ExchangeRates contract. bytes32 public baseAsset; // The total number of base units in long and short positions. uint128 public marketSize; /* * The net position in base units of the whole market. * When this is positive, longs outweigh shorts. When it is negative, shorts outweigh longs. */ int128 public marketSkew; /* * The funding sequence allows constant-time calculation of the funding owed to a given position. * Each entry in the sequence holds the net funding accumulated per base unit since the market was created. * Then to obtain the net funding over a particular interval, subtract the start point's sequence entry * from the end point's sequence entry. * Positions contain the funding sequence entry at the time they were confirmed; so to compute * the net funding on a given position, obtain from this sequence the net funding per base unit * since the position was confirmed and multiply it by the position size. */ uint32 public fundingLastRecomputed; int128[] public fundingSequence; /* * Each user's position. Multiple positions can always be merged, so each user has * only have one position at a time. */ mapping(address => Position) public positions; /// mapping of position id to account addresses mapping(uint => address) public positionIdOwner; /* * This holds the value: sum_{p in positions}{p.margin - p.size * (p.lastPrice + fundingSequence[p.lastFundingIndex])} * Then marketSkew * (price + _nextFundingEntry()) + _entryDebtCorrection yields the total system debt, * which is equivalent to the sum of remaining margins in all positions. */ int128 internal _entryDebtCorrection; // This increments for each position; zero id reflects a position id that wasn't initialized. uint64 public lastPositionId = 0; // Holds the revert message for each type of error. mapping(uint8 => string) internal _errorMessages; bytes32 public constant CONTRACT_NAME = "PerpsV2Market"; /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_CIRCUIT_BREAKER = "ExchangeCircuitBreaker"; bytes32 internal constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 internal constant CONTRACT_FUTURESMARKETMANAGER = "FuturesMarketManager"; bytes32 internal constant CONTRACT_PERPSV2SETTINGS = "PerpsV2Settings"; bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; // convenience struct for passing params between position modification helper functions struct TradeParams { int sizeDelta; uint price; uint baseFee; bytes32 trackingCode; // optional tracking code for volume source fee sharing } /* ========== CONSTRUCTOR ========== */ constructor( address _resolver, bytes32 _baseAsset, bytes32 _marketKey ) public PerpsV2SettingsMixin(_resolver) { baseAsset = _baseAsset; marketKey = _marketKey; // Initialise the funding sequence with 0 initially accrued, so that the first usable funding index is 1. fundingSequence.push(0); // Set up the mapping between error codes and their revert messages. _errorMessages[uint8(Status.InvalidPrice)] = "Invalid price"; _errorMessages[uint8(Status.PriceOutOfBounds)] = "Price out of acceptable range"; _errorMessages[uint8(Status.CanLiquidate)] = "Position can be liquidated"; _errorMessages[uint8(Status.CannotLiquidate)] = "Position cannot be liquidated"; _errorMessages[uint8(Status.MaxMarketSizeExceeded)] = "Max market size exceeded"; _errorMessages[uint8(Status.MaxLeverageExceeded)] = "Max leverage exceeded"; _errorMessages[uint8(Status.InsufficientMargin)] = "Insufficient margin"; _errorMessages[uint8(Status.NotPermitted)] = "Not permitted by this address"; _errorMessages[uint8(Status.NilOrder)] = "Cannot submit empty order"; _errorMessages[uint8(Status.NoPositionOpen)] = "No position open"; _errorMessages[uint8(Status.PriceTooVolatile)] = "Price too volatile"; } /* ========== VIEWS ========== */ /* ---------- External Contracts ---------- */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = PerpsV2SettingsMixin.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](5); newAddresses[0] = CONTRACT_EXCHANGER; newAddresses[1] = CONTRACT_CIRCUIT_BREAKER; newAddresses[2] = CONTRACT_FUTURESMARKETMANAGER; newAddresses[3] = CONTRACT_PERPSV2SETTINGS; newAddresses[4] = CONTRACT_SYSTEMSTATUS; addresses = combineArrays(existingAddresses, newAddresses); } function _exchangeCircuitBreaker() internal view returns (IExchangeCircuitBreaker) { return IExchangeCircuitBreaker(requireAndGetAddress(CONTRACT_CIRCUIT_BREAKER)); } function _exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function _systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function _manager() internal view returns (IFuturesMarketManagerInternal) { return IFuturesMarketManagerInternal(requireAndGetAddress(CONTRACT_FUTURESMARKETMANAGER)); } function _settings() internal view returns (address) { return requireAndGetAddress(CONTRACT_PERPSV2SETTINGS); } /* ---------- Market Details ---------- */ /* * The size of the skew relative to the size of the market skew scaler. * This value can be outside of [-1, 1] values. * Scaler used for skew is at skewScaleUSD to prevent extreme funding rates for small markets. */ function _proportionalSkew(uint price) internal view returns (int) { // marketSize is in baseAsset units so we need to convert from USD units require(price > 0, "price can't be zero"); uint skewScaleBaseAsset = _skewScaleUSD(marketKey).divideDecimal(price); require(skewScaleBaseAsset != 0, "skewScale is zero"); // don't divide by zero return int(marketSkew).divideDecimal(int(skewScaleBaseAsset)); } function _currentFundingRate(uint price) internal view returns (int) { int maxFundingRate = int(_maxFundingRate(marketKey)); // Note the minus sign: funding flows in the opposite direction to the skew. return _min(_max(-_UNIT, -_proportionalSkew(price)), _UNIT).multiplyDecimal(maxFundingRate); } function _unrecordedFunding(uint price) internal view returns (int funding) { int elapsed = int(block.timestamp.sub(fundingLastRecomputed)); // The current funding rate, rescaled to a percentage per second. int currentFundingRatePerSecond = _currentFundingRate(price) / 1 days; return currentFundingRatePerSecond.multiplyDecimal(int(price)).mul(elapsed); } /* * The new entry in the funding sequence, appended when funding is recomputed. It is the sum of the * last entry and the unrecorded funding, so the sequence accumulates running total over the market's lifetime. */ function _nextFundingEntry(uint price) internal view returns (int funding) { return int(fundingSequence[_latestFundingIndex()]).add(_unrecordedFunding(price)); } function _netFundingPerUnit(uint startIndex, uint price) internal view returns (int) { // Compute the net difference between start and end indices. return _nextFundingEntry(price).sub(fundingSequence[startIndex]); } /* ---------- Position Details ---------- */ /* * Determines whether a change in a position's size would violate the max market value constraint. */ function _orderSizeTooLarge( uint maxSize, int oldSize, int newSize ) internal view returns (bool) { // Allow users to reduce an order no matter the market conditions. if (_sameSide(oldSize, newSize) && _abs(newSize) <= _abs(oldSize)) { return false; } // Either the user is flipping sides, or they are increasing an order on the same side they're already on; // we check that the side of the market their order is on would not break the limit. int newSkew = int(marketSkew).sub(oldSize).add(newSize); int newMarketSize = int(marketSize).sub(_signedAbs(oldSize)).add(_signedAbs(newSize)); int newSideSize; if (0 < newSize) { // long case: marketSize + skew // = (|longSize| + |shortSize|) + (longSize + shortSize) // = 2 * longSize newSideSize = newMarketSize.add(newSkew); } else { // short case: marketSize - skew // = (|longSize| + |shortSize|) - (longSize + shortSize) // = 2 * -shortSize newSideSize = newMarketSize.sub(newSkew); } // newSideSize still includes an extra factor of 2 here, so we will divide by 2 in the actual condition if (maxSize < _abs(newSideSize.div(2))) { return true; } return false; } function _notionalValue(int positionSize, uint price) internal pure returns (int value) { return positionSize.multiplyDecimal(int(price)); } function _profitLoss(Position memory position, uint price) internal pure returns (int pnl) { int priceShift = int(price).sub(int(position.lastPrice)); return int(position.size).multiplyDecimal(priceShift); } function _accruedFunding(Position memory position, uint price) internal view returns (int funding) { uint lastModifiedIndex = position.lastFundingIndex; if (lastModifiedIndex == 0) { return 0; // The position does not exist -- no funding. } int net = _netFundingPerUnit(lastModifiedIndex, price); return int(position.size).multiplyDecimal(net); } /* * The initial margin of a position, plus any PnL and funding it has accrued. The resulting value may be negative. */ function _marginPlusProfitFunding(Position memory position, uint price) internal view returns (int) { int funding = _accruedFunding(position, price); return int(position.margin).add(_profitLoss(position, price)).add(funding); } /* * The value in a position's margin after a deposit or withdrawal, accounting for funding and profit. * If the resulting margin would be negative or below the liquidation threshold, an appropriate error is returned. * If the result is not an error, callers of this function that use it to update a position's margin * must ensure that this is accompanied by a corresponding debt correction update, as per `_applyDebtCorrection`. */ function _recomputeMarginWithDelta( Position memory position, uint price, int marginDelta ) internal view returns (uint margin, Status statusCode) { int newMargin = _marginPlusProfitFunding(position, price).add(marginDelta); if (newMargin < 0) { return (0, Status.InsufficientMargin); } uint uMargin = uint(newMargin); int positionSize = int(position.size); // minimum margin beyond which position can be liquidated uint lMargin = _liquidationMargin(positionSize, price); if (positionSize != 0 && uMargin <= lMargin) { return (uMargin, Status.CanLiquidate); } return (uMargin, Status.Ok); } function _remainingMargin(Position memory position, uint price) internal view returns (uint) { int remaining = _marginPlusProfitFunding(position, price); // If the margin went past zero, the position should have been liquidated - return zero remaining margin. return uint(_max(0, remaining)); } function _accessibleMargin(Position memory position, uint price) internal view returns (uint) { // Ugly solution to rounding safety: leave up to an extra tenth of a cent in the account/leverage // This should guarantee that the value returned here can always been withdrawn, but there may be // a little extra actually-accessible value left over, depending on the position size and margin. uint milli = uint(_UNIT / 1000); int maxLeverage = int(_maxLeverage(marketKey).sub(milli)); uint inaccessible = _abs(_notionalValue(position.size, price).divideDecimal(maxLeverage)); // If the user has a position open, we'll enforce a min initial margin requirement. if (0 < inaccessible) { uint minInitialMargin = _minInitialMargin(); if (inaccessible < minInitialMargin) { inaccessible = minInitialMargin; } inaccessible = inaccessible.add(milli); } uint remaining = _remainingMargin(position, price); if (remaining <= inaccessible) { return 0; } return remaining.sub(inaccessible); } /** * The fee charged from the margin during liquidation. Fee is proportional to position size * but is at least the _minKeeperFee() of sUSD to prevent underincentivising * liquidations of small positions. * @param positionSize size of position in fixed point decimal baseAsset units * @param price price of single baseAsset unit in sUSD fixed point decimal units * @return lFee liquidation fee to be paid to liquidator in sUSD fixed point decimal units */ function _liquidationFee(int positionSize, uint price) internal view returns (uint lFee) { // size * price * fee-ratio uint proportionalFee = _abs(positionSize).multiplyDecimal(price).multiplyDecimal(_liquidationFeeRatio()); uint minFee = _minKeeperFee(); // max(proportionalFee, minFee) - to prevent not incentivising liquidations enough return proportionalFee > minFee ? proportionalFee : minFee; // not using _max() helper because it's for signed ints } /** * The minimal margin at which liquidation can happen. Is the sum of liquidationBuffer and liquidationFee * @param positionSize size of position in fixed point decimal baseAsset units * @param price price of single baseAsset unit in sUSD fixed point decimal units * @return lMargin liquidation margin to maintain in sUSD fixed point decimal units * @dev The liquidation margin contains a buffer that is proportional to the position * size. The buffer should prevent liquidation happenning at negative margin (due to next price being worse) * so that stakers would not leak value to liquidators through minting rewards that are not from the * account's margin. */ function _liquidationMargin(int positionSize, uint price) internal view returns (uint lMargin) { uint liquidationBuffer = _abs(positionSize).multiplyDecimal(price).multiplyDecimal(_liquidationBufferRatio()); return liquidationBuffer.add(_liquidationFee(positionSize, price)); } function _canLiquidate(Position memory position, uint price) internal view returns (bool) { // No liquidating empty positions. if (position.size == 0) { return false; } return _remainingMargin(position, price) <= _liquidationMargin(int(position.size), price); } function _currentLeverage( Position memory position, uint price, uint remainingMargin_ ) internal pure returns (int leverage) { // No position is open, or it is ready to be liquidated; leverage goes to nil if (remainingMargin_ == 0) { return 0; } return _notionalValue(position.size, price).divideDecimal(int(remainingMargin_)); } function _orderFee(TradeParams memory params, uint dynamicFeeRate) internal pure returns (uint fee) { // usd value of the difference in position int notionalDiff = params.sizeDelta.multiplyDecimal(int(params.price)); uint feeRate = params.baseFee.add(dynamicFeeRate); return _abs(notionalDiff.multiplyDecimal(int(feeRate))); } /// Uses the exchanger to get the dynamic fee (SIP-184) for trading from sUSD to baseAsset /// this assumes dynamic fee is symmetric in direction of trade. /// @dev this is a pretty expensive action in terms of execution gas as it queries a lot /// of past rates from oracle. Shoudn't be much of an issue on a rollup though. function _dynamicFeeRate() internal view returns (uint feeRate, bool tooVolatile) { return _exchanger().dynamicFeeRateForExchange(sUSD, baseAsset); } function _latestFundingIndex() internal view returns (uint) { return fundingSequence.length.sub(1); // at least one element is pushed in constructor } function _postTradeDetails(Position memory oldPos, TradeParams memory params) internal view returns ( Position memory newPosition, uint fee, Status tradeStatus ) { // Reverts if the user is trying to submit a size-zero order. if (params.sizeDelta == 0) { return (oldPos, 0, Status.NilOrder); } // The order is not submitted if the user's existing position needs to be liquidated. if (_canLiquidate(oldPos, params.price)) { return (oldPos, 0, Status.CanLiquidate); } // get the dynamic fee rate SIP-184 (uint dynamicFeeRate, bool tooVolatile) = _dynamicFeeRate(); if (tooVolatile) { return (oldPos, 0, Status.PriceTooVolatile); } // calculate the total fee for exchange fee = _orderFee(params, dynamicFeeRate); // Deduct the fee. // It is an error if the realised margin minus the fee is negative or subject to liquidation. (uint newMargin, Status status) = _recomputeMarginWithDelta(oldPos, params.price, -int(fee)); if (_isError(status)) { return (oldPos, 0, status); } // construct new position Position memory newPos = Position({ id: oldPos.id, lastFundingIndex: uint64(_latestFundingIndex()), margin: uint128(newMargin), lastPrice: uint128(params.price), size: int128(int(oldPos.size).add(params.sizeDelta)) }); // always allow to decrease a position, otherwise a margin of minInitialMargin can never // decrease a position as the price goes against them. // we also add the paid out fee for the minInitialMargin because otherwise minInitialMargin // is never the actual minMargin, because the first trade will always deduct // a fee (so the margin that otherwise would need to be transferred would have to include the future // fee as well, making the UX and definition of min-margin confusing). bool positionDecreasing = _sameSide(oldPos.size, newPos.size) && _abs(newPos.size) < _abs(oldPos.size); if (!positionDecreasing) { // minMargin + fee <= margin is equivalent to minMargin <= margin - fee // except that we get a nicer error message if fee > margin, rather than arithmetic overflow. if (uint(newPos.margin).add(fee) < _minInitialMargin()) { return (oldPos, 0, Status.InsufficientMargin); } } // check that new position margin is above liquidation margin // (above, in _recomputeMarginWithDelta() we checked the old position, here we check the new one) // Liquidation margin is considered without a fee, because it wouldn't make sense to allow // a trade that will make the position liquidatable. if (newMargin <= _liquidationMargin(newPos.size, params.price)) { return (newPos, 0, Status.CanLiquidate); } // Check that the maximum leverage is not exceeded when considering new margin including the paid fee. // The paid fee is considered for the benefit of UX of allowed max leverage, otherwise, the actual // max leverage is always below the max leverage parameter since the fee paid for a trade reduces the margin. // We'll allow a little extra headroom for rounding errors. { // stack too deep int leverage = int(newPos.size).multiplyDecimal(int(params.price)).divideDecimal(int(newMargin.add(fee))); if (_maxLeverage(marketKey).add(uint(_UNIT) / 100) < _abs(leverage)) { return (oldPos, 0, Status.MaxLeverageExceeded); } } // Check that the order isn't too large for the market. // Allow a bit of extra value in case of rounding errors. if ( _orderSizeTooLarge( uint(int(_maxSingleSideValueUSD(marketKey).add(100 * uint(_UNIT))).divideDecimal(int(params.price))), oldPos.size, newPos.size ) ) { return (oldPos, 0, Status.MaxMarketSizeExceeded); } return (newPos, fee, Status.Ok); } /* ---------- Utilities ---------- */ /* * Absolute value of the input, returned as a signed number. */ function _signedAbs(int x) internal pure returns (int) { return x < 0 ? -x : x; } /* * Absolute value of the input, returned as an unsigned number. */ function _abs(int x) internal pure returns (uint) { return uint(_signedAbs(x)); } function _max(int x, int y) internal pure returns (int) { return x < y ? y : x; } function _min(int x, int y) internal pure returns (int) { return x < y ? x : y; } // True if and only if two positions a and b are on the same side of the market; // that is, if they have the same sign, or either of them is zero. function _sameSide(int a, int b) internal pure returns (bool) { return (a >= 0) == (b >= 0); } /* * True if and only if the given status indicates an error. */ function _isError(Status status) internal pure returns (bool) { return status != Status.Ok; } /* * Revert with an appropriate message if the first argument is true. */ function _revertIfError(bool isError, Status status) internal view { if (isError) { revert(_errorMessages[uint8(status)]); } } /* * Revert with an appropriate message if the input is an error. */ function _revertIfError(Status status) internal view { if (_isError(status)) { revert(_errorMessages[uint8(status)]); } } /* * The current base price from the oracle, and whether that price was invalid. Zero prices count as invalid. * Public because used both externally and internally */ function assetPrice() public view returns (uint price, bool invalid) { (price, invalid) = _exchangeCircuitBreaker().rateWithInvalid(baseAsset); return (price, invalid); } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Market Operations ---------- */ /** * The current base price, reverting if it is invalid, or if system or synth is suspended. * This is mutative because the circuit breaker stores the last price on every invocation. * @param allowMarketPaused if true, checks everything except the specific market, if false * checks only top level checks (system, exchange, futures) */ function _assetPriceRequireSystemChecks(bool allowMarketPaused) internal returns (uint) { // check that market isn't suspended, revert with appropriate message if (allowMarketPaused) { // this will check system activbe, exchange active, futures active _systemStatus().requireFuturesActive(); } else { // this will check all of the above + that specific market is active _systemStatus().requireFuturesMarketActive(marketKey); // asset and market may be different } // TODO: refactor the following when circuit breaker is updated. // The reason both view and mutative are used is because the breaker validates that the // synth exists, and for perps - the there is no synth, so in case of attempting to suspend // the suspension fails (reverts due to "No such synth") // check the view first and revert if price is invalid or out deviation range (uint price, bool invalid) = _exchangeCircuitBreaker().rateWithInvalid(baseAsset); _revertIfError(invalid, Status.InvalidPrice); // note: rateWithBreakCircuit (mutative) is used here in addition to rateWithInvalid (view). // This is despite reverting immediately after if circuit is broken, which may seem silly. // This is in order to persist last-rate in exchangeCircuitBreaker in the happy case // because last-rate is what used for measuring the deviation for subsequent trades. // This also means that the circuit will not be broken in unhappy case (synth suspended) // because this method will revert above. The reason it has to revert is that perps // don't support no-op actions. _exchangeCircuitBreaker().rateWithBreakCircuit(baseAsset); // persist rate for next checks return price; } // default of allowMarketPaused is false, allow calling without this flag function _assetPriceRequireSystemChecks() internal returns (uint) { return _assetPriceRequireSystemChecks(false); } function _recomputeFunding(uint price) internal returns (uint lastIndex) { uint sequenceLengthBefore = fundingSequence.length; int funding = _nextFundingEntry(price); fundingSequence.push(int128(funding)); fundingLastRecomputed = uint32(block.timestamp); emit FundingRecomputed(funding, sequenceLengthBefore, fundingLastRecomputed); return sequenceLengthBefore; } /** * Pushes a new entry to the funding sequence at the current price and funding rate. * @dev Admin only method accessible to FuturesMarketSettings. This is admin only because: * - When system parameters change, funding should be recomputed, but system may be paused * during that time for any reason, so this method needs to work even if system is paused. * But in that case, it shouldn't be accessible to external accounts. */ function recomputeFunding() external returns (uint lastIndex) { // only FuturesMarketSettings is allowed to use this method _revertIfError(msg.sender != _settings(), Status.NotPermitted); // This method uses the view _assetPrice() // and not the mutative _assetPriceRequireSystemChecks() that reverts on system flags. // This is because this method is used by system settings when changing funding related // parameters, so needs to function even when system / market is paused. E.g. to facilitate // market migration. (uint price, bool invalid) = assetPrice(); // A check for a valid price is still in place, to ensure that a system settings action // doesn't take place when the price is invalid (e.g. some oracle issue). require(!invalid, "Invalid price"); return _recomputeFunding(price); } /* * The impact of a given position on the debt correction. */ function _positionDebtCorrection(Position memory position) internal view returns (int) { /** This method only returns the correction term for the debt calculation of the position, and not it's debt. This is needed for keeping track of the _marketDebt() in an efficient manner to allow O(1) marketDebt calculation in _marketDebt(). Explanation of the full market debt calculation from the SIP https://sips.synthetix.io/sips/sip-80/: The overall market debt is the sum of the remaining margin in all positions. The intuition is that the debt of a single position is the value withdrawn upon closing that position. single position remaining margin = initial-margin + profit-loss + accrued-funding = = initial-margin + q * (price - last-price) + q * funding-accrued-per-unit = initial-margin + q * price - q * last-price + q * (funding - initial-funding) Total debt = sum ( position remaining margins ) = sum ( initial-margin + q * price - q * last-price + q * (funding - initial-funding) ) = sum( q * price ) + sum( q * funding ) + sum( initial-margin - q * last-price - q * initial-funding ) = skew * price + skew * funding + sum( initial-margin - q * ( last-price + initial-funding ) ) = skew (price + funding) + sum( initial-margin - q * ( last-price + initial-funding ) ) The last term: sum( initial-margin - q * ( last-price + initial-funding ) ) being the position debt correction that is tracked with each position change using this method. The first term and the full debt calculation using current skew, price, and funding is calculated globally in _marketDebt(). */ return int(position.margin).sub( int(position.size).multiplyDecimal(int(position.lastPrice).add(fundingSequence[position.lastFundingIndex])) ); } function _marketDebt(uint price) internal view returns (uint) { // short circuit and also convenient during setup if (marketSkew == 0 && _entryDebtCorrection == 0) { // if these are 0, the resulting calculation is necessarily zero as well return 0; } // see comment explaining this calculation in _positionDebtCorrection() int priceWithFunding = int(price).add(_nextFundingEntry(price)); int totalDebt = int(marketSkew).multiplyDecimal(priceWithFunding).add(_entryDebtCorrection); return uint(_max(totalDebt, 0)); } /* * Alter the debt correction to account for the net result of altering a position. */ function _applyDebtCorrection(Position memory newPosition, Position memory oldPosition) internal { int newCorrection = _positionDebtCorrection(newPosition); int oldCorrection = _positionDebtCorrection(oldPosition); _entryDebtCorrection = int128(int(_entryDebtCorrection).add(newCorrection).sub(oldCorrection)); } function _transferMargin( int marginDelta, uint price, address sender ) internal { // Transfer no tokens if marginDelta is 0 uint absDelta = _abs(marginDelta); if (marginDelta > 0) { // A positive margin delta corresponds to a deposit, which will be burnt from their // sUSD balance and credited to their margin account. // Ensure we handle reclamation when burning tokens. uint postReclamationAmount = _manager().burnSUSD(sender, absDelta); if (postReclamationAmount != absDelta) { // If balance was insufficient, the actual delta will be smaller marginDelta = int(postReclamationAmount); } } else if (marginDelta < 0) { // A negative margin delta corresponds to a withdrawal, which will be minted into // their sUSD balance, and debited from their margin account. _manager().issueSUSD(sender, absDelta); } else { // Zero delta is a no-op return; } Position storage position = positions[sender]; // initialise id if not initialised and store update id=>account mapping _initPosition(sender, position); // add the margin _updatePositionMargin(position, price, marginDelta); emit MarginTransferred(sender, marginDelta); emit PositionModified(position.id, sender, position.margin, position.size, 0, price, _latestFundingIndex(), 0); } function _initPosition(address account, Position storage position) internal { // if position has no id, give it an incremental id if (position.id == 0) { lastPositionId++; // increment position id uint64 id = lastPositionId; position.id = id; positionIdOwner[id] = account; } } // updates the stored position margin in place (on the stored position) function _updatePositionMargin( Position storage position, uint price, int marginDelta ) internal { Position memory oldPosition = position; // Determine new margin, ensuring that the result is positive. (uint margin, Status status) = _recomputeMarginWithDelta(oldPosition, price, marginDelta); _revertIfError(status); // Update the debt correction. int positionSize = position.size; uint fundingIndex = _latestFundingIndex(); _applyDebtCorrection( Position(0, uint64(fundingIndex), uint128(margin), uint128(price), int128(positionSize)), Position(0, position.lastFundingIndex, position.margin, position.lastPrice, int128(positionSize)) ); // Update the account's position with the realised margin. position.margin = uint128(margin); // We only need to update their funding/PnL details if they actually have a position open if (positionSize != 0) { position.lastPrice = uint128(price); position.lastFundingIndex = uint64(fundingIndex); // The user can always decrease their margin if they have no position, or as long as: // * they have sufficient margin to do so // * the resulting margin would not be lower than the liquidation margin or min initial margin // * the resulting leverage is lower than the maximum leverage if (marginDelta < 0) { _revertIfError( (margin < _minInitialMargin()) || (margin <= _liquidationMargin(position.size, price)) || (_maxLeverage(marketKey) < _abs(_currentLeverage(position, price, margin))), Status.InsufficientMargin ); } } } /* * Alter the amount of margin in a position. A positive input triggers a deposit; a negative one, a * withdrawal. The margin will be burnt or issued directly into/out of the caller's sUSD wallet. * Reverts on deposit if the caller lacks a sufficient sUSD balance. * Reverts on withdrawal if the amount to be withdrawn would expose an open position to liquidation. */ function transferMargin(int marginDelta) external { // allow topping up margin if this specific market is paused. // will still revert on all other checks (system, exchange, futures in general) bool allowMarketPaused = marginDelta > 0; uint price = _assetPriceRequireSystemChecks(allowMarketPaused); _recomputeFunding(price); _transferMargin(marginDelta, price, msg.sender); } /* * Withdraws all accessible margin in a position. This will leave some remaining margin * in the account if the caller has a position open. Equivalent to `transferMargin(-accessibleMargin(sender))`. */ function withdrawAllMargin() external { address sender = msg.sender; uint price = _assetPriceRequireSystemChecks(); _recomputeFunding(price); int marginDelta = -int(_accessibleMargin(positions[sender], price)); _transferMargin(marginDelta, price, sender); } function _trade(address sender, TradeParams memory params) internal { Position storage position = positions[sender]; Position memory oldPosition = position; // Compute the new position after performing the trade (Position memory newPosition, uint fee, Status status) = _postTradeDetails(oldPosition, params); _revertIfError(status); // Update the aggregated market size and skew with the new order size marketSkew = int128(int(marketSkew).add(newPosition.size).sub(oldPosition.size)); marketSize = uint128(uint(marketSize).add(_abs(newPosition.size)).sub(_abs(oldPosition.size))); // Send the fee to the fee pool if (0 < fee) { _manager().payFee(fee, params.trackingCode); // emit tracking code event if (params.trackingCode != bytes32(0)) { emit Tracking(params.trackingCode, baseAsset, marketKey, params.sizeDelta, fee); } } // Update the margin, and apply the resulting debt correction position.margin = newPosition.margin; _applyDebtCorrection(newPosition, oldPosition); // Record the trade uint64 id = oldPosition.id; uint fundingIndex = _latestFundingIndex(); position.size = newPosition.size; position.lastPrice = uint128(params.price); position.lastFundingIndex = uint64(fundingIndex); // emit the modification event emit PositionModified( id, sender, newPosition.margin, newPosition.size, params.sizeDelta, params.price, fundingIndex, fee ); } /* * Adjust the sender's position size. * Reverts if the resulting position is too large, outside the max leverage, or is liquidating. */ function modifyPosition(int sizeDelta) external { _modifyPosition(sizeDelta, bytes32(0)); } /* * Same as modifyPosition, but emits an event with the passed tracking code to * allow offchain calculations for fee sharing with originating integrations */ function modifyPositionWithTracking(int sizeDelta, bytes32 trackingCode) external { _modifyPosition(sizeDelta, trackingCode); } function _modifyPosition(int sizeDelta, bytes32 trackingCode) internal { uint price = _assetPriceRequireSystemChecks(); _recomputeFunding(price); _trade( msg.sender, TradeParams({sizeDelta: sizeDelta, price: price, baseFee: _baseFee(marketKey), trackingCode: trackingCode}) ); } /* * Submit an order to close a position. */ function closePosition() external { _closePosition(bytes32(0)); } /// Same as closePosition, but emits an even with the trackingCode for volume source fee sharing function closePositionWithTracking(bytes32 trackingCode) external { _closePosition(trackingCode); } function _closePosition(bytes32 trackingCode) internal { int size = positions[msg.sender].size; _revertIfError(size == 0, Status.NoPositionOpen); uint price = _assetPriceRequireSystemChecks(); _recomputeFunding(price); _trade( msg.sender, TradeParams({sizeDelta: -size, price: price, baseFee: _baseFee(marketKey), trackingCode: trackingCode}) ); } function _liquidatePosition( address account, address liquidator, uint price ) internal { Position storage position = positions[account]; // get remaining margin for sending any leftover buffer to fee pool uint remMargin = _remainingMargin(position, price); // Record updates to market size and debt. int positionSize = position.size; uint positionId = position.id; marketSkew = int128(int(marketSkew).sub(positionSize)); marketSize = uint128(uint(marketSize).sub(_abs(positionSize))); uint fundingIndex = _latestFundingIndex(); _applyDebtCorrection( Position(0, uint64(fundingIndex), 0, uint128(price), 0), Position(0, position.lastFundingIndex, position.margin, position.lastPrice, int128(positionSize)) ); // Close the position size and margin delete positions[account].size; delete positions[account].margin; // Issue the reward to the liquidator. uint liqFee = _liquidationFee(positionSize, price); _manager().issueSUSD(liquidator, liqFee); emit PositionModified(positionId, account, 0, 0, 0, price, fundingIndex, 0); emit PositionLiquidated(positionId, account, liquidator, positionSize, price, liqFee); // Send any positive margin buffer to the fee pool if (remMargin > liqFee) { _manager().payFee(remMargin.sub(liqFee), bytes32(0)); } } /* * Liquidate a position if its remaining margin is below the liquidation fee. This succeeds if and only if * `canLiquidate(account)` is true, and reverts otherwise. * Upon liquidation, the position will be closed, and the liquidation fee minted into the liquidator's account. */ function liquidatePosition(address account) external { uint price = _assetPriceRequireSystemChecks(); _recomputeFunding(price); _revertIfError(!_canLiquidate(positions[account], price), Status.CannotLiquidate); _liquidatePosition(account, msg.sender, price); } /* ========== EVENTS ========== */ event MarginTransferred(address indexed account, int marginDelta); event PositionModified( uint indexed id, address indexed account, uint margin, int size, int tradeSize, uint lastPrice, uint fundingIndex, uint fee ); event PositionLiquidated( uint indexed id, address indexed account, address indexed liquidator, int size, uint price, uint fee ); event FundingRecomputed(int funding, uint index, uint timestamp); event Tracking(bytes32 indexed trackingCode, bytes32 baseAsset, bytes32 marketKey, int sizeDelta, uint fee); }
default of allowMarketPaused is false, allow calling without this flag
function _assetPriceRequireSystemChecks() internal returns (uint) { return _assetPriceRequireSystemChecks(false); }
12,936,039
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/blueprints/DynamicBlueprint.sol
See {IDynamicBlueprint.updateBlueprintArtist}/
function updateBlueprintArtist(address _newArtist) external override onlyRole(MINTER_ROLE) { artist = _newArtist; }
3,599,359
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721PausableUpgradeable.sol"; import "./interfaces/IRegistrar.sol"; contract Registrar is IRegistrar, OwnableUpgradeable, ERC721PausableUpgradeable { // Data recorded for each domain struct DomainRecord { address minter; bool metadataLocked; address metadataLockedBy; address controller; uint256 royaltyAmount; } // A map of addresses that are authorised to register domains. mapping(address => bool) public controllers; // A mapping of domain id's to domain data // This essentially expands the internal ERC721's token storage to additional fields mapping(uint256 => DomainRecord) public records; modifier onlyController { require(controllers[msg.sender], "Registrar: Not controller"); _; } modifier onlyOwnerOf(uint256 id) { require(ownerOf(id) == msg.sender, "Registrar: Not owner"); _; } function initialize() public initializer { __Ownable_init(); __ERC721Pausable_init(); __ERC721_init("Zero Name Service", "zNS"); // create the root domain _createDomain(0, msg.sender, msg.sender, address(0)); } /* External Methods */ /** @notice Authorizes a controller to control the registrar @param controller The address of the controller */ function addController(address controller) external override onlyOwner { require(!controllers[controller], "Registrar: Controller is already added"); controllers[controller] = true; emit ControllerAdded(controller); } /** @notice Unauthorizes a controller to control the registrar @param controller The address of the controller */ function removeController(address controller) external override onlyOwner { require(controllers[controller], "Registrar: Controller does not exist"); controllers[controller] = false; emit ControllerRemoved(controller); } /** @notice Pauses the registrar. Can only be done when not paused. */ function pause() external onlyOwner { _pause(); } /** @notice Unpauses the registrar. Can only be done when not paused. */ function unpause() external onlyOwner { _unpause(); } /** @notice Registers a new (sub) domain @param parentId The parent domain @param name The name of the domain @param domainOwner the owner of the new domain @param minter the minter of the new domain */ function registerDomain( uint256 parentId, string memory name, address domainOwner, address minter ) external override onlyController returns (uint256) { require(bytes(name).length > 0, "Registrar: Empty name"); // Create the child domain under the parent domain uint256 labelHash = uint256(keccak256(bytes(name))); address controller = msg.sender; // Domain parents must exist require(_exists(parentId), "Registrar: No parent"); // Calculate the new domain's id and create it uint256 domainId = uint256(keccak256(abi.encodePacked(parentId, labelHash))); _createDomain(domainId, domainOwner, minter, controller); emit DomainCreated(domainId, name, labelHash, parentId, minter, controller); return domainId; } /** @notice Sets the domain royalty amount @param id The domain to set on @param amount The royalty amount */ function setDomainRoyaltyAmount(uint256 id, uint256 amount) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "Registrar: Metadata locked"); records[id].royaltyAmount = amount; emit RoyaltiesAmountChanged(id, amount); } /** @notice Sets the domain metadata uri @param id The domain to set on @param uri The uri to set */ function setDomainMetadataUri(uint256 id, string memory uri) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "Registrar: Metadata locked"); _setTokenURI(id, uri); emit MetadataChanged(id, uri); } /** @notice Locks a domains metadata uri @param id The domain to lock */ function lockDomainMetadata(uint256 id) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "Registrar: Metadata locked"); _lockMetadata(id, msg.sender); } /** @notice Locks a domains metadata uri on behalf the owner @param id The domain to lock */ function lockDomainMetadataForOwner(uint256 id) external override onlyController { require(!isDomainMetadataLocked(id), "Registrar: Metadata locked"); address domainOwner = ownerOf(id); _lockMetadata(id, domainOwner); } /** @notice Unlocks a domains metadata uri @param id The domain to unlock */ function unlockDomainMetadata(uint256 id) external override { require(isDomainMetadataLocked(id), "Registrar: Not locked"); require(domainMetadataLockedBy(id) == msg.sender, "Registrar: Not locker"); _unlockMetadata(id); } /* Public View */ /** @notice Returns whether or not a domain is available to be created @param id The domain */ function isAvailable(uint256 id) public view override returns (bool) { bool notRegistered = !_exists(id); return notRegistered; } /** @notice Returns whether or not a domain is exists @param id The domain */ function domainExists(uint256 id) public view override returns (bool) { bool domainNftExists = _exists(id); return domainNftExists; } /** @notice Returns the original minter of a domain @param id The domain */ function minterOf(uint256 id) public view override returns (address) { address minter = records[id].minter; return minter; } /** @notice Returns whether or not a domain's metadata is locked @param id The domain */ function isDomainMetadataLocked(uint256 id) public view override returns (bool) { bool isLocked = records[id].metadataLocked; return isLocked; } /** @notice Returns who locked a domain's metadata @param id The domain */ function domainMetadataLockedBy(uint256 id) public view override returns (address) { address lockedBy = records[id].metadataLockedBy; return lockedBy; } /** @notice Returns the controller which created the domain on behalf of a user @param id The domain */ function domainController(uint256 id) public view override returns (address) { address controller = records[id].controller; return controller; } /** @notice Returns the current royalty amount for a domain @param id The domain */ function domainRoyaltyAmount(uint256 id) public view override returns (uint256) { uint256 amount = records[id].royaltyAmount; return amount; } /* Internal Methods */ // internal - creates a domain function _createDomain( uint256 domainId, address domainOwner, address minter, address controller ) internal { // Create the NFT and register the domain data _safeMint(domainOwner, domainId); records[domainId] = DomainRecord({ minter: minter, metadataLocked: false, metadataLockedBy: address(0), controller: controller, royaltyAmount: 0 }); } // internal - locks a domains metadata function _lockMetadata(uint256 id, address locker) internal { records[id].metadataLocked = true; records[id].metadataLockedBy = locker; emit MetadataLocked(id, locker); } // internal - unlocks a domains metadata function _unlockMetadata(uint256 id) internal { records[id].metadataLocked = false; records[id].metadataLockedBy = address(0); emit MetadataUnlocked(id); } } // 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.0 <0.8.0; import "./ERC721Upgradeable.sol"; import "../../utils/PausableUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable { function __ERC721Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); } function __ERC721Pausable_init_unchained() internal initializer { } /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721MetadataUpgradeable.sol"; interface IRegistrar is IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { // Emitted when a controller is removed event ControllerAdded(address indexed controller); // Emitted whenever a controller is removed event ControllerRemoved(address indexed controller); // Emitted whenever a new domain is created event DomainCreated( uint256 indexed id, string name, uint256 indexed nameHash, uint256 indexed parent, address minter, address controller ); // Emitted whenever the metadata of a domain is locked event MetadataLocked(uint256 indexed id, address locker); // Emitted whenever the metadata of a domain is unlocked event MetadataUnlocked(uint256 indexed id); // Emitted whenever the metadata of a domain is changed event MetadataChanged(uint256 indexed id, string uri); // Emitted whenever the royalty amount is changed event RoyaltiesAmountChanged(uint256 indexed id, uint256 amount); // Authorises a controller, who can register domains. function addController(address controller) external; // Revoke controller permission for an address. function removeController(address controller) external; // Registers a new sub domain function registerDomain( uint256 parentId, string memory name, address domainOwner, address minter ) external returns (uint256); // Lock a domains metadata from being modified, can only be called by domain owner and if the metadata is unlocked function lockDomainMetadata(uint256 id) external; // Utility function to lock a domains metadata, used by controllers instead of a user. function lockDomainMetadataForOwner(uint256 id) external; // Unlocks a domains metadata, can only be called by the address that locked the metadata function unlockDomainMetadata(uint256 id) external; // Sets a domains metadata uri function setDomainMetadataUri(uint256 id, string memory uri) external; // Sets the asked royalty amount on a domain (amount is a percentage with 5 decimal places) function setDomainRoyaltyAmount(uint256 id, uint256 amount) external; // Checks whether or not a domain exists function domainExists(uint256 id) external view returns (bool); // Whether or not a domain specific by an id is available. function isAvailable(uint256 id) external view returns (bool); // Returns the original minter of a domain function minterOf(uint256 id) external view returns (address); // Checks if a domains metadata is locked function isDomainMetadataLocked(uint256 id) external view returns (bool); // Returns the address which locked the domain metadata function domainMetadataLockedBy(uint256 id) external view returns (address); // Gets the controller that registered a domain function domainController(uint256 id) external view returns (address); // Gets a domains current royalty amount function domainRoyaltyAmount(uint256 id) external view 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 // 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; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721Upgradeable.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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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( IERC721ReceiverUpgradeable(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(ERC721Upgradeable.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 { } uint256[41] private __gap; } // 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 pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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 "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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 "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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 IERC721ReceiverUpgradeable { /** * @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 "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // 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; /** * @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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // 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 EnumerableMapUpgradeable { // 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 StringsUpgradeable { /** * @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 IERC165Upgradeable { /** * @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); }
internal - unlocks a domains metadata
function _unlockMetadata(uint256 id) internal { records[id].metadataLocked = false; records[id].metadataLockedBy = address(0); emit MetadataUnlocked(id); }
14,511,259
pragma solidity ^0.4.23; /** * @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 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } contract ClockAuctionBase { function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external; function isSaleAuction() public returns (bool); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: 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)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _account address of the account to check * @return whether the target address is a contract */ function isContract(address _account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_account) } return size > 0; } } contract CardBase is Ownable { bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ( (_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceId_ERC721Exists) ); } } contract CardMint is CardBase { using AddressUtils for address; /* EVENTS */ event TemplateMint(uint256 _templateId); // Transfer from address 0x0 = newly minted card. event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /* DATA TYPES */ struct Template { uint256 generation; uint256 category; uint256 variation; string name; } /* STORAGE */ // Minter address can mint cards but not templates. address public minter; Template[] internal templates; // Each Card is a template ID (index of a template in `templates`). uint256[] internal cards; // Template ID => max number of cards that can be minted with this template ID. mapping (uint256 => uint256) internal templateIdToMintLimit; // Template ID => number of cards that have been minted with this template ID. mapping (uint256 => uint256) internal templateIdToMintCount; // Card ID => owner of card. mapping (uint256 => address) internal cardIdToOwner; // Owner => number of cards owner owns. mapping (address => uint256) internal ownerToCardCount; // Card ID => address approved to transfer on behalf of owner. mapping (uint256 => address) internal cardIdToApproved; // Operator => from address to operated or not. mapping (address => mapping (address => bool)) internal operatorToApprovals; /* MODIFIERS */ modifier onlyMinter() { require(msg.sender == minter); _; } /* FUNCTIONS */ /** PRIVATE FUNCTIONS **/ function _addTokenTo(address _to, uint256 _tokenId) internal { require(cardIdToOwner[_tokenId] == address(0)); ownerToCardCount[_to] = ownerToCardCount[_to] + 1; cardIdToOwner[_tokenId] = _to; } /** PUBLIC FUNCTIONS **/ function setMinter(address _minter) external onlyOwner { minter = _minter; } function mintTemplate( uint256 _mintLimit, uint256 _generation, uint256 _category, uint256 _variation, string _name ) external onlyOwner { require(_mintLimit > 0); uint256 newTemplateId = templates.push(Template({ generation: _generation, category: _category, variation: _variation, name: _name })) - 1; templateIdToMintLimit[newTemplateId] = _mintLimit; emit TemplateMint(newTemplateId); } function mintCard( uint256 _templateId, address _owner ) external onlyMinter { require(templateIdToMintCount[_templateId] < templateIdToMintLimit[_templateId]); templateIdToMintCount[_templateId] = templateIdToMintCount[_templateId] + 1; uint256 newCardId = cards.push(_templateId) - 1; _addTokenTo(_owner, newCardId); emit Transfer(0, _owner, newCardId); } function mintCards( uint256[] _templateIds, address _owner ) external onlyMinter { uint256 mintCount = _templateIds.length; uint256 templateId; for (uint256 i = 0; i < mintCount; ++i) { templateId = _templateIds[i]; require(templateIdToMintCount[templateId] < templateIdToMintLimit[templateId]); templateIdToMintCount[templateId] = templateIdToMintCount[templateId] + 1; uint256 newCardId = cards.push(templateId) - 1; cardIdToOwner[newCardId] = _owner; emit Transfer(0, _owner, newCardId); } // Bulk add to ownerToCardCount. ownerToCardCount[_owner] = ownerToCardCount[_owner] + mintCount; } } contract CardOwnership is CardMint { /* FUNCTIONS */ /** PRIVATE FUNCTIONS **/ function _approve(address _owner, address _approved, uint256 _tokenId) internal { cardIdToApproved[_tokenId] = _approved; emit Approval(_owner, _approved, _tokenId); } function _clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (cardIdToApproved[_tokenId] != address(0)) { cardIdToApproved[_tokenId] = address(0); } } function _removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownerToCardCount[_from] = ownerToCardCount[_from] - 1; cardIdToOwner[_tokenId] = address(0); } /** PUBLIC FUNCTIONS **/ function approve(address _to, uint256 _tokenId) external { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _approve(owner, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); require(_to != address(this)); _clearApproval(_from, _tokenId); _removeTokenFrom(_from, _tokenId); _addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == 0x150b7a02); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _operator operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _operator, bool _approved) public { require(_operator != msg.sender); require(_operator != address(0)); operatorToApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return cardIdToApproved[_tokenId]; } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorToApprovals[_owner][_operator]; } function ownerOf(uint256 _tokenId) public view returns (address) { address owner = cardIdToOwner[_tokenId]; require(owner != address(0)); return owner; } function exists(uint256 _tokenId) public view returns (bool) { address owner = cardIdToOwner[_tokenId]; return owner != address(0); } } contract CardAuction is CardOwnership { ClockAuctionBase public saleAuction; function setSaleAuction(address _address) external onlyOwner { ClockAuctionBase candidateContract = ClockAuctionBase(_address); require(candidateContract.isSaleAuction()); saleAuction = candidateContract; } function createSaleAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external { require(saleAuction != address(0)); require(msg.sender == cardIdToOwner[_tokenId]); _approve(msg.sender, saleAuction, _tokenId); saleAuction.createAuction( _tokenId, _startingPrice, _endingPrice, _duration, msg.sender ); } } contract CardTreasury is CardAuction { /* FUNCTIONS */ /** PUBLIC FUNCTIONS **/ function getTemplate(uint256 _templateId) external view returns ( uint256 generation, uint256 category, uint256 variation, string name ) { require(_templateId < templates.length); Template storage template = templates[_templateId]; generation = template.generation; category = template.category; variation = template.variation; name = template.name; } function getCard(uint256 _cardId) external view returns ( uint256 generation, uint256 category, uint256 variation, string name ) { require(_cardId < cards.length); uint256 templateId = cards[_cardId]; Template storage template = templates[templateId]; generation = template.generation; category = template.category; variation = template.variation; name = template.name; } function templateIdOf(uint256 _cardId) external view returns (uint256) { require(_cardId < cards.length); return cards[_cardId]; } function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownerToCardCount[_owner]; } function templateSupply() external view returns (uint256) { return templates.length; } function totalSupply() external view returns (uint256) { return cards.length; } function mintLimitByTemplate(uint256 _templateId) external view returns(uint256) { require(_templateId < templates.length); return templateIdToMintLimit[_templateId]; } function mintCountByTemplate(uint256 _templateId) external view returns(uint256) { require(_templateId < templates.length); return templateIdToMintCount[_templateId]; } function name() external pure returns (string) { return "Battlebound"; } function symbol() external pure returns (string) { return "BB"; } function tokensOfOwner(address _owner) external view returns (uint256[]) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; for (uint256 cardId = 0; cardId < cards.length; ++cardId) { if (cardIdToOwner[cardId] == _owner) { result[resultIndex] = cardId; ++resultIndex; } } return result; } } function templatesOfOwner(address _owner) external view returns (uint256[]) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; for (uint256 cardId = 0; cardId < cards.length; ++cardId) { if (cardIdToOwner[cardId] == _owner) { uint256 templateId = cards[cardId]; result[resultIndex] = templateId; ++resultIndex; } } return result; } } function variationsOfOwner(address _owner) external view returns (uint256[]) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; for (uint256 cardId = 0; cardId < cards.length; ++cardId) { if (cardIdToOwner[cardId] == _owner) { uint256 templateId = cards[cardId]; Template storage template = templates[templateId]; result[resultIndex] = template.variation; ++resultIndex; } } return result; } } }
PUBLIC FUNCTIONS /
function approve(address _to, uint256 _tokenId) external { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _approve(owner, _to, _tokenId); }
6,433,043
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "./Token.sol"; contract banco { Token private token; mapping(address => uint256) public depositStart; mapping(address => uint256) public etherBalanceOf; mapping(address => bool) public isDeposited; event Deposit(address indexed user, uint256 etherAmount, uint256 timeSeart); event Withdraw( address indexed user, uint256 etherAmount, uint256 depositTime, uint256 interest ); constructor(Token _token) public { token = _token; } function deposit() public payable { require(isDeposited[msg.sender] == false, "Error, account deposited"); require(msg.value >= 1e16, "Error, amount must be >= 0.01 ETH"); etherBalanceOf[msg.sender] += msg.value; depositStart[msg.sender] += block.timestamp; isDeposited[msg.sender] = true; emit Deposit(msg.sender, msg.value, block.timestamp); } function withdraw() public { require(isDeposited[msg.sender] == true, "Error, account not deposited"); uint256 userBalance = etherBalanceOf[msg.sender]; uint256 depositTime = block.timestamp - depositStart[msg.sender]; //calculation below // uint256 interestPerSecond = (etherBalanceOf[msg.sender] / 1e16); uint256 interestPerSecond = userBalance / 100; uint256 interest = interestPerSecond * depositTime; payable(msg.sender).transfer(etherBalanceOf[msg.sender]); token.mint(msg.sender, interest); depositStart[msg.sender] = 0; etherBalanceOf[msg.sender] = 0; isDeposited[msg.sender] = false; emit Withdraw(msg.sender, userBalance, depositTime, interest); } }
calculation below uint256 interestPerSecond = (etherBalanceOf[msg.sender] / 1e16);
function withdraw() public { require(isDeposited[msg.sender] == true, "Error, account not deposited"); uint256 userBalance = etherBalanceOf[msg.sender]; uint256 depositTime = block.timestamp - depositStart[msg.sender]; uint256 interestPerSecond = userBalance / 100; uint256 interest = interestPerSecond * depositTime; payable(msg.sender).transfer(etherBalanceOf[msg.sender]); token.mint(msg.sender, interest); depositStart[msg.sender] = 0; etherBalanceOf[msg.sender] = 0; isDeposited[msg.sender] = false; emit Withdraw(msg.sender, userBalance, depositTime, interest); }
1,032,882
pragma solidity ^0.4.24; import "./SafeMathLib.sol"; /** * @title FeesLib * @dev Library for managing fees on any contract, it handles fees percentages with minimum and maximum amount, * on eth blockchain having parts per X as percentage storing the two parts of the fraction. */ library FeesLib { using SafeMathLib for uint; // fee as parts per X units, e.g. 2 per 1000 = 0.2% struct FeeStorage { // e.g. 0.1% => [1] per 1000, this is 1 uint parts_Fee; // e.g. 0.1% => 1 per [1000], this is 1000 uint perX_Fee; // minimum fee in tokens that are the minimum unit number in smart contract uint min_Fee; // maximum fee in tokens that are the maximum unit number in smart contract, if zero is disabled uint max_Fee; // fees enabled/disabled bool feesEnabled; } /** * @dev initTransferFees, given all required parameters in the same order as they are declared in the FeeStorage struct. * @param _parts_Fee Parts component of the fee percentage * @param _perX_Fee Per X component of the fee percentage * @param _min_Fee Mininmum amount of tokens for the fee * @param _max_Fee Maximum amount of tokens for the fee, zero means no maximum * @param _feesEnabled Are fees enables? * @return bool */ function init(FeeStorage storage self, uint _parts_Fee, uint _perX_Fee, uint _min_Fee, uint _max_Fee, bool _feesEnabled) internal returns (bool) { if (self.parts_Fee != _parts_Fee) self.parts_Fee = _parts_Fee; if (self.perX_Fee != _perX_Fee) self.perX_Fee = _perX_Fee; if (self.min_Fee != _min_Fee) self.min_Fee = _min_Fee; if (self.max_Fee != _max_Fee) self.max_Fee = _max_Fee; if (self.feesEnabled != _feesEnabled) self.feesEnabled = _feesEnabled; return true; } /** * @dev CalculateFee, given token amount, calculate transfer fee in units/tokens that are cents or pennies * @param tokens Tokens amount to calculate fees for * @return uint */ function calculateFee(FeeStorage storage self, uint tokens) internal view returns (uint fee) { if (!self.feesEnabled) return 0; fee = tokens.percent(self.parts_Fee, self.perX_Fee); //filter fee to minimum amount of tokens/pennies allowed if (self.feesEnabled && fee < self.min_Fee) { fee = self.min_Fee; } //filter fee to maximum amount of tokens/pennies allowed if greater than zero if (self.feesEnabled && self.max_Fee > 0 && fee > self.max_Fee) { fee = self.max_Fee; } } /** * @dev Get minimum fee tokens/pennies/cents * @return uint */ function getMinFee(FeeStorage storage self) internal view returns (uint) { return self.min_Fee; } /** * @dev Get maximum fee tokens/pennies/cents * @return uint */ function getMaxFee(FeeStorage storage self) internal view returns (uint) { return self.max_Fee; } /** * @dev Change minimum fee tokens/pennies/cents * @param newMinFee Minimum amount of tokens to be set as minimum * @return bool */ function setMinFee(FeeStorage storage self, uint newMinFee) internal returns (bool) { if (self.min_Fee != newMinFee) { self.min_Fee = newMinFee; return true; } return false; } /** * @dev Change maximum fee tokens/pennies/cents * @param newMaxFee Maximum amount of tokens to be set as maximum * @return bool */ function setMaxFee(FeeStorage storage self, uint newMaxFee) internal returns (bool) { if (self.max_Fee != newMaxFee) { self.max_Fee = newMaxFee; return true; } return false; } /** * @dev Enable/Disable fees * @return bool */ function enableFees(FeeStorage storage self, bool enable) internal returns (bool) { if (self.feesEnabled != enable) { self.feesEnabled = enable; return true; } return false; } /** * @dev Set fees as parts per X units * @param _parts_Fee Parts component of the fee percentage * @param _perX_Fee Per X component of the fee percentage * @return bool */ function setFees(FeeStorage storage self, uint _parts_Fee, uint _perX_Fee) internal returns (bool) { // at least one factor has to be different for change to be allowed, what's the point of setting the same values anyway? require(_parts_Fee != self.parts_Fee || _perX_Fee != self.perX_Fee, "FeesLib._setFees: required _parts_Fee != self.parts_Fee || _perX_Fee != self.perX_Fee"); require(_perX_Fee > 0, "FeesLib._setFees: required _perX_Fee > 0"); require(_parts_Fee < _perX_Fee, "FeesLib._setFees: required _parts_Fee < _perX_Fee"); self.parts_Fee = _parts_Fee; self.perX_Fee = _perX_Fee; return true; } }
initTransferFees, given all required parameters in the same order as they are declared in the FeeStorage struct. _parts_Fee Parts component of the fee percentage _perX_Fee Per X component of the fee percentage _min_Fee Mininmum amount of tokens for the fee _max_Fee Maximum amount of tokens for the fee, zero means no maximum _feesEnabled Are fees enables? return bool/
function init(FeeStorage storage self, uint _parts_Fee, uint _perX_Fee, uint _min_Fee, uint _max_Fee, bool _feesEnabled) internal returns (bool) { if (self.parts_Fee != _parts_Fee) self.parts_Fee = _parts_Fee; if (self.perX_Fee != _perX_Fee) self.perX_Fee = _perX_Fee; if (self.min_Fee != _min_Fee) self.min_Fee = _min_Fee; if (self.max_Fee != _max_Fee) self.max_Fee = _max_Fee; if (self.feesEnabled != _feesEnabled) self.feesEnabled = _feesEnabled; return true; }
2,507,255
pragma solidity ^0.5.0; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/lifecycle/Pausable.sol'; import '@openzeppelin/contracts/introspection/IERC165.sol'; import './TokenBuyInterface.sol'; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) public; function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; function mintLand(address to, uint256 OVRLandID) public returns (bool); } contract Ownable { address payable public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } constructor () internal { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } function transferOwnership(address payable _newOwner) public onlyOwner { require(_newOwner != address(0), "Ownable: new owner can't be the zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /// The ICO contract to run auctions and buy OVRLands (ERC721) after winning in exchange for OVRTokens (ERC20) /// Also handles land sells and purchases for people that want to exchange their land once they got it contract ICO is Ownable, Pausable, IERC721Receiver { using SafeMath for uint256; // Default state is NOT_STARTED enum AuctionState { NOT_STARTED, ACTIVE, ENDED } enum LandOfferState { NOT_STARTED, ACTIVE, ACCEPTED, DECLINED, EXPIRED, CANCELLED } struct Land { address payable owner; uint256 landToBuy; uint256 paid; uint256 lastBidTimestamp; AuctionState state; uint256 cashbackAmount; bool isCashbackRedeemed; // Marketplace functionality uint256 sellPrice; bool onSale; bool hasBeenRedeemed; uint256 lastUpdateTimestamp; uint256 paidWith; uint256 amountToReturn; // How many tokens or eth to return if outbidded } struct LandOffer { uint256 id; // The unique land offer identifier address payable by; uint256 group; // Unique counter for group orders to desactive those after 1 has been approved uint256 landId; uint256 price; uint256 timestamp; uint256 expirationDate; LandOfferState state; } event WonLand(address indexed winner, uint256 indexed landId, uint256 price); event LandSaleStarted(address indexed owner, uint256 indexed landId, uint256 price); event CashbackRedeemed(uint256 indexed landId, address indexed receiver, uint256 amount, uint256 timestamp); // For lands that have been on sale but were removed by the owner event LandSaleCancelled(address indexed owner, uint256 indexed landId); event LandOfferCreated(uint256 indexed id, address indexed by, uint256 indexed landId, uint256 price, uint256 timestamp, uint256 expirationDate); event LandSold(uint256 indexed landId, address indexed oldOwner, address indexed buyer, uint256 price, uint256 timestamp); event LandOfferDeclined(uint256 indexed landOfferId, uint256 indexed landId); event LandOfferCancelled(uint256 indexed offerId); address public ovrToken; address public ovrLand; address public tokenBuy; address public approved; uint256 public initialLandBid; uint256 public lastLandOfferId; // A counter for setting up ids // When the contract was created required for calculating cashbacks uint256 public contractCreationDate; // LandID => Land mapping (uint256 => Land) public lands; // User => a list of owned land ids mapping (address => uint256[]) public ownedLands; // User => how many tokens he can cashback with redeemCashback() mapping (address => uint256) public cashbacks; // LandID => All the LandOffer IDS each landId has mapping (uint256 => uint256[]) public landOfferIds; // LandOfferId => LandOffer mapping (uint256 => LandOffer) public landOffers; // LandID => groupCounter mapping (uint256 => uint256) public groupCounters; // Lands that have initiated the auction process can be either active or ended uint256[] public activeLands; uint256 public auctionLandDuration = 24 hours; // Default 24 hours // Lands that are on sale or have been sold previously // This array is immutable meaning it won't delete already existing ids // because it's a very gas consuming process. // When a land is sold, the pointed Land id from `lands` is updated // There can be multiple instances of the same id inside so filter them in js uint256[] public landsOnSaleOrSold; modifier onlyApproved { require(msg.sender == approved); _; } constructor(address _ovrToken, address _ovrLand, address _tokenBuy, uint256 _initialLandBid) public { require(_ovrToken != address(0), "The OVR ERC20 token address can't be empty"); require(_ovrLand != address(0), "The OVR land ERC721 token address can't be empty"); require(_tokenBuy != address(0), "The TokenBuy contract address can't be empty"); require(_initialLandBid != 0, "The initial land bid can't be zero"); ovrToken = _ovrToken; ovrLand = _ovrLand; tokenBuy = _tokenBuy; initialLandBid = _initialLandBid; contractCreationDate = now; } function setApproved(address _approved) public onlyOwner { approved = _approved; } /// Sets the duration of each land auction function setAuctionLandDuration(uint256 _time) public onlyOwner { require(_time > 0, "The auction duration can't be zero"); auctionLandDuration = _time; } /// To redeem the land that you won in an auction function redeemWonLand(uint256 _landId) public whenNotPaused { Land storage land = lands[_landId]; if (now.sub(land.lastBidTimestamp) >= auctionLandDuration) { land.state = AuctionState.ENDED; } require(land.state == AuctionState.ENDED, "You can't redeem this land until its auction is finished"); require(land.owner == msg.sender, 'You must be the land winner to redeem it'); uint256 cashbackPercentage; uint256 monthPurchasedSinceBeginning = now.sub(contractCreationDate).div(30 days) + 1; if (monthPurchasedSinceBeginning == 1) { cashbackPercentage = 95; } else if (monthPurchasedSinceBeginning == 2) { cashbackPercentage = 85; } else if (monthPurchasedSinceBeginning == 3) { cashbackPercentage = 75; } else if (monthPurchasedSinceBeginning == 4) { cashbackPercentage = 65; } else if (monthPurchasedSinceBeginning == 5) { cashbackPercentage = 55; } else if (monthPurchasedSinceBeginning == 6) { cashbackPercentage = 45; } else if (monthPurchasedSinceBeginning == 7) { cashbackPercentage = 35; } else if (monthPurchasedSinceBeginning == 8) { cashbackPercentage = 25; } else if (monthPurchasedSinceBeginning == 9) { cashbackPercentage = 15; } else { cashbackPercentage = 0; } uint256 cashback = land.paid.mul(cashbackPercentage).div(100); cashbacks[msg.sender] = cashbacks[msg.sender].add(cashback); land.cashbackAmount = cashback; land.hasBeenRedeemed = true; // Transfer the land to the user IERC721(ovrLand).mintLand(msg.sender, _landId); ownedLands[msg.sender].push(_landId); emit WonLand(msg.sender, _landId, land.paid); } function redeemBulkLands(uint256[] memory _landIds) public whenNotPaused { for (uint256 i = 0; i < _landIds.length; i++) { redeemWonLand(_landIds[i]); } } /// To get your cashback for the buyers in the initial 9 months /// @param _landId The land whose cashback you want to get function redeemCashback(uint256 _landId) public whenNotPaused { Land storage land = lands[_landId]; require(!land.isCashbackRedeemed, 'The cashback has already been redeemed for this land'); require(land.hasBeenRedeemed, 'The land must be redeemed before getting its cashback'); require(land.owner == msg.sender, 'You must be the land owner to redeem its cashback'); require(now.sub(land.lastBidTimestamp) >= 30 days, "You can't redeem a cashback before 30 days"); uint256 tempAmount = land.cashbackAmount; cashbacks[msg.sender] = cashbacks[msg.sender].sub(land.cashbackAmount); land.isCashbackRedeemed = true; land.cashbackAmount = 0; IERC20(ovrToken).transfer(msg.sender, tempAmount); emit CashbackRedeemed(_landId, msg.sender, land.cashbackAmount, now); } /// To extract the tokens that may have been sent to this contract by accident function extractTokens(address _tokenToExtract, uint256 _amount) public onlyOwner whenNotPaused { IERC20(_tokenToExtract).transfer(owner, _amount); } function extractEth() public onlyOwner whenNotPaused { owner.transfer(address(this).balance); } /// To put on sell a land you own /// Note: the price can be 0 to give it away for free /// The seller must approve the ERC721 token to the ICO contract ONLY if _onSale is true /// @param _onSale To indicate whether you want to put it on sale or remove it from the sale function putLandOnSale(uint256 _landId, uint256 _price, bool _onSale) public whenNotPaused { Land storage land = lands[_landId]; require(msg.sender == land.owner, 'You must be the land owner to put it on sale'); require(land.state == AuctionState.ENDED, 'The land auction must have been completed to put it on sale'); if (_onSale) { address _approved = IERC721(ovrLand).getApproved(_landId); require(_approved == address(this), 'You must approve this contract to manage your ERC721 token'); } land.onSale = _onSale; land.sellPrice = _price; land.lastUpdateTimestamp = now; landsOnSaleOrSold.push(_landId); if (_onSale) { IERC721(ovrLand).safeTransferFrom(msg.sender, address(this), _landId); emit LandSaleStarted(land.owner, _landId, _price); } else { IERC721(ovrLand).safeTransferFrom(address(this), msg.sender, _landId); emit LandSaleCancelled(land.owner, _landId); } } /// To buy a land on sale /// The buyer must approve the land price in OVR tokens to purchase it beforehand function buyLand(uint256 _landId) public whenNotPaused { Land storage land = lands[_landId]; address oldOwner = land.owner; uint256 salePrice = land.sellPrice; uint256 allowance = IERC20(ovrToken).allowance(msg.sender, address(this)); require(land.onSale, 'The land must be on sale to buy it'); require(allowance >= land.sellPrice, 'You must approve the right amount of OVR tokens to buy this land'); require(land.state == AuctionState.ENDED, 'The land auction must have been completed to buy it'); land.owner = msg.sender; land.onSale = false; land.sellPrice = 0; land.lastUpdateTimestamp = now; IERC20(ovrToken).transferFrom(msg.sender, oldOwner, salePrice); IERC721(ovrLand).safeTransferFrom(address(this), msg.sender, _landId); emit LandSold(_landId, oldOwner, msg.sender, salePrice, now); } /// To offer someone to buy his land for a specific price /// it doesn't matter if the land is on sale or not, this offer will be sent regardless /// If the user already has an existing offer, override it with this new one /// The frontend will have to get all the offers and check those made by the same person to only keep /// the most recent one by looking at the timestamp function offerToBuyLand(uint256 _landId, uint256 _price, uint256 _expirationDate) public whenNotPaused { Land storage land = lands[_landId]; uint256 allowance = IERC20(ovrToken).allowance(msg.sender, address(this)); require(land.state == AuctionState.ENDED, 'The land auction must have been completed to send the offer to buy it'); require(allowance >= _price, 'You must approve the right amount of OVR tokens to offer to buy it'); require(_expirationDate > now, 'The expiration date must be larger than now'); lastLandOfferId++; LandOffer memory newOffer = LandOffer(lastLandOfferId, msg.sender, groupCounters[_landId], _landId, _price, now, _expirationDate, LandOfferState.ACTIVE); landOffers[lastLandOfferId] = newOffer; landOfferIds[_landId].push(lastLandOfferId); emit LandOfferCreated(lastLandOfferId, msg.sender, _landId, _price, now, _expirationDate); } /// To cancel buy offers function cancelBuyOffer(uint256 _offerId) public whenNotPaused { LandOffer storage offer = landOffers[_offerId]; require(msg.sender == offer.by, 'You must be the owner to cancel the buy offer'); offer.state = LandOfferState.CANCELLED; emit LandOfferCancelled(_offerId); } /// To respond to a buy land offer independently on whether your land is on sale or not /// kinda like ebay does it with the custom buy offers function respondToBuyOffer(uint256 _landOfferId, bool _accept) public whenNotPaused { LandOffer storage landOffer = landOffers[_landOfferId]; Land storage land = lands[landOffer.landId]; require(landOffer.state == LandOfferState.ACTIVE, 'The offer must be active to be able to respond to it'); require(landOffer.expirationDate > now, 'The offer is expired'); require(land.owner == msg.sender, 'You must be the owner to accept the land offer'); if (_accept) { address _approved = IERC721(ovrLand).getApproved(land.landToBuy); require(_approved == address(this), 'You must approve this contract to manage your ERC721 token'); emit LandSold(land.landToBuy, land.owner, landOffer.by, landOffer.price, now); IERC20(ovrToken).transferFrom(landOffer.by, land.owner, landOffer.price); IERC721(ovrLand).safeTransferFrom(land.owner, landOffer.by, land.landToBuy); landOffer.state = LandOfferState.ACCEPTED; land.owner = landOffer.by; land.onSale = false; land.sellPrice = 0; groupCounters[landOffer.landId]++; } else { landOffer.state = LandOfferState.DECLINED; emit LandOfferDeclined(_landOfferId, land.landToBuy); } } /// To update the lands value array function setLands( address payable owner, uint256 landToBuy, uint256 paid, AuctionState state, uint256 paidWith, uint256 amountToReturn ) public onlyApproved { lands[landToBuy] = Land(owner, landToBuy, paid, now, state, 0, false, 0, false, false, now, paidWith, amountToReturn); } function pushActiveLand(uint256 _landId) public onlyApproved { activeLands.push(_landId); } /// Returns an array with the the landOfferIds for a given land id /// you can check each independently using the array ownedLands function checkMyLandOffers(uint256 _landId) public view returns(uint256[] memory) { return landOfferIds[_landId]; } /// Returns the landIds you won so you know which landIds you can redeem function checkWonLands() public view returns(uint256[] memory) { uint256[] memory result; uint256 counter = 0; for(uint256 i = 0; i < activeLands.length; i++) { uint256 landId = activeLands[i]; if (lands[landId].state == AuctionState.ENDED && lands[landId].owner == msg.sender) { result[counter] = landId; counter = counter.add(1); } } return result; } /// Checks if the token you want to buy is within the epoch available /// @return bool True if it's in a valid epoch and false if not function checkEpoch(uint256 _landId) public view returns(bool) { uint256 currentMonth = now.sub(contractCreationDate).div(30) + 1; // Extract the last 2 digits uint256 landIdDigits = _landId % 100; if (currentMonth == 1) { if (landIdDigits <= 17) { return true; } else { return false; } } else if (currentMonth == 2) { if (landIdDigits > 17 && landIdDigits <= 35) { return true; } else { return false; } } else if (currentMonth == 3) { if (landIdDigits > 35 && landIdDigits <= 53) { return true; } else { return false; } } else if (currentMonth == 4) { if (landIdDigits > 53 && landIdDigits <= 70) { return true; } else { return false; } } else if (currentMonth == 5) { if (landIdDigits > 70 && landIdDigits <= 88) { return true; } else { return false; } } else if (currentMonth == 6) { if (landIdDigits > 88 && landIdDigits <= 99) { return true; } else { return false; } } return true; } function getActiveLands() public view returns(uint256[] memory) { return activeLands; } function getLandsOnSaleOrSold() public view returns(uint256[] memory) { return landsOnSaleOrSold; } function getLandOffers(uint256 _landId) public view returns(uint256[] memory) { return landOfferIds[_landId]; } function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4) { // Both return values work return this.onERC721Received.selector; // return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } } contract ICOParticipate is Ownable, Pausable { using SafeMath for uint256; event AuctionStarted(address indexed lastBidder, uint256 indexed landToBuy, uint256 paid, uint256 timestamp); event AuctionBid(address indexed newBidder, address indexed oldBidder, uint256 indexed landToBuy, uint256 paid, uint256 timestamp); address public ovrLand; address public tokenBuy; IERC20 public ovrToken; IERC20 public dai; IERC20 public usdt; IERC20 public usdc; uint256 public tokensPerUsd; uint256 public ethPrice; ICO public ico; constructor (address _ico) public { ico = ICO(_ico); ovrLand = ico.ovrLand(); tokenBuy = ico.tokenBuy(); ovrToken = IERC20(ico.ovrToken()); dai = IERC20(TokenBuyInterface(tokenBuy).daiToken()); usdt = IERC20(TokenBuyInterface(tokenBuy).usdtToken()); usdc = IERC20(TokenBuyInterface(tokenBuy).usdcToken()); updateTokenBuyValues(); } function updateTokenBuyValues() public { tokensPerUsd = TokenBuyInterface(tokenBuy).tokensPerUsd() / 2; ethPrice = TokenBuyInterface(tokenBuy).ethPrice(); } function participate (uint256 _token, uint256 _bid, uint256 _landId) public payable whenNotPaused { updateTokenBuyValues(); if (msg.value > 0) { uint256 calculatedBid = msg.value.mul(ethPrice).mul(tokensPerUsd) + 1; require(calculatedBid >= _bid, 'You must send more or equal the value of tokens to buy'); } require(ico.checkEpoch(_landId), "This land isn't available at the current epoch"); require(_bid > 0 || msg.value > 0, "The bid can't be zero"); (,,, uint256 lastBidTimestamp, ICO.AuctionState state,,,,,,,,) = ico.lands(_landId); if (state == ICO.AuctionState.NOT_STARTED) { require(_bid >= ico.initialLandBid(), 'The bid must be larger or equal the initial minimum'); participateNewAuction(_token, _bid, _landId); } else if (state == ICO.AuctionState.ACTIVE) { require(now.sub(lastBidTimestamp) < ico.auctionLandDuration(), 'This land auction has ended'); participateActiveAuction(_token, _bid, _landId); } else if (state == ICO.AuctionState.ENDED) { revert('The auction has ended for this land 1'); } else { revert('The auction has ended for this land 2'); } } function participateActiveAuction (uint256 _token, uint256 _bid, uint256 _landId) internal whenNotPaused { (address payable oldBidder,, uint256 oldBid,, ICO.AuctionState state,,,,,,, uint256 paidWith, uint256 amountToReturn) = ico.lands(_landId); require(_bid >= oldBid.mul(2), 'Your bid must be equal or larger than double the previous one'); // Transfer the new tokens if (_token == 1) { dai.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 2) { usdt.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 3) { usdc.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 4) { ovrToken.transferFrom(msg.sender, address(this), _bid); } if (paidWith == 0) { ico.setLands(msg.sender, _landId, _bid, state, _token, msg.value); } else { ico.setLands(msg.sender, _landId, _bid, state, _token, _bid.div(tokensPerUsd)); } // Return previous bidder's tokens if (paidWith == 0) { oldBidder.transfer(amountToReturn); } else if (paidWith == 1) { dai.transfer(oldBidder, amountToReturn); } else if (paidWith == 2) { usdt.transfer(oldBidder, amountToReturn); } else if (paidWith == 3) { usdc.transfer(oldBidder, amountToReturn); } else if (paidWith == 4) { ovrToken.transfer(oldBidder, oldBid); } emit AuctionBid(msg.sender, oldBidder, _landId, _bid, now); } function participateNewAuction (uint256 _token, uint256 _bid, uint256 _landId) internal whenNotPaused { if (_token == 0) { ico.setLands(msg.sender, _landId, _bid, ICO.AuctionState.ACTIVE, _token, msg.value); } else { ico.setLands(msg.sender, _landId, _bid, ICO.AuctionState.ACTIVE, _token, _bid.div(tokensPerUsd)); } if (_token == 1) { dai.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 2) { usdt.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 3) { usdc.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 4) { ovrToken.transferFrom(msg.sender, address(this), _bid); } ico.pushActiveLand(_landId); emit AuctionStarted(msg.sender, _landId, _bid, now); } /// To extract the tokens that may have been sent to this contract by accident function extractTokens(address _tokenToExtract, uint256 _amount) public onlyOwner whenNotPaused { IERC20(_tokenToExtract).transfer(owner, _amount); } function extractEth() public onlyOwner whenNotPaused { owner.transfer(address(this).balance); } }
To get your cashback for the buyers in the initial 9 months _landId The land whose cashback you want to get
function redeemCashback(uint256 _landId) public whenNotPaused { Land storage land = lands[_landId]; require(!land.isCashbackRedeemed, 'The cashback has already been redeemed for this land'); require(land.hasBeenRedeemed, 'The land must be redeemed before getting its cashback'); require(land.owner == msg.sender, 'You must be the land owner to redeem its cashback'); require(now.sub(land.lastBidTimestamp) >= 30 days, "You can't redeem a cashback before 30 days"); uint256 tempAmount = land.cashbackAmount; cashbacks[msg.sender] = cashbacks[msg.sender].sub(land.cashbackAmount); land.isCashbackRedeemed = true; land.cashbackAmount = 0; IERC20(ovrToken).transfer(msg.sender, tempAmount); emit CashbackRedeemed(_landId, msg.sender, land.cashbackAmount, now); }
12,638,969
./partial_match/1/0xCCF27D3FfF920D999Cc7e8a3fc847a96BCa44cCd/sources/StandardToken.sol
Moves tokens `amount` from `sender` to `recipient`./
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] + amount; emit Transfer(sender, recipient, amount); }
2,705,673
// File: contracts/libraries/Math.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.12; library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/libraries/SafeMath256.sol pragma solidity 0.6.12; library SafeMath256 { /** * @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; } } // File: contracts/libraries/DecFloat32.sol pragma solidity 0.6.12; /* This library defines a decimal floating point number. It has 8 decimal significant digits. Its maximum value is 9.9999999e+15. And its minimum value is 1.0e-16. The following golang code explains its detail implementation. func buildPrice(significant int, exponent int) uint32 { if !(10000000 <= significant && significant <= 99999999) { panic("Invalid significant") } if !(-16 <= exponent && exponent <= 15) { panic("Invalid exponent") } return uint32(((exponent+16)<<27)|significant); } func priceToFloat(price uint32) float64 { exponent := int(price>>27) significant := float64(price&((1<<27)-1)) return significant * math.Pow10(exponent-23) } */ // A price presented as a rational number struct RatPrice { uint numerator; // at most 54bits uint denominator; // at most 76bits } library DecFloat32 { uint32 public constant MANTISSA_MASK = (1<<27) - 1; uint32 public constant MAX_MANTISSA = 9999_9999; uint32 public constant MIN_MANTISSA = 1000_0000; uint32 public constant MIN_PRICE = MIN_MANTISSA; uint32 public constant MAX_PRICE = (31<<27)|MAX_MANTISSA; // 10 ** (i + 1) function powSmall(uint32 i) internal pure returns (uint) { uint x = 2695994666777834996822029817977685892750687677375768584125520488993233305610; return (x >> (32*i)) & ((1<<32)-1); } // 10 ** (i * 8) function powBig(uint32 i) internal pure returns (uint) { uint y = 3402823669209384634633746076162356521930955161600000001; return (y >> (64*i)) & ((1<<64)-1); } // if price32=( 0<<27)|12345678 then numerator=12345678 denominator=100000000000000000000000 // if price32=( 1<<27)|12345678 then numerator=12345678 denominator=10000000000000000000000 // if price32=( 2<<27)|12345678 then numerator=12345678 denominator=1000000000000000000000 // if price32=( 3<<27)|12345678 then numerator=12345678 denominator=100000000000000000000 // if price32=( 4<<27)|12345678 then numerator=12345678 denominator=10000000000000000000 // if price32=( 5<<27)|12345678 then numerator=12345678 denominator=1000000000000000000 // if price32=( 6<<27)|12345678 then numerator=12345678 denominator=100000000000000000 // if price32=( 7<<27)|12345678 then numerator=12345678 denominator=10000000000000000 // if price32=( 8<<27)|12345678 then numerator=12345678 denominator=1000000000000000 // if price32=( 9<<27)|12345678 then numerator=12345678 denominator=100000000000000 // if price32=(10<<27)|12345678 then numerator=12345678 denominator=10000000000000 // if price32=(11<<27)|12345678 then numerator=12345678 denominator=1000000000000 // if price32=(12<<27)|12345678 then numerator=12345678 denominator=100000000000 // if price32=(13<<27)|12345678 then numerator=12345678 denominator=10000000000 // if price32=(14<<27)|12345678 then numerator=12345678 denominator=1000000000 // if price32=(15<<27)|12345678 then numerator=12345678 denominator=100000000 // if price32=(16<<27)|12345678 then numerator=12345678 denominator=10000000 // if price32=(17<<27)|12345678 then numerator=12345678 denominator=1000000 // if price32=(18<<27)|12345678 then numerator=12345678 denominator=100000 // if price32=(19<<27)|12345678 then numerator=12345678 denominator=10000 // if price32=(20<<27)|12345678 then numerator=12345678 denominator=1000 // if price32=(21<<27)|12345678 then numerator=12345678 denominator=100 // if price32=(22<<27)|12345678 then numerator=12345678 denominator=10 // if price32=(23<<27)|12345678 then numerator=12345678 denominator=1 // if price32=(24<<27)|12345678 then numerator=123456780 denominator=1 // if price32=(25<<27)|12345678 then numerator=1234567800 denominator=1 // if price32=(26<<27)|12345678 then numerator=12345678000 denominator=1 // if price32=(27<<27)|12345678 then numerator=123456780000 denominator=1 // if price32=(28<<27)|12345678 then numerator=1234567800000 denominator=1 // if price32=(29<<27)|12345678 then numerator=12345678000000 denominator=1 // if price32=(30<<27)|12345678 then numerator=123456780000000 denominator=1 // if price32=(31<<27)|12345678 then numerator=1234567800000000 denominator=1 function expandPrice(uint32 price32) internal pure returns (RatPrice memory) { uint s = price32&((1<<27)-1); uint32 a = price32 >> 27; RatPrice memory price; if(a >= 24) { uint32 b = a - 24; price.numerator = s * powSmall(b); price.denominator = 1; } else if(a == 23) { price.numerator = s; price.denominator = 1; } else { uint32 b = 22 - a; price.numerator = s; price.denominator = powSmall(b&0x7) * powBig(b>>3); } return price; } function getExpandPrice(uint price) internal pure returns(uint numerator, uint denominator) { uint32 m = uint32(price) & MANTISSA_MASK; require(MIN_MANTISSA <= m && m <= MAX_MANTISSA, "Invalid Price"); RatPrice memory actualPrice = expandPrice(uint32(price)); return (actualPrice.numerator, actualPrice.denominator); } } // File: contracts/libraries/ProxyData.sol pragma solidity 0.6.12; library ProxyData { uint public constant COUNT = 5; uint public constant INDEX_FACTORY = 0; uint public constant INDEX_MONEY_TOKEN = 1; uint public constant INDEX_STOCK_TOKEN = 2; uint public constant INDEX_ONES = 3; uint public constant INDEX_OTHER = 4; uint public constant OFFSET_PRICE_DIV = 0; uint public constant OFFSET_PRICE_MUL = 64; uint public constant OFFSET_STOCK_UNIT = 64+64; uint public constant OFFSET_IS_ONLY_SWAP = 64+64+64; function factory(uint[5] memory proxyData) internal pure returns (address) { return address(proxyData[INDEX_FACTORY]); } function money(uint[5] memory proxyData) internal pure returns (address) { return address(proxyData[INDEX_MONEY_TOKEN]); } function stock(uint[5] memory proxyData) internal pure returns (address) { return address(proxyData[INDEX_STOCK_TOKEN]); } function ones(uint[5] memory proxyData) internal pure returns (address) { return address(proxyData[INDEX_ONES]); } function priceMul(uint[5] memory proxyData) internal pure returns (uint64) { return uint64(proxyData[INDEX_OTHER]>>OFFSET_PRICE_MUL); } function priceDiv(uint[5] memory proxyData) internal pure returns (uint64) { return uint64(proxyData[INDEX_OTHER]>>OFFSET_PRICE_DIV); } function stockUnit(uint[5] memory proxyData) internal pure returns (uint64) { return uint64(proxyData[INDEX_OTHER]>>OFFSET_STOCK_UNIT); } function isOnlySwap(uint[5] memory proxyData) internal pure returns (bool) { return uint8(proxyData[INDEX_OTHER]>>OFFSET_IS_ONLY_SWAP) != 0; } function fill(uint[5] memory proxyData, uint expectedCallDataSize) internal pure { uint size; // solhint-disable-next-line no-inline-assembly assembly { size := calldatasize() } require(size == expectedCallDataSize, "INVALID_CALLDATASIZE"); // solhint-disable-next-line no-inline-assembly assembly { let offset := sub(size, 160) calldatacopy(proxyData, offset, 160) } } } // File: contracts/interfaces/IOneSwapFactory.sol pragma solidity 0.6.12; interface IOneSwapFactory { event PairCreated(address indexed pair, address stock, address money, bool isOnlySwap); function createPair(address stock, address money, bool isOnlySwap) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setFeeBPS(uint32 bps) external; function setPairLogic(address implLogic) external; function allPairsLength() external view returns (uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function feeBPS() external view returns (uint32); function pairLogic() external returns (address); function getTokensFromPair(address pair) external view returns (address stock, address money); function tokensToPair(address stock, address money, bool isOnlySwap) external view returns (address pair); } // File: contracts/interfaces/IERC20.sol pragma solidity 0.6.12; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts/interfaces/IOneSwapToken.sol pragma solidity 0.6.12; interface IOneSwapBlackList { event OwnerChanged(address); event AddedBlackLists(address[]); event RemovedBlackLists(address[]); function owner()external view returns (address); function newOwner()external view returns (address); function isBlackListed(address)external view returns (bool); function changeOwner(address ownerToSet) external; function updateOwner() external; function addBlackLists(address[] calldata accounts)external; function removeBlackLists(address[] calldata accounts)external; } interface IOneSwapToken is IERC20, IOneSwapBlackList{ function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function multiTransfer(uint256[] calldata mixedAddrVal) external returns (bool); } // File: contracts/interfaces/IOneSwapPair.sol pragma solidity 0.6.12; interface IOneSwapERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IOneSwapPool { // more liquidity was minted event Mint(address indexed sender, uint stockAndMoneyAmount, address indexed to); // liquidity was burned event Burn(address indexed sender, uint stockAndMoneyAmount, address indexed to); // amounts of reserved stock and money in this pair changed event Sync(uint reserveStockAndMoney); function internalStatus() external view returns(uint[3] memory res); function getReserves() external view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID); function getBooked() external view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID); function stock() external returns (address); function money() external returns (address); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint stockAmount, uint moneyAmount); function skim(address to) external; function sync() external; } interface IOneSwapPair { event NewLimitOrder(uint data); // new limit order was sent by an account event NewMarketOrder(uint data); // new market order was sent by an account event OrderChanged(uint data); // old orders in orderbook changed event DealWithPool(uint data); // new order deal with the AMM pool event RemoveOrder(uint data); // an order was removed from the orderbook // Return three prices in rational number form, i.e., numerator/denominator. // They are: the first sell order's price; the first buy order's price; the current price of the AMM pool. function getPrices() external returns ( uint firstSellPriceNumerator, uint firstSellPriceDenominator, uint firstBuyPriceNumerator, uint firstBuyPriceDenominator, uint poolPriceNumerator, uint poolPriceDenominator); // This function queries a list of orders in orderbook. It starts from 'id' and iterates the single-linked list, util it reaches the end, // or until it has found 'maxCount' orders. If 'id' is 0, it starts from the beginning of the single-linked list. // It may cost a lot of gas. So you'd not to call in on chain. It is mainly for off-chain query. // The first uint256 returned by this function is special: the lowest 24 bits is the first order's id and the the higher bits is block height. // THe other uint256s are all corresponding to an order record of the single-linked list. function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external view returns (uint[] memory); // remove an order from orderbook and return its booked (i.e. frozen) money to maker // 'id' points to the order to be removed // prevKey points to 3 previous orders in the single-linked list function removeOrder(bool isBuy, uint32 id, uint72 positionID) external; function removeOrders(uint[] calldata rmList) external; // Try to deal a new limit order or insert it into orderbook // its suggested order id is 'id' and suggested positions are in 'prevKey' // prevKey points to 3 existing orders in the single-linked list // the order's sender is 'sender'. the order's amount is amount*stockUnit, which is the stock amount to be sold or bought. // the order's price is 'price32', which is decimal floating point value. function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable; // Try to deal a new market order. 'sender' pays 'inAmount' of 'inputToken', in exchange of the other token kept by this pair function addMarketOrder(address inputToken, address sender, uint112 inAmount) external payable returns (uint); // Given the 'amount' of stock and decimal floating point price 'price32', calculate the 'stockAmount' and 'moneyAmount' to be traded function calcStockAndMoney(uint64 amount, uint32 price32) external pure returns (uint stockAmount, uint moneyAmount); } // File: contracts/OneSwapPair.sol pragma solidity 0.6.12; abstract contract OneSwapERC20 is IOneSwapERC20 { using SafeMath256 for uint; uint internal _unusedVar0; uint internal _unusedVar1; uint internal _unusedVar2; uint internal _unusedVar3; uint internal _unusedVar4; uint internal _unusedVar5; uint internal _unusedVar6; uint internal _unusedVar7; uint internal _unusedVar8; uint internal _unusedVar9; uint internal _unlocked = 1; modifier lock() { require(_unlocked == 1, "OneSwap: LOCKED"); _unlocked = 0; _; _unlocked = 1; } string private constant _NAME = "OneSwap-Liquidity-Share"; uint8 private constant _DECIMALS = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; function symbol() virtual external override returns (string memory); function name() external view override returns (string memory) { return _NAME; } function decimals() external view override returns (uint8) { return _DECIMALS; } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != uint(- 1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } // An order can be compressed into 256 bits and saved using one SSTORE instruction // The orders form a single-linked list. The preceding order points to the following order with nextID struct Order { //total 256 bits address sender; //160 bits, sender creates this order uint32 price; // 32-bit decimal floating point number uint64 amount; // 42 bits are used, the stock amount to be sold or bought uint32 nextID; // 22 bits are used } // When the match engine of orderbook runs, it uses follow context to cache data in memory struct Context { // this order is a limit order bool isLimitOrder; // the new order's id, it is only used when a limit order is not fully dealt uint32 newOrderID; // for buy-order, it's remained money amount; for sell-order, it's remained stock amount uint remainAmount; // it points to the first order in the opposite order book against current order uint32 firstID; // it points to the first order in the buy-order book uint32 firstBuyID; // it points to the first order in the sell-order book uint32 firstSellID; // the amount goes into the pool, for buy-order, it's money amount; for sell-order, it's stock amount uint amountIntoPool; // the total dealt money and stock in the order book uint dealMoneyInBook; uint dealStockInBook; // cache these values from storage to memory uint reserveMoney; uint reserveStock; uint bookedMoney; uint bookedStock; // reserveMoney or reserveStock is changed bool reserveChanged; // the taker has dealt in the orderbook bool hasDealtInOrderBook; // the current taker order Order order; // the following data come from proxy uint64 stockUnit; uint64 priceMul; uint64 priceDiv; address stockToken; address moneyToken; address ones; address factory; } // OneSwapPair combines a Uniswap-like AMM and an orderbook abstract contract OneSwapPool is OneSwapERC20, IOneSwapPool { using SafeMath256 for uint; uint private constant _MINIMUM_LIQUIDITY = 10 ** 3; bytes4 internal constant _SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); // reserveMoney and reserveStock are both uint112, id is 22 bits; they are compressed into a uint256 word uint internal _reserveStockAndMoneyAndFirstSellID; // bookedMoney and bookedStock are both uint112, id is 22 bits; they are compressed into a uint256 word uint internal _bookedStockAndMoneyAndFirstBuyID; uint private _kLast; uint32 private constant _OS = 2; // owner's share uint32 private constant _LS = 3; // liquidity-provider's share function internalStatus() external override view returns(uint[3] memory res) { res[0] = _reserveStockAndMoneyAndFirstSellID; res[1] = _bookedStockAndMoneyAndFirstBuyID; res[2] = _kLast; } function stock() external override returns (address) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); return ProxyData.stock(proxyData); } function money() external override returns (address) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); return ProxyData.money(proxyData); } // the following 4 functions load&store compressed storage function getReserves() public override view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) { uint temp = _reserveStockAndMoneyAndFirstSellID; reserveStock = uint112(temp); reserveMoney = uint112(temp>>112); firstSellID = uint32(temp>>224); } function _setReserves(uint stockAmount, uint moneyAmount, uint32 firstSellID) internal { require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "OneSwap: OVERFLOW"); uint temp = (moneyAmount<<112)|stockAmount; emit Sync(temp); temp = (uint(firstSellID)<<224)| temp; _reserveStockAndMoneyAndFirstSellID = temp; } function getBooked() public override view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID) { uint temp = _bookedStockAndMoneyAndFirstBuyID; bookedStock = uint112(temp); bookedMoney = uint112(temp>>112); firstBuyID = uint32(temp>>224); } function _setBooked(uint stockAmount, uint moneyAmount, uint32 firstBuyID) internal { require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "OneSwap: OVERFLOW"); _bookedStockAndMoneyAndFirstBuyID = (uint(firstBuyID)<<224)|(moneyAmount<<112)|stockAmount; } function _myBalance(address token) internal view returns (uint) { if(token==address(0)) { return address(this).balance; } else { return IERC20(token).balanceOf(address(this)); } } // safely transfer ERC20 tokens, or ETH (when token==0) function _safeTransfer(address token, address to, uint value, address ones) internal { if(token==address(0)) { // limit gas to 9000 to prevent gastoken attacks // solhint-disable-next-line avoid-low-level-calls to.call{value: value, gas: 9000}(new bytes(0)); //we ignore its return value purposely return; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR, to, value)); success = success && (data.length == 0 || abi.decode(data, (bool))); if(!success) { // for failsafe address onesOwner = IOneSwapToken(ones).owner(); // solhint-disable-next-line avoid-low-level-calls (success, data) = token.call(abi.encodeWithSelector(_SELECTOR, onesOwner, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "OneSwap: TRANSFER_FAILED"); } } // Give feeTo some liquidity tokens if K got increased since last liquidity-changing function _mintFee(uint112 _reserve0, uint112 _reserve1, uint[5] memory proxyData) private returns (bool feeOn) { address feeTo = IOneSwapFactory(ProxyData.factory(proxyData)).feeTo(); feeOn = feeTo != address(0); uint kLast = _kLast; // gas savings to use cached kLast if (feeOn) { if (kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(_OS); uint denominator = rootK.mul(_LS).add(rootKLast.mul(_OS)); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (kLast != 0) { _kLast = 0; } } // mint new liquidity tokens to 'to' function mint(address to) external override lock returns (uint liquidity) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1)); (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); (uint112 bookedStock, uint112 bookedMoney, ) = getBooked(); uint stockBalance = _myBalance(ProxyData.stock(proxyData)); uint moneyBalance = _myBalance(ProxyData.money(proxyData)); require(stockBalance >= uint(bookedStock) + uint(reserveStock) && moneyBalance >= uint(bookedMoney) + uint(reserveMoney), "OneSwap: INVALID_BALANCE"); stockBalance -= uint(bookedStock); moneyBalance -= uint(bookedMoney); uint stockAmount = stockBalance - uint(reserveStock); uint moneyAmount = moneyBalance - uint(reserveMoney); bool feeOn = _mintFee(reserveStock, reserveMoney, proxyData); uint _totalSupply = totalSupply; // gas savings by caching totalSupply in memory, // must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(stockAmount.mul(moneyAmount)).sub(_MINIMUM_LIQUIDITY); _mint(address(0), _MINIMUM_LIQUIDITY); // permanently lock the first _MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(stockAmount.mul(_totalSupply) / uint(reserveStock), moneyAmount.mul(_totalSupply) / uint(reserveMoney)); } require(liquidity > 0, "OneSwap: INSUFFICIENT_MINTED"); _mint(to, liquidity); _setReserves(stockBalance, moneyBalance, firstSellID); if (feeOn) _kLast = stockBalance.mul(moneyBalance); emit Mint(msg.sender, (moneyAmount<<112)|stockAmount, to); } // burn liquidity tokens and send stock&money to 'to' function burn(address to) external override lock returns (uint stockAmount, uint moneyAmount) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1)); (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint stockBalance = _myBalance(ProxyData.stock(proxyData)).sub(bookedStock); uint moneyBalance = _myBalance(ProxyData.money(proxyData)).sub(bookedMoney); require(stockBalance >= uint(reserveStock) && moneyBalance >= uint(reserveMoney), "OneSwap: INVALID_BALANCE"); bool feeOn = _mintFee(reserveStock, reserveMoney, proxyData); { uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee uint liquidity = balanceOf[address(this)]; // we're sure liquidity < totalSupply stockAmount = liquidity.mul(stockBalance) / _totalSupply; moneyAmount = liquidity.mul(moneyBalance) / _totalSupply; require(stockAmount > 0 && moneyAmount > 0, "OneSwap: INSUFFICIENT_BURNED"); //_burn(address(this), liquidity); balanceOf[address(this)] = 0; totalSupply = totalSupply.sub(liquidity); emit Transfer(address(this), address(0), liquidity); } address ones = ProxyData.ones(proxyData); _safeTransfer(ProxyData.stock(proxyData), to, stockAmount, ones); _safeTransfer(ProxyData.money(proxyData), to, moneyAmount, ones); stockBalance = stockBalance - stockAmount; moneyBalance = moneyBalance - moneyAmount; _setReserves(stockBalance, moneyBalance, firstSellID); if (feeOn) _kLast = stockBalance.mul(moneyBalance); emit Burn(msg.sender, (moneyAmount<<112)|stockAmount, to); } // take the extra money&stock in this pair to 'to' function skim(address to) external override lock { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1)); address stockToken = ProxyData.stock(proxyData); address moneyToken = ProxyData.money(proxyData); (uint112 reserveStock, uint112 reserveMoney, ) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint balanceStock = _myBalance(stockToken); uint balanceMoney = _myBalance(moneyToken); require(balanceStock >= uint(bookedStock) + uint(reserveStock) && balanceMoney >= uint(bookedMoney) + uint(reserveMoney), "OneSwap: INVALID_BALANCE"); address ones = ProxyData.ones(proxyData); _safeTransfer(stockToken, to, balanceStock-reserveStock-bookedStock, ones); _safeTransfer(moneyToken, to, balanceMoney-reserveMoney-bookedMoney, ones); } // sync-up reserve stock&money in pool according to real balance function sync() external override lock { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); (, , uint32 firstSellID) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint balanceStock = _myBalance(ProxyData.stock(proxyData)); uint balanceMoney = _myBalance(ProxyData.money(proxyData)); require(balanceStock >= bookedStock && balanceMoney >= bookedMoney, "OneSwap: INVALID_BALANCE"); _setReserves(balanceStock-bookedStock, balanceMoney-bookedMoney, firstSellID); } } contract OneSwapPair is OneSwapPool, IOneSwapPair { // the orderbooks. Gas is saved when using array to store them instead of mapping uint[1<<22] private _sellOrders; uint[1<<22] private _buyOrders; uint32 private constant _MAX_ID = (1<<22)-1; // the maximum value of an order ID function _expandPrice(uint32 price32, uint[5] memory proxyData) private pure returns (RatPrice memory price) { price = DecFloat32.expandPrice(price32); price.numerator *= ProxyData.priceMul(proxyData); price.denominator *= ProxyData.priceDiv(proxyData); } function _expandPrice(Context memory ctx, uint32 price32) private pure returns (RatPrice memory price) { price = DecFloat32.expandPrice(price32); price.numerator *= ctx.priceMul; price.denominator *= ctx.priceDiv; } function symbol() external override returns (string memory) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); string memory s = IERC20(ProxyData.stock(proxyData)).symbol(); string memory m = IERC20(ProxyData.money(proxyData)).symbol(); return string(abi.encodePacked(s, "/", m, "-Share")); //to concat strings } // when emitting events, solidity's ABI pads each entry to uint256, which is so wasteful // we compress the entries into one uint256 to save gas function _emitNewLimitOrder( uint64 addressLow, /*255~192*/ uint64 totalStockAmount, /*191~128*/ uint64 remainedStockAmount, /*127~64*/ uint32 price, /*63~32*/ uint32 orderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(addressLow); data = (data<<64) | uint(totalStockAmount); data = (data<<64) | uint(remainedStockAmount); data = (data<<32) | uint(price); data = (data<<32) | uint(orderID<<8); if(isBuy) { data = data | 1; } emit NewLimitOrder(data); } function _emitNewMarketOrder( uint136 addressLow, /*255~120*/ uint112 amount, /*119~8*/ bool isBuy /*7~0*/) private { uint data = uint(addressLow); data = (data<<112) | uint(amount); data = data<<8; if(isBuy) { data = data | 1; } emit NewMarketOrder(data); } function _emitOrderChanged( uint64 makerLastAmount, /*159~96*/ uint64 makerDealAmount, /*95~32*/ uint32 makerOrderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(makerLastAmount); data = (data<<64) | uint(makerDealAmount); data = (data<<32) | uint(makerOrderID<<8); if(isBuy) { data = data | 1; } emit OrderChanged(data); } function _emitDealWithPool( uint112 inAmount, /*131~120*/ uint112 outAmount,/*119~8*/ bool isBuy/*7~0*/) private { uint data = uint(inAmount); data = (data<<112) | uint(outAmount); data = data<<8; if(isBuy) { data = data | 1; } emit DealWithPool(data); } function _emitRemoveOrder( uint64 remainStockAmount, /*95~32*/ uint32 orderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(remainStockAmount); data = (data<<32) | uint(orderID<<8); if(isBuy) { data = data | 1; } emit RemoveOrder(data); } // compress an order into a 256b integer function _order2uint(Order memory order) internal pure returns (uint) { uint n = uint(order.sender); n = (n<<32) | order.price; n = (n<<42) | order.amount; n = (n<<22) | order.nextID; return n; } // extract an order from a 256b integer function _uint2order(uint n) internal pure returns (Order memory) { Order memory order; order.nextID = uint32(n & ((1<<22)-1)); n = n >> 22; order.amount = uint64(n & ((1<<42)-1)); n = n >> 42; order.price = uint32(n & ((1<<32)-1)); n = n >> 32; order.sender = address(n); return order; } // returns true if this order exists function _hasOrder(bool isBuy, uint32 id) internal view returns (bool) { if(isBuy) { return _buyOrders[id] != 0; } else { return _sellOrders[id] != 0; } } // load an order from storage, converting its compressed form into an Order struct function _getOrder(bool isBuy, uint32 id) internal view returns (Order memory order, bool findIt) { if(isBuy) { order = _uint2order(_buyOrders[id]); return (order, order.price != 0); } else { order = _uint2order(_sellOrders[id]); return (order, order.price != 0); } } // save an order to storage, converting it into compressed form function _setOrder(bool isBuy, uint32 id, Order memory order) internal { if(isBuy) { _buyOrders[id] = _order2uint(order); } else { _sellOrders[id] = _order2uint(order); } } // delete an order from storage function _deleteOrder(bool isBuy, uint32 id) internal { if(isBuy) { delete _buyOrders[id]; } else { delete _sellOrders[id]; } } function _getFirstOrderID(Context memory ctx, bool isBuy) internal pure returns (uint32) { if(isBuy) { return ctx.firstBuyID; } return ctx.firstSellID; } function _setFirstOrderID(Context memory ctx, bool isBuy, uint32 id) internal pure { if(isBuy) { ctx.firstBuyID = id; } else { ctx.firstSellID = id; } } function removeOrders(uint[] calldata rmList) external override lock { uint[5] memory proxyData; uint expectedCallDataSize = 4+32*(ProxyData.COUNT+2+rmList.length); ProxyData.fill(proxyData, expectedCallDataSize); for(uint i = 0; i < rmList.length; i++) { uint rmInfo = rmList[i]; bool isBuy = uint8(rmInfo) != 0; uint32 id = uint32(rmInfo>>8); uint72 prevKey = uint72(rmInfo>>40); _removeOrder(isBuy, id, prevKey, proxyData); } } function removeOrder(bool isBuy, uint32 id, uint72 prevKey) external override lock { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+3)); _removeOrder(isBuy, id, prevKey, proxyData); } function _removeOrder(bool isBuy, uint32 id, uint72 prevKey, uint[5] memory proxyData) private { Context memory ctx; (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); if(!isBuy) { (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); } Order memory order = _removeOrderFromBook(ctx, isBuy, id, prevKey); // this is the removed order require(msg.sender == order.sender, "OneSwap: NOT_OWNER"); uint64 stockUnit = ProxyData.stockUnit(proxyData); uint stockAmount = uint(order.amount)/*42bits*/ * uint(stockUnit); address ones = ProxyData.ones(proxyData); if(isBuy) { RatPrice memory price = _expandPrice(order.price, proxyData); uint moneyAmount = stockAmount * price.numerator/*54+64bits*/ / price.denominator; ctx.bookedMoney -= moneyAmount; _safeTransfer(ProxyData.money(proxyData), order.sender, moneyAmount, ones); } else { ctx.bookedStock -= stockAmount; _safeTransfer(ProxyData.stock(proxyData), order.sender, stockAmount, ones); } _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); } // remove an order from orderbook and return it function _removeOrderFromBook(Context memory ctx, bool isBuy, uint32 id, uint72 prevKey) internal returns (Order memory) { (Order memory order, bool ok) = _getOrder(isBuy, id); require(ok, "OneSwap: NO_SUCH_ORDER"); if(prevKey == 0) { uint32 firstID = _getFirstOrderID(ctx, isBuy); require(id == firstID, "OneSwap: NOT_FIRST"); _setFirstOrderID(ctx, isBuy, order.nextID); if(!isBuy) { _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); } } else { (uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey); require(findIt, "OneSwap: INVALID_POSITION"); while(prevOrder.nextID != id) { currID = prevOrder.nextID; require(currID != 0, "OneSwap: REACH_END"); (prevOrder, ) = _getOrder(isBuy, currID); } prevOrder.nextID = order.nextID; _setOrder(isBuy, currID, prevOrder); } _emitRemoveOrder(order.amount, id, isBuy); _deleteOrder(isBuy, id); return order; } // insert an order at the head of single-linked list // this function does not check price, use it carefully function _insertOrderAtHead(Context memory ctx, bool isBuy, Order memory order, uint32 id) private { order.nextID = _getFirstOrderID(ctx, isBuy); _setOrder(isBuy, id, order); _setFirstOrderID(ctx, isBuy, id); } // prevKey contains 3 orders. try to get the first existing order function _getOrder3Times(bool isBuy, uint72 prevKey) private view returns ( uint32 currID, Order memory prevOrder, bool findIt) { currID = uint32(prevKey&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); if(!findIt) { currID = uint32((prevKey>>24)&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); if(!findIt) { currID = uint32((prevKey>>48)&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); } } } // Given a valid start position, find a proper position to insert order // prevKey contains three suggested order IDs, each takes 24 bits. // We try them one by one to find a valid start position // can not use this function to insert at head! if prevKey is all zero, it will return false function _insertOrderFromGivenPos(bool isBuy, Order memory order, uint32 id, uint72 prevKey) private returns (bool inserted) { (uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey); if(!findIt) { return false; } return _insertOrder(isBuy, order, prevOrder, id, currID); } // Starting from the head of orderbook, find a proper position to insert order function _insertOrderFromHead(Context memory ctx, bool isBuy, Order memory order, uint32 id) private returns (bool inserted) { uint32 firstID = _getFirstOrderID(ctx, isBuy); bool canBeFirst = (firstID == 0); Order memory firstOrder; if(!canBeFirst) { (firstOrder, ) = _getOrder(isBuy, firstID); canBeFirst = (isBuy && (firstOrder.price < order.price)) || (!isBuy && (firstOrder.price > order.price)); } if(canBeFirst) { order.nextID = firstID; _setOrder(isBuy, id, order); _setFirstOrderID(ctx, isBuy, id); return true; } return _insertOrder(isBuy, order, firstOrder, id, firstID); } // starting from 'prevOrder', whose id is 'currID', find a proper position to insert order function _insertOrder(bool isBuy, Order memory order, Order memory prevOrder, uint32 id, uint32 currID) private returns (bool inserted) { while(currID != 0) { bool canFollow = (isBuy && (order.price <= prevOrder.price)) || (!isBuy && (order.price >= prevOrder.price)); if(!canFollow) {break;} Order memory nextOrder; if(prevOrder.nextID != 0) { (nextOrder, ) = _getOrder(isBuy, prevOrder.nextID); bool canPrecede = (isBuy && (nextOrder.price < order.price)) || (!isBuy && (nextOrder.price > order.price)); canFollow = canFollow && canPrecede; } if(canFollow) { order.nextID = prevOrder.nextID; _setOrder(isBuy, id, order); prevOrder.nextID = id; _setOrder(isBuy, currID, prevOrder); return true; } currID = prevOrder.nextID; prevOrder = nextOrder; } return false; } // to query the first sell price, the first buy price and the price of pool function getPrices() external override returns ( uint firstSellPriceNumerator, uint firstSellPriceDenominator, uint firstBuyPriceNumerator, uint firstBuyPriceDenominator, uint poolPriceNumerator, uint poolPriceDenominator) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); poolPriceNumerator = uint(reserveMoney); poolPriceDenominator = uint(reserveStock); firstSellPriceNumerator = 0; firstSellPriceDenominator = 0; firstBuyPriceNumerator = 0; firstBuyPriceDenominator = 0; if(firstSellID!=0) { uint order = _sellOrders[firstSellID]; RatPrice memory price = _expandPrice(uint32(order>>64), proxyData); firstSellPriceNumerator = price.numerator; firstSellPriceDenominator = price.denominator; } uint32 id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224); if(id!=0) { uint order = _buyOrders[id]; RatPrice memory price = _expandPrice(uint32(order>>64), proxyData); firstBuyPriceNumerator = price.numerator; firstBuyPriceDenominator = price.denominator; } } // Get the orderbook's content, starting from id, to get no more than maxCount orders function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external override view returns (uint[] memory) { if(id == 0) { if(isBuy) { id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224); } else { id = uint32(_reserveStockAndMoneyAndFirstSellID>>224); } } uint[1<<22] storage orderbook; if(isBuy) { orderbook = _buyOrders; } else { orderbook = _sellOrders; } //record block height at the first entry uint order = (block.number<<24) | id; uint addrOrig; // start of returned data uint addrLen; // the slice's length is written at this address uint addrStart; // the address of the first entry of returned slice uint addrEnd; // ending address to write the next order uint count = 0; // the slice's length // solhint-disable-next-line no-inline-assembly assembly { addrOrig := mload(0x40) // There is a “free memory pointer” at address 0x40 in memory mstore(addrOrig, 32) //the meaningful data start after offset 32 } addrLen = addrOrig + 32; addrStart = addrLen + 32; addrEnd = addrStart; while(count < maxCount) { // solhint-disable-next-line no-inline-assembly assembly { mstore(addrEnd, order) //write the order } addrEnd += 32; count++; if(id == 0) {break;} order = orderbook[id]; require(order!=0, "OneSwap: INCONSISTENT_BOOK"); id = uint32(order&_MAX_ID); } // solhint-disable-next-line no-inline-assembly assembly { mstore(addrLen, count) // record the returned slice's length let byteCount := sub(addrEnd, addrOrig) return(addrOrig, byteCount) } } // Get an unused id to be used with new order function _getUnusedOrderID(bool isBuy, uint32 id) internal view returns (uint32) { if(id == 0) { // 0 is reserved // solhint-disable-next-line avoid-tx-origin id = uint32(uint(blockhash(block.number-1))^uint(tx.origin)) & _MAX_ID; //get a pseudo random number } for(uint32 i = 0; i < 100 && id <= _MAX_ID; i++) { //try 100 times if(!_hasOrder(isBuy, id)) { return id; } id++; } require(false, "OneSwap: CANNOT_FIND_VALID_ID"); return 0; } function calcStockAndMoney(uint64 amount, uint32 price32) external pure override returns (uint stockAmount, uint moneyAmount) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+2)); (stockAmount, moneyAmount, ) = _calcStockAndMoney(amount, price32, proxyData); } function _calcStockAndMoney(uint64 amount, uint32 price32, uint[5] memory proxyData) private pure returns (uint stockAmount, uint moneyAmount, RatPrice memory price) { price = _expandPrice(price32, proxyData); uint64 stockUnit = ProxyData.stockUnit(proxyData); stockAmount = uint(amount)/*42bits*/ * uint(stockUnit); moneyAmount = stockAmount * price.numerator/*54+64bits*/ /price.denominator; } function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable override lock { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+6)); require(ProxyData.isOnlySwap(proxyData)==false, "OneSwap: LIMIT_ORDER_NOT_SUPPORTED"); Context memory ctx; ctx.stockUnit = ProxyData.stockUnit(proxyData); ctx.ones = ProxyData.ones(proxyData); ctx.factory = ProxyData.factory(proxyData); ctx.stockToken = ProxyData.stock(proxyData); ctx.moneyToken = ProxyData.money(proxyData); ctx.priceMul = ProxyData.priceMul(proxyData); ctx.priceDiv = ProxyData.priceDiv(proxyData); ctx.hasDealtInOrderBook = false; ctx.isLimitOrder = true; ctx.order.sender = sender; ctx.order.amount = amount; ctx.order.price = price32; ctx.newOrderID = _getUnusedOrderID(isBuy, id); RatPrice memory price; {// to prevent "CompilerError: Stack too deep, try removing local variables." require((amount >> 42) == 0, "OneSwap: INVALID_AMOUNT"); uint32 m = price32 & DecFloat32.MANTISSA_MASK; require(DecFloat32.MIN_MANTISSA <= m && m <= DecFloat32.MAX_MANTISSA, "OneSwap: INVALID_PRICE"); uint stockAmount; uint moneyAmount; (stockAmount, moneyAmount, price) = _calcStockAndMoney(amount, price32, proxyData); if(isBuy) { ctx.remainAmount = moneyAmount; } else { ctx.remainAmount = stockAmount; } } require(ctx.remainAmount < uint(1<<112), "OneSwap: OVERFLOW"); (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); _checkRemainAmount(ctx, isBuy); if(prevKey != 0) { // try to insert it bool inserted = _insertOrderFromGivenPos(isBuy, ctx.order, ctx.newOrderID, prevKey); if(inserted) { // if inserted successfully, record the booked tokens _emitNewLimitOrder(uint64(ctx.order.sender), amount, amount, price32, ctx.newOrderID, isBuy); if(isBuy) { ctx.bookedMoney += ctx.remainAmount; } else { ctx.bookedStock += ctx.remainAmount; } _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); if(ctx.reserveChanged) { _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); } return; } // if insertion failed, we try to match this order and make it deal } _addOrder(ctx, isBuy, price); } function addMarketOrder(address inputToken, address sender, uint112 inAmount) external payable override lock returns (uint) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+3)); Context memory ctx; ctx.moneyToken = ProxyData.money(proxyData); ctx.stockToken = ProxyData.stock(proxyData); require(inputToken == ctx.moneyToken || inputToken == ctx.stockToken, "OneSwap: INVALID_TOKEN"); bool isBuy = inputToken == ctx.moneyToken; ctx.stockUnit = ProxyData.stockUnit(proxyData); ctx.priceMul = ProxyData.priceMul(proxyData); ctx.priceDiv = ProxyData.priceDiv(proxyData); ctx.ones = ProxyData.ones(proxyData); ctx.factory = ProxyData.factory(proxyData); ctx.hasDealtInOrderBook = false; ctx.isLimitOrder = false; ctx.remainAmount = inAmount; (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); _checkRemainAmount(ctx, isBuy); ctx.order.sender = sender; if(isBuy) { ctx.order.price = DecFloat32.MAX_PRICE; } else { ctx.order.price = DecFloat32.MIN_PRICE; } RatPrice memory price; // leave it to zero, actually it will not be used; _emitNewMarketOrder(uint136(ctx.order.sender), inAmount, isBuy); return _addOrder(ctx, isBuy, price); } // Check router contract did send me enough tokens. // If Router sent to much tokens, take them as reserve money&stock function _checkRemainAmount(Context memory ctx, bool isBuy) private view { ctx.reserveChanged = false; uint diff; if(isBuy) { uint balance = _myBalance(ctx.moneyToken); require(balance >= ctx.bookedMoney + ctx.reserveMoney, "OneSwap: MONEY_MISMATCH"); diff = balance - ctx.bookedMoney - ctx.reserveMoney; if(ctx.remainAmount < diff) { ctx.reserveMoney += (diff - ctx.remainAmount); ctx.reserveChanged = true; } } else { uint balance = _myBalance(ctx.stockToken); require(balance >= ctx.bookedStock + ctx.reserveStock, "OneSwap: STOCK_MISMATCH"); diff = balance - ctx.bookedStock - ctx.reserveStock; if(ctx.remainAmount < diff) { ctx.reserveStock += (diff - ctx.remainAmount); ctx.reserveChanged = true; } } require(ctx.remainAmount <= diff, "OneSwap: DEPOSIT_NOT_ENOUGH"); } // internal helper function to add new limit order & market order // returns the amount of tokens which were sent to the taker (from AMM pool and booked tokens) function _addOrder(Context memory ctx, bool isBuy, RatPrice memory price) private returns (uint) { (ctx.dealMoneyInBook, ctx.dealStockInBook) = (0, 0); ctx.firstID = _getFirstOrderID(ctx, !isBuy); uint32 currID = ctx.firstID; ctx.amountIntoPool = 0; while(currID != 0) { // while not reaching the end of single-linked (Order memory orderInBook, ) = _getOrder(!isBuy, currID); bool canDealInOrderBook = (isBuy && (orderInBook.price <= ctx.order.price)) || (!isBuy && (orderInBook.price >= ctx.order.price)); if(!canDealInOrderBook) {break;} // no proper price in orderbook, stop here // Deal in liquid pool RatPrice memory priceInBook = _expandPrice(ctx, orderInBook.price); bool allDeal = _tryDealInPool(ctx, isBuy, priceInBook); if(allDeal) {break;} // Deal in orderbook _dealInOrderBook(ctx, isBuy, currID, orderInBook, priceInBook); // if the order in book did NOT fully deal, then this new order DID fully deal, so stop here if(orderInBook.amount != 0) { _setOrder(!isBuy, currID, orderInBook); break; } // if the order in book DID fully deal, then delete this order from storage and move to the next _deleteOrder(!isBuy, currID); currID = orderInBook.nextID; } // Deal in liquid pool if(ctx.isLimitOrder) { // use current order's price to deal with pool _tryDealInPool(ctx, isBuy, price); // If a limit order did NOT fully deal, we add it into orderbook // Please note a market order always fully deals _insertOrderToBook(ctx, isBuy, price); } else { // the AMM pool can deal with orders with any amount ctx.amountIntoPool += ctx.remainAmount; // both of them are less than 112 bits ctx.remainAmount = 0; } uint amountToTaker = _dealWithPoolAndCollectFee(ctx, isBuy); if(isBuy) { ctx.bookedStock -= ctx.dealStockInBook; //If this subtraction overflows, _setBooked will fail } else { ctx.bookedMoney -= ctx.dealMoneyInBook; //If this subtraction overflows, _setBooked will fail } if(ctx.firstID != currID) { //some orders DID fully deal, so the head of single-linked list change _setFirstOrderID(ctx, !isBuy, currID); } // write the cached values to storage _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); return amountToTaker; } // Given reserveMoney and reserveStock in AMM pool, calculate how much tokens will go into the pool if the // final price is 'price' function _intopoolAmountTillPrice(bool isBuy, uint reserveMoney, uint reserveStock, RatPrice memory price) private pure returns (uint result) { // sqrt(Pold/Pnew) = sqrt((2**32)*M_old*PnewDenominator / (S_old*PnewNumerator)) / (2**16) // sell, stock-into-pool, Pold > Pnew uint numerator = reserveMoney/*112bits*/ * price.denominator/*76+64bits*/; uint denominator = reserveStock/*112bits*/ * price.numerator/*54+64bits*/; if(isBuy) { // buy, money-into-pool, Pold < Pnew // sqrt(Pnew/Pold) = sqrt((2**32)*S_old*PnewNumerator / (M_old*PnewDenominator)) / (2**16) (numerator, denominator) = (denominator, numerator); } while(numerator >= (1<<192)) { // can not equal to (1<<192) !!! numerator >>= 16; denominator >>= 16; } require(denominator != 0, "OneSwapPair: DIV_BY_ZERO"); numerator = numerator * (1<<64); uint quotient = numerator / denominator; if(quotient <= (1<<64)) { return 0; } else if(quotient <= ((1<<64)*5/4)) { // Taylor expansion: x/2 - x*x/8 + x*x*x/16 uint x = quotient - (1<<64); uint y = x*x; y = x/2 - y/(8*(1<<64)) + y*x/(16*(1<<128)); if(isBuy) { result = reserveMoney * y; } else { result = reserveStock * y; } result /= (1<<64); return result; } uint root = Math.sqrt(quotient); //root is at most 110bits uint diff = root - (1<<32); //at most 110bits if(isBuy) { result = reserveMoney * diff; } else { result = reserveStock * diff; } result /= (1<<32); return result; } // Current order tries to deal against the AMM pool. Returns whether current order fully deals. function _tryDealInPool(Context memory ctx, bool isBuy, RatPrice memory price) private pure returns (bool) { uint currTokenCanTrade = _intopoolAmountTillPrice(isBuy, ctx.reserveMoney, ctx.reserveStock, price); require(currTokenCanTrade < uint(1<<112), "OneSwap: CURR_TOKEN_TOO_LARGE"); // all the below variables are less than 112 bits if(!isBuy) { currTokenCanTrade /= ctx.stockUnit; //to round currTokenCanTrade *= ctx.stockUnit; } if(currTokenCanTrade > ctx.amountIntoPool) { uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool; bool allDeal = diffTokenCanTrade >= ctx.remainAmount; if(allDeal) { diffTokenCanTrade = ctx.remainAmount; } ctx.amountIntoPool += diffTokenCanTrade; ctx.remainAmount -= diffTokenCanTrade; return allDeal; } return false; } // Current order tries to deal against the orders in book function _dealInOrderBook(Context memory ctx, bool isBuy, uint32 currID, Order memory orderInBook, RatPrice memory priceInBook) internal { ctx.hasDealtInOrderBook = true; uint stockAmount; if(isBuy) { uint a = ctx.remainAmount/*112bits*/ * priceInBook.denominator/*76+64bits*/; uint b = priceInBook.numerator/*54+64bits*/ * ctx.stockUnit/*64bits*/; stockAmount = a/b; } else { stockAmount = ctx.remainAmount/ctx.stockUnit; } if(uint(orderInBook.amount) < stockAmount) { stockAmount = uint(orderInBook.amount); } require(stockAmount < (1<<42), "OneSwap: STOCK_TOO_LARGE"); uint stockTrans = stockAmount/*42bits*/ * ctx.stockUnit/*64bits*/; uint moneyTrans = stockTrans * priceInBook.numerator/*54+64bits*/ / priceInBook.denominator/*76+64bits*/; _emitOrderChanged(orderInBook.amount, uint64(stockAmount), currID, isBuy); orderInBook.amount -= uint64(stockAmount); if(isBuy) { //subtraction cannot overflow: moneyTrans and stockTrans are calculated from remainAmount ctx.remainAmount -= moneyTrans; } else { ctx.remainAmount -= stockTrans; } // following accumulations can not overflow, because stockTrans(moneyTrans) at most 106bits(160bits) // we know for sure that dealStockInBook and dealMoneyInBook are less than 192 bits ctx.dealStockInBook += stockTrans; ctx.dealMoneyInBook += moneyTrans; if(isBuy) { _safeTransfer(ctx.moneyToken, orderInBook.sender, moneyTrans, ctx.ones); } else { _safeTransfer(ctx.stockToken, orderInBook.sender, stockTrans, ctx.ones); } } // make real deal with the pool and then collect fee, which will be added to AMM pool function _dealWithPoolAndCollectFee(Context memory ctx, bool isBuy) internal returns (uint) { (uint outpoolTokenReserve, uint inpoolTokenReserve, uint otherToTaker) = ( ctx.reserveMoney, ctx.reserveStock, ctx.dealMoneyInBook); if(isBuy) { (outpoolTokenReserve, inpoolTokenReserve, otherToTaker) = ( ctx.reserveStock, ctx.reserveMoney, ctx.dealStockInBook); } // all these 4 varialbes are less than 112 bits // outAmount is sure to less than outpoolTokenReserve (which is ctx.reserveStock or ctx.reserveMoney) uint outAmount = (outpoolTokenReserve*ctx.amountIntoPool)/(inpoolTokenReserve+ctx.amountIntoPool); if(ctx.amountIntoPool > 0) { _emitDealWithPool(uint112(ctx.amountIntoPool), uint112(outAmount), isBuy); } uint32 feeBPS = IOneSwapFactory(ctx.factory).feeBPS(); // the token amount that should go to the taker, // for buy-order, it's stock amount; for sell-order, it's money amount uint amountToTaker = outAmount + otherToTaker; require(amountToTaker < uint(1<<112), "OneSwap: AMOUNT_TOO_LARGE"); uint fee = (amountToTaker * feeBPS + 9999) / 10000; amountToTaker -= fee; if(isBuy) { ctx.reserveMoney = ctx.reserveMoney + ctx.amountIntoPool; ctx.reserveStock = ctx.reserveStock - outAmount + fee; } else { ctx.reserveMoney = ctx.reserveMoney - outAmount + fee; ctx.reserveStock = ctx.reserveStock + ctx.amountIntoPool; } address token = ctx.moneyToken; if(isBuy) { token = ctx.stockToken; } _safeTransfer(token, ctx.order.sender, amountToTaker, ctx.ones); return amountToTaker; } // Insert a not-fully-deal limit order into orderbook function _insertOrderToBook(Context memory ctx, bool isBuy, RatPrice memory price) internal { (uint smallAmount, uint moneyAmount, uint stockAmount) = (0, 0, 0); if(isBuy) { uint tempAmount1 = ctx.remainAmount /*112bits*/ * price.denominator /*76+64bits*/; uint temp = ctx.stockUnit * price.numerator/*54+64bits*/; stockAmount = tempAmount1 / temp; uint tempAmount2 = stockAmount * temp; // Now tempAmount1 >= tempAmount2 moneyAmount = (tempAmount2+price.denominator-1)/price.denominator; // round up if(ctx.remainAmount > moneyAmount) { // smallAmount is the gap where remainAmount can not buy an integer of stocks smallAmount = ctx.remainAmount - moneyAmount; } else { moneyAmount = ctx.remainAmount; } //Now ctx.remainAmount >= moneyAmount } else { // for sell orders, remainAmount were always decreased by integral multiple of StockUnit // and we know for sure that ctx.remainAmount % StockUnit == 0 stockAmount = ctx.remainAmount / ctx.stockUnit; smallAmount = ctx.remainAmount - stockAmount * ctx.stockUnit; } ctx.amountIntoPool += smallAmount; // Deal smallAmount with pool //ctx.reserveMoney += smallAmount; // If this addition overflows, _setReserves will fail _emitNewLimitOrder(uint64(ctx.order.sender), ctx.order.amount, uint64(stockAmount), ctx.order.price, ctx.newOrderID, isBuy); if(stockAmount != 0) { ctx.order.amount = uint64(stockAmount); if(ctx.hasDealtInOrderBook) { // if current order has ever dealt, it has the best price and can be inserted at head _insertOrderAtHead(ctx, isBuy, ctx.order, ctx.newOrderID); } else { // if current order has NEVER dealt, we must find a proper position for it. // we may scan a lot of entries in the single-linked list and run out of gas _insertOrderFromHead(ctx, isBuy, ctx.order, ctx.newOrderID); } } // Any overflow/underflow in following calculation will be caught by _setBooked if(isBuy) { ctx.bookedMoney += moneyAmount; } else { ctx.bookedStock += (ctx.remainAmount - smallAmount); } } } // solhint-disable-next-line max-states-count contract OneSwapPairProxy { uint internal _unusedVar0; uint internal _unusedVar1; uint internal _unusedVar2; uint internal _unusedVar3; uint internal _unusedVar4; uint internal _unusedVar5; uint internal _unusedVar6; uint internal _unusedVar7; uint internal _unusedVar8; uint internal _unusedVar9; uint internal _unlocked; uint internal immutable _immuFactory; uint internal immutable _immuMoneyToken; uint internal immutable _immuStockToken; uint internal immutable _immuOnes; uint internal immutable _immuOther; constructor(address stockToken, address moneyToken, bool isOnlySwap, uint64 stockUnit, uint64 priceMul, uint64 priceDiv, address ones) public { _immuFactory = uint(msg.sender); _immuMoneyToken = uint(moneyToken); _immuStockToken = uint(stockToken); _immuOnes = uint(ones); uint temp = 0; if(isOnlySwap) { temp = 1; } temp = (temp<<64) | stockUnit; temp = (temp<<64) | priceMul; temp = (temp<<64) | priceDiv; _immuOther = temp; _unlocked = 1; } receive() external payable { } // solhint-disable-next-line no-complex-fallback fallback() payable external { uint factory = _immuFactory; uint moneyToken = _immuMoneyToken; uint stockToken = _immuStockToken; uint ones = _immuOnes; uint other = _immuOther; address impl = IOneSwapFactory(address(_immuFactory)).pairLogic(); // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) let size := calldatasize() calldatacopy(ptr, 0, size) let end := add(ptr, size) // append immutable variables to the end of calldata mstore(end, factory) end := add(end, 32) mstore(end, moneyToken) end := add(end, 32) mstore(end, stockToken) end := add(end, 32) mstore(end, ones) end := add(end, 32) mstore(end, other) size := add(size, 160) let result := delegatecall(gas(), impl, ptr, size, 0, 0) size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // this contract is only used for test contract OneSwapFactoryPXYTEST { address public feeTo; address public feeToSetter; address public pairLogic; mapping(address => mapping(address => address)) public pairs; address[] public allPairs; event PairCreated(address indexed stock, address indexed money, address pair, uint); function createPair(address stock, address money, address impl) external { require(stock != money, "OneSwap: IDENTICAL_ADDRESSES"); require(stock != address(0) || money != address(0), "OneSwap: ZERO_ADDRESS"); require(pairs[stock][money] == address(0), "OneSwap: PAIR_EXISTS"); // single check is sufficient uint8 dec; if (stock == address(0)){ dec = 18; } else{ dec = IERC20(stock).decimals(); } require(25 >= dec && dec >= 6, "OneSwap: DECIMALS_NOT_SUPPORTED"); dec -= 6; bytes32 salt = keccak256(abi.encodePacked(stock, money)); OneSwapPairProxy oneswap = new OneSwapPairProxy{salt: salt}(stock, money, false, 1, 1, 1, address(0)); address pair = address(oneswap); pairs[stock][money] = pair; allPairs.push(pair); pairLogic = impl; emit PairCreated(stock, money, pair, allPairs.length); } function allPairsLength() external view returns (uint) { return allPairs.length; } function feeBPS() external pure returns (uint32) { return 30; } }
prevKey contains 3 orders. try to get the first existing order
function _getOrder3Times(bool isBuy, uint72 prevKey) private view returns ( uint32 currID, Order memory prevOrder, bool findIt) { currID = uint32(prevKey&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); if(!findIt) { currID = uint32((prevKey>>24)&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); if(!findIt) { currID = uint32((prevKey>>48)&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); } } }
1,096,963
./partial_match/1/0xaF4ce7CD4F8891ecf1799878c3e9A35b8BE57E09/sources/src/newFolder/ERC4626.sol
Deposit/mint common workflow./ If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer, calls the vault, which is assumed not malicious. Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the assets are transferred and before the shares are minted, which is a valid state. slither-disable-next-line reentrancy-no-eth
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual { SafeERC20.safeTransferFrom(_asset, caller, address(this), assets); _mint(receiver, shares); emit Deposit(caller, receiver, assets, shares); }
2,721,989
pragma solidity 0.5.12; // @author Authereum, Inc. /** * @title AccountStateV1 * @author Authereum, Inc. * @dev This contract holds the state variables used by the account contracts. * @dev This abscraction exists in order to retain the order of the state variables. */ contract AccountStateV1 { uint256 public lastInitializedVersion; mapping(address => bool) public authKeys; uint256 public nonce; uint256 public numAuthKeys; } // File: contracts/account/state/AccountState.sol pragma solidity 0.5.12; /** * @title AccountState * @author Authereum, Inc. * @dev This contract holds the state variables used by the account contracts. * @dev This exists as the main contract to hold state. This contract is inherited * @dev by Account.sol, which will not care about state as long as it inherits * @dev AccountState.sol. Any state variable additions will be made to the various * @dev versions of AccountStateVX that this contract will inherit. */ contract AccountState is AccountStateV1 {} // File: contracts/account/event/AccountEvent.sol pragma solidity 0.5.12; /** * @title AccountEvent * @author Authereum, Inc. * @dev This contract holds the events used by the Authereum contracts. * @dev This abscraction exists in order to retain the order to give initialization functions * @dev access to events. * @dev This contract can be overwritten with no changes to the upgradeability. */ contract AccountEvent { /** * BaseAccount.sol */ event FundsReceived(address indexed sender, uint256 indexed value); event AddedAuthKey(address indexed authKey); event RemovedAuthKey(address indexed authKey); event SwappedAuthKeys(address indexed oldAuthKey, address indexed newAuthKey); // Invalid Sigs event InvalidAuthkey(); event InvalidTransactionDataSigner(); // Invalid Tx event CallFailed(bytes32 encodedData); /** * AccountUpgradeability.sol */ event Upgraded(address indexed implementation); } // File: contracts/account/initializer/AccountInitializeV1.sol pragma solidity 0.5.12; /** * @title AccountInitializeV1 * @author Authereum, Inc. * @dev This contract holds the initialize function used by the account contracts. * @dev This abscraction exists in order to retain the order of the initialization functions. */ contract AccountInitializeV1 is AccountState, AccountEvent { /// @dev Initialize the Authereum Account /// @param _authKey authKey that will own this account function initializeV1( address _authKey ) public { require(lastInitializedVersion == 0); lastInitializedVersion = 1; // Add self as an authKey authKeys[_authKey] = true; numAuthKeys += 1; emit AddedAuthKey(_authKey); } } // File: contracts/account/initializer/AccountInitialize.sol pragma solidity 0.5.12; /** * @title AccountInitialize * @author Authereum, Inc. * @dev This contract holds the intialize functions used by the account contracts. * @dev This exists as the main contract to hold these functions. This contract is inherited * @dev by AuthereumAccount.sol, which will not care about initialization functions as long as it inherits * @dev AccountInitialize.sol. Any initialization function additions will be made to the various * @dev versions of AccountInitializeVx that this contract will inherit. */ contract AccountInitialize is AccountInitializeV1 {} // File: contracts/interfaces/IERC1271.sol pragma solidity 0.5.12; contract IERC1271 { function isValidSignature( bytes memory _messageHash, bytes memory _signature) public view returns (bytes4 magicValue); } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.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 { /** * @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. * * (.note) This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * (.warning) `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) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * [`eth_sign`](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign) * JSON-RPC method. * * 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)); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.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, 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"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: solidity-bytes-utils/contracts/BytesLib.sol /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <goncalo.sa@consensys.net> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity ^0.5.0; library BytesLib { 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 concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } 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 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 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 equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage( bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } // File: contracts/account/BaseAccount.sol pragma solidity 0.5.12; pragma experimental ABIEncoderV2; /** * @title BaseAccount * @author Authereum, Inc. * @dev Base account contract. Performs most of the functionality * @dev of an Authereum account contract. */ contract BaseAccount is AccountInitialize, IERC1271 { using SafeMath for uint256; using ECDSA for bytes32; using BytesLib for bytes; // Include a CHAIN_ID const uint256 constant CHAIN_ID = 1; // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 constant internal VALID_SIG = 0x20c13b0b; bytes4 constant internal INVALID_SIG = 0xffffffff; modifier onlyValidAuthKeyOrSelf { _validateAuthKey(msg.sender); _; } // This is required for funds sent to this contract function () external payable {} /** * Getters */ /// @dev Get the current nonce of the contract /// @return The nonce of the contract function getNonce() public view returns (uint256) { return nonce; } /// @dev Get the chain ID constant /// @return The chain id function getChainId() public view returns (uint256) { return CHAIN_ID; } /** * Public functions */ /// @dev Execute a transaction /// @notice This is to be called directly by an AuthKey /// @param _destination Destination of the transaction /// @param _value Value of the transaction /// @param _data Data of the transaction /// @param _gasLimit Gas limit of the transaction /// @return Response of the call function executeTransaction( address _destination, uint256 _value, bytes memory _data, uint256 _gasLimit ) public onlyValidAuthKeyOrSelf returns (bytes memory) { return _executeTransaction(_destination, _value, _data, _gasLimit); } /// @dev Add an auth key to the list of auth keys /// @param _authKey Address of the auth key to add function addAuthKey(address _authKey) public onlyValidAuthKeyOrSelf { require(!authKeys[_authKey], "Auth key already added"); authKeys[_authKey] = true; numAuthKeys += 1; emit AddedAuthKey(_authKey); } /// @dev Add multiple auth keys to the list of auth keys /// @param _authKeys Array of addresses to add to the auth keys list function addMultipleAuthKeys(address[] memory _authKeys) public onlyValidAuthKeyOrSelf { for (uint256 i = 0; i < _authKeys.length; i++) { addAuthKey(_authKeys[i]); } } /// @dev Remove an auth key from the list of auth keys /// @param _authKey Address of the auth key to remove function removeAuthKey(address _authKey) public onlyValidAuthKeyOrSelf { require(authKeys[_authKey], "Auth key not yet added"); require(numAuthKeys > 1, "Cannot remove last auth key"); authKeys[_authKey] = false; numAuthKeys -= 1; emit RemovedAuthKey(_authKey); } /// @dev Remove multiple auth keys to the list of auth keys /// @param _authKeys Array of addresses to remove to the auth keys list function removeMultipleAuthKeys(address[] memory _authKeys) public onlyValidAuthKeyOrSelf { for (uint256 i = 0; i < _authKeys.length; i++) { removeAuthKey(_authKeys[i]); } } /// @dev Swap one authKey for a non-authKey /// @param _oldAuthKey An existing authKey /// @param _newAuthKey A non-existing authKey function swapAuthKeys( address _oldAuthKey, address _newAuthKey ) public onlyValidAuthKeyOrSelf { require(authKeys[_oldAuthKey], "Old auth key does not exist"); require(!authKeys[_newAuthKey], "New auth key already exists"); addAuthKey(_newAuthKey); removeAuthKey(_oldAuthKey); emit SwappedAuthKeys(_oldAuthKey, _newAuthKey); } /// @dev Swap multiple auth keys to the list of auth keys /// @param _oldAuthKeys Array of addresses to remove to the auth keys list /// @param _newAuthKeys Array of addresses to add to the auth keys list function swapMultipleAuthKeys( address[] memory _oldAuthKeys, address[] memory _newAuthKeys ) public { require(_oldAuthKeys.length == _newAuthKeys.length, "Input arrays not equal length"); for (uint256 i = 0; i < _oldAuthKeys.length; i++) { swapAuthKeys(_oldAuthKeys[i], _newAuthKeys[i]); } } /// @dev Check if a message and signature pair is valid /// @notice The _signatures parameter can either be one auth key signature or it can /// @notice be a login key signature and an auth key signature (signed login key) /// @param _msg Message that was signed /// @param _signatures Signature(s) of the data. Either a single signature (login) or two (login and auth) /// @return VALID_SIG or INVALID_SIG hex data function isValidSignature( bytes memory _msg, bytes memory _signatures ) public view returns (bytes4) { if (_signatures.length == 65) { return isValidAuthKeySignature(_msg, _signatures); } else if (_signatures.length == 130) { return isValidLoginKeySignature(_msg, _signatures); } else { revert("Invalid _signatures length"); } } /// @dev Check if a message and auth key signature pair is valid /// @param _msg Message that was signed /// @param _signature Signature of the data signed by the authkey /// @return VALID_SIG or INVALID_SIG hex data function isValidAuthKeySignature( bytes memory _msg, bytes memory _signature ) public view returns (bytes4) { address authKeyAddress = _getEthSignedMessageHash(_msg).recover( _signature ); if(authKeys[authKeyAddress]) { return VALID_SIG; } else { return INVALID_SIG; } } /// @dev Check if a message and login key signature pair is valid, as well as a signed login key by an auth key /// @param _msg Message that was signed /// @param _signatures Signatures of the data. Signed msg data by the login key and signed login key by auth key /// @return VALID_SIG or INVALID_SIG hex data function isValidLoginKeySignature( bytes memory _msg, bytes memory _signatures ) public view returns (bytes4) { bytes memory msgHashSignature = _signatures.slice(0, 65); bytes memory loginKeyAuthorizationSignature = _signatures.slice(65, 65); address loginKeyAddress = _getEthSignedMessageHash(_msg).recover( msgHashSignature ); bytes32 loginKeyAuthorizationMessageHash = keccak256(abi.encodePacked( loginKeyAddress )).toEthSignedMessageHash(); address authorizationSigner = loginKeyAuthorizationMessageHash.recover( loginKeyAuthorizationSignature ); if(authKeys[authorizationSigner]) { return VALID_SIG; } else { return INVALID_SIG; } } /** * Internal functions */ /// @dev Validate an authKey /// @param _authKey Address of the auth key to validate function _validateAuthKey(address _authKey) internal view { require(authKeys[_authKey] == true || msg.sender == address(this), "Auth key is invalid"); } /// @dev Validate signatures from an AuthKeyMetaTx /// @param _txDataMessageHash Ethereum signed message of the transaction /// @param _transactionDataSignature Signed tx data /// @return Address of the auth key that signed the data function _validateAuthKeyMetaTxSigs( bytes32 _txDataMessageHash, bytes memory _transactionDataSignature ) internal view returns (address) { address transactionDataSigner = _txDataMessageHash.recover(_transactionDataSignature); _validateAuthKey(transactionDataSigner); return transactionDataSigner; } /// @dev Validate signatures from an AuthKeyMetaTx /// @param _txDataMessageHash Ethereum signed message of the transaction /// @param _transactionDataSignature Signed tx data /// @param _loginKeyAuthorizationSignature Signed loginKey /// @return Address of the login key that signed the data function validateLoginKeyMetaTxSigs( bytes32 _txDataMessageHash, bytes memory _transactionDataSignature, bytes memory _loginKeyAuthorizationSignature ) public view returns (address) { address transactionDataSigner = _txDataMessageHash.recover( _transactionDataSignature ); bytes32 loginKeyAuthorizationMessageHash = keccak256(abi.encodePacked( transactionDataSigner )).toEthSignedMessageHash(); address authorizationSigner = loginKeyAuthorizationMessageHash.recover( _loginKeyAuthorizationSignature ); _validateAuthKey(authorizationSigner); return transactionDataSigner; } /// @dev Execute a transaction without a refund /// @notice This is the transaction sent from the CBA /// @param _destination Destination of the transaction /// @param _value Value of the transaction /// @param _data Data of the transaction /// @param _gasLimit Gas limit of the transaction /// @return Response of the call function _executeTransaction( address _destination, uint256 _value, bytes memory _data, uint256 _gasLimit ) internal returns (bytes memory) { (bool success, bytes memory response) = _destination.call.gas(_gasLimit).value(_value)(_data); if (!success) { bytes32 encodedData = _encodeData(nonce, _destination, _value, _data); emit CallFailed(encodedData); } // Increment nonce here so that both relayed and non-relayed calls will increment nonce // Must be incremented after !success data encode in order to encode original nonce nonce++; return response; } /// @dev Issue a refund /// @param _startGas Starting gas at the beginning of the transaction /// @param _gasPrice Gas price to use when sending a refund function _issueRefund( uint256 _startGas, uint256 _gasPrice ) internal { uint256 _gasUsed = _startGas.sub(gasleft()); require(_gasUsed.mul(_gasPrice) <= address(this).balance, "Insufficient gas for refund"); msg.sender.transfer(_gasUsed.mul(_gasPrice)); } /// @dev Get the gas buffer for each transaction /// @notice This takes into account the input params as well as the fixed /// @notice cost of checking if the account has enough gas left as well as the /// @notice transfer to the relayer /// @param _txData Input data of the transaction /// @return Total cost of input data and final require and transfer function _getGasBuffer(bytes memory _txData) internal view returns (uint256) { // Input data cost uint256 costPerByte = 68; uint256 txDataCost = _txData.length * costPerByte; // Cost of require and transfer uint256 costPerCheck = 10000; return txDataCost.add(costPerCheck); } /// @dev Encode data for a failed transaction /// @param _nonce Nonce of the transaction /// @param _destination Destination of the transaction /// @param _value Value of the transaction /// @param _data Data of the transaction /// @return Encoded data hash function _encodeData( uint256 _nonce, address _destination, uint256 _value, bytes memory _data ) internal pure returns (bytes32) { return keccak256(abi.encodePacked( _nonce, _destination, _value, _data )); } /// @dev Adds ETH signed message prefix to bytes message and hashes it /// @param _msg Bytes message before adding the prefix /// @return Prefixed and hashed message function _getEthSignedMessageHash(bytes memory _msg) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", _uint2str(_msg.length), _msg)); } /// @dev Convert uint to string /// @param _num Uint to be converted /// @return String equivalent of the uint function _uint2str(uint _num) private pure returns (string memory _uintAsString) { if (_num == 0) { return "0"; } uint i = _num; uint j = _num; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } } // File: contracts/account/LoginKeyMetaTxAccount.sol pragma solidity 0.5.12; /** * @title LoginKeyMetaTxAccount * @author Authereum, Inc. * @dev Contract used by login keys to send transactions. Login key firwall checks * @dev are performed in this contract as well. */ contract LoginKeyMetaTxAccount is BaseAccount { /// @dev Execute an loginKey meta transaction /// @param _destinations Destinations of the transaction /// @param _datas Datas of the transaction /// @param _values Values of the transaction /// @param _gasLimits Gas limits of the transaction /// @param _transactionDataSignatures Signed tx datas /// @param _loginKeyAuthorizationSignature Signed loginKey /// @return Response of the call function executeMultipleLoginKeyMetaTx( address[] memory _destinations, bytes[] memory _datas, uint256[] memory _values, uint256[] memory _gasLimits, bytes[] memory _transactionDataSignatures, bytes memory _loginKeyAuthorizationSignature ) public returns (bytes[] memory) { uint256 startGas = gasleft(); // Verify data length verifyLoginKeyParamDataLength( _destinations, _datas, _values, _gasLimits, _transactionDataSignatures ); // Execute transactions individually bytes[] memory returnValues = new bytes[](_destinations.length); for(uint i = 0; i < _destinations.length; i++) { returnValues[i] = _executeLoginKeyMetaTx( _destinations[i], _datas[i], _values[i], _gasLimits[i], _transactionDataSignatures[i], _loginKeyAuthorizationSignature ); } // Refund gas costs _issueRefund(startGas, tx.gasprice); return returnValues; } /// @dev Check if a loginKey is valid /// @param _transactionDataSigner loginKey that signed the tx data /// @param _loginKeyAuthorizationSignature Signed loginKey /// @return True if login key is valid function isValidLoginKey( address _transactionDataSigner, bytes memory _loginKeyAuthorizationSignature ) public view returns (bool) { bytes32 loginKeyAuthorizationMessageHash = keccak256(abi.encodePacked( _transactionDataSigner )).toEthSignedMessageHash(); address authorizationSigner = loginKeyAuthorizationMessageHash.recover( _loginKeyAuthorizationSignature ); return authKeys[authorizationSigner]; } /** * Internal functions */ /// @dev Execute an loginKey meta transaction /// @param _destination Destination of the transaction /// @param _data Data of the transaction /// @param _value Value of the transaction /// @param _gasLimit Gas limit of the transaction /// @param _transactionDataSignature Signed tx data /// @param _loginKeyAuthorizationSignature Signed loginKey /// @return Response of the call function _executeLoginKeyMetaTx( address _destination, bytes memory _data, uint256 _value, uint256 _gasLimit, bytes memory _transactionDataSignature, bytes memory _loginKeyAuthorizationSignature ) internal returns (bytes memory) { uint256 startGas = gasleft(); // Login key cannot upgrade the contract require(_checkDestination(_destination), "Login key is not able to upgrade to proxy"); bytes32 _txDataMessageHash = keccak256(abi.encodePacked( address(this), msg.sig, CHAIN_ID, _destination, _data, _value, nonce, tx.gasprice, _gasLimit )).toEthSignedMessageHash(); validateLoginKeyMetaTxSigs( _txDataMessageHash, _transactionDataSignature, _loginKeyAuthorizationSignature ); return _executeTransaction( _destination, _value, _data, _gasLimit ); } /// @dev Verify the length of the input data /// @param _destinations Destinations of the transaction /// @param _dataArray Data of the transactions /// @param _values Values of the transaction /// @param _gasLimits Gas limits of the transaction /// @param _transactionDataSignatures Signed tx data function verifyLoginKeyParamDataLength( address[] memory _destinations, bytes[] memory _dataArray, uint256[] memory _values, uint256[] memory _gasLimits, bytes[] memory _transactionDataSignatures ) internal view { require(_destinations.length == _values.length, "Invalid values length"); require(_destinations.length == _dataArray.length, "Invalid dataArray length"); require(_destinations.length == _gasLimits.length, "Invalid gasLimits length"); require(_destinations.length == _transactionDataSignatures.length, "Invalid transactionDataSignatures length"); } /// @dev Check to see if the destination is self. /// @notice The login key is not able to upgrade the proxy by transacting with itself. /// @notice This transaction will throw if an upgrade is attempted /// @param _destination Destination address /// @return True if the destination is not self function _checkDestination(address _destination) internal view returns (bool) { return (address(this) != _destination); } } // File: contracts/account/AuthKeyMetaTxAccount.sol pragma solidity 0.5.12; /** * @title AuthKeyMetaTxAccount * @author Authereum, Inc. * @dev Contract used by auth keys to send transactions. */ contract AuthKeyMetaTxAccount is BaseAccount { /// @dev Execute multiple authKey meta transactiona /// @param _destinations Destinations of the transaction /// @param _datas Data of the transactions /// @param _values Values of the transaction /// @param _gasLimits Gas limits of the transaction /// @param _transactionDataSignatures Signed tx data function executeMultipleAuthKeyMetaTx( address[] memory _destinations, bytes[] memory _datas, uint256[] memory _values, uint256[] memory _gasLimits, bytes[] memory _transactionDataSignatures ) public returns (bytes[] memory) { uint256 startGas = gasleft(); // Verify data length verifyAuthKeyParamDataLength( _destinations, _datas, _values, _gasLimits, _transactionDataSignatures ); // Execute transactions individually bytes[] memory returnValues = new bytes[](_destinations.length); for(uint i = 0; i < _destinations.length; i++) { returnValues[i] = _executeAuthKeyMetaTx( _destinations[i], _datas[i], _values[i], _gasLimits[i], _transactionDataSignatures[i] ); } // Refund gas costs _issueRefund(startGas, tx.gasprice); return returnValues; } /** * Internal functions */ /// @dev Execute an authKey meta transaction /// @param _destination Destination of the transaction /// @param _data Data of the transaction /// @param _value Value of the transaction /// @param _gasLimit Gas limit of the transaction /// @param _transactionDataSignature Signed tx data /// @return Response of the call function _executeAuthKeyMetaTx( address _destination, bytes memory _data, uint256 _value, uint256 _gasLimit, bytes memory _transactionDataSignature ) internal returns (bytes memory) { bytes32 _txDataMessageHash = keccak256(abi.encodePacked( address(this), msg.sig, CHAIN_ID, _destination, _data, _value, nonce, tx.gasprice, _gasLimit )).toEthSignedMessageHash(); // Validate the signer _validateAuthKeyMetaTxSigs( _txDataMessageHash, _transactionDataSignature ); return _executeTransaction( _destination, _value, _data, _gasLimit ); } /// @dev Verify the length of the input data /// @param _destinations Destinations of the transaction /// @param _dataArray Data of the transactions /// @param _values Values of the transaction /// @param _gasLimits Gas limits of the transaction /// @param _transactionDataSignatures Signed tx data function verifyAuthKeyParamDataLength( address[] memory _destinations, bytes[] memory _dataArray, uint256[] memory _values, uint256[] memory _gasLimits, bytes[] memory _transactionDataSignatures ) internal view { require(_destinations.length == _values.length, "Invalid values length"); require(_destinations.length == _dataArray.length, "Invalid dataArray length"); require(_destinations.length == _gasLimits.length, "Invalid gasLimits length"); require(_destinations.length == _transactionDataSignatures.length, "Invalid gasLimits length"); } } // File: contracts/utils/Address.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/account/AccountUpgradeability.sol pragma solidity 0.5.12; /** * @title AccountUpgradeability * @author Authereum, Inc. * @dev The upgradeability logic for an Authereum account. */ contract AccountUpgradeability is BaseAccount { /// @dev Storage slot with the address of the current implementation. /// @notice This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted /// @notice by 1, and is validated in the constructor. bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /// Only allow this contract to perform upgrade logic modifier onlySelf() { require(address(this) == msg.sender); _; } /// @dev Upgrades the proxy to the newest implementation of a contract and /// @dev forwards a function call to it. /// @notice This is useful to initialize the proxied contract. /// @param _newImplementation Address of the new implementation. /// @param _data Array of initialize data function upgradeToAndCall( address _newImplementation, bytes memory _data ) public onlySelf { setImplementation(_newImplementation); (bool success,) = _newImplementation.delegatecall(_data); require(success); emit Upgraded(_newImplementation); } /// @dev Sets the implementation address of the proxy. /// @notice This is only meant to be called when upgrading self /// @notice The initial setImplementation for a proxy is set during /// @notice the proxy's initialization, not with this call /// @param _newImplementation Address of the new implementation. function setImplementation(address _newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(_newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, _newImplementation) } } } // File: contracts/account/AuthereumAccount.sol pragma solidity 0.5.12; /** * @title AuthereumAccount * @author Authereum, Inc. * @dev Top-level contract used when creating an Authereum account. * @dev This contract is meant to only hold the version. All other logic is inherited. */ contract AuthereumAccount is BaseAccount, LoginKeyMetaTxAccount, AuthKeyMetaTxAccount, AccountUpgradeability { string constant public authereumVersion = "2019102500"; }
Check to see if the destination is self. The login key is not able to upgrade the proxy by transacting with itself. This transaction will throw if an upgrade is attempted _destination Destination address return True if the destination is not self
function _checkDestination(address _destination) internal view returns (bool) { return (address(this) != _destination); }
974,997
// SPDX-License-Identifier: BUSL-1.1 // Gearbox. Generalized leverage protocol that allows to take leverage and then use it across other DeFi protocols and platforms in a composable way. // (c) Gearbox.fi, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {AddressProvider} from "../core/AddressProvider.sol"; import {ACL} from "../core/ACL.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; import {CurveV1Adapter} from "../adapters/CurveV1.sol"; import {UniswapV2Adapter} from "../adapters/UniswapV2.sol"; import {UniswapV3Adapter} from "../adapters/UniswapV3.sol"; import {YearnAdapter} from "../adapters/YearnV2.sol"; contract AdaptersDeployer is Ownable { struct AdapterConfig { address targetContract; // Adapter types: // UNISWAP_V2 = 1; // UNISWAP_V3 = 2; // CURVE_V1 = 3; // LP_YEARN = 4; uint256 adapterType; } struct DeployOpts { address addressProvider; address creditManager; AdapterConfig[] adapters; } struct Adapter { address adapter; address targetContract; } AddressProvider public addressProvider; ICreditFilter public creditFilter; Adapter[] public adapters; address public root; constructor(DeployOpts memory opts) { addressProvider = AddressProvider(opts.addressProvider); // T:[PD-3] creditFilter = ICreditManager(opts.creditManager).creditFilter(); // T:[PD-3] address newAdapter; // T:[PD-3] for (uint256 i = 0; i < opts.adapters.length; i++) { if (opts.adapters[i].adapterType == Constants.UNISWAP_V2) { newAdapter = address( new UniswapV2Adapter( opts.creditManager, opts.adapters[i].targetContract ) ); // T:[PD-3] } else if (opts.adapters[i].adapterType == Constants.UNISWAP_V3) { newAdapter = address( new UniswapV3Adapter( opts.creditManager, opts.adapters[i].targetContract ) ); // T:[PD-3] } else if (opts.adapters[i].adapterType == Constants.CURVE_V1) { newAdapter = address( new CurveV1Adapter( opts.creditManager, opts.adapters[i].targetContract ) ); // T:[PD-3] } else if (opts.adapters[i].adapterType == Constants.LP_YEARN) { newAdapter = address( new YearnAdapter( opts.creditManager, opts.adapters[i].targetContract ) ); } // T:[PD-3] Adapter memory adapter = Adapter( newAdapter, opts.adapters[i].targetContract ); // T:[PD-3] adapters.push(adapter); // T:[PD-3] } root = ACL(addressProvider.getACL()).owner(); // T:Todo } function connectAdapters() external onlyOwner // T:[PD-3] { ACL acl = ACL(addressProvider.getACL()); // T:[PD-3] for (uint256 i; i < adapters.length; i++) { creditFilter.allowContract( adapters[i].targetContract, adapters[i].adapter ); } // creditFilter.allowPlugin(addressProvider.getLeveragedActions()); acl.transferOwnership(root); // T:[PD-3] // Discussable // selfdestruct(msg.sender); } // Will be used in case of connectAdapters() revert function getRootBack() external onlyOwner { ACL acl = ACL(addressProvider.getACL()); // T:[PD-3] acl.transferOwnership(root); } function destoy() external onlyOwner { selfdestruct(msg.sender); } } // 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: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {IAppAddressProvider} from "../interfaces/app/IAppAddressProvider.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title AddressRepository /// @notice Stores addresses of deployed contracts contract AddressProvider is Ownable, IAppAddressProvider { // Mapping which keeps all addresses mapping(bytes32 => address) public addresses; // Emits each time when new address is set event AddressSet(bytes32 indexed service, address indexed newAddress); // This event is triggered when a call to ClaimTokens succeeds. event Claimed(uint256 user_id, address account, uint256 amount, bytes32 leaf); // Repositories & services bytes32 public constant CONTRACTS_REGISTER = "CONTRACTS_REGISTER"; bytes32 public constant ACL = "ACL"; bytes32 public constant PRICE_ORACLE = "PRICE_ORACLE"; bytes32 public constant ACCOUNT_FACTORY = "ACCOUNT_FACTORY"; bytes32 public constant DATA_COMPRESSOR = "DATA_COMPRESSOR"; bytes32 public constant TREASURY_CONTRACT = "TREASURY_CONTRACT"; bytes32 public constant GEAR_TOKEN = "GEAR_TOKEN"; bytes32 public constant WETH_TOKEN = "WETH_TOKEN"; bytes32 public constant WETH_GATEWAY = "WETH_GATEWAY"; bytes32 public constant LEVERAGED_ACTIONS = "LEVERAGED_ACTIONS"; // Contract version uint256 public constant version = 1; constructor() { // @dev Emits first event for contract discovery emit AddressSet("ADDRESS_PROVIDER", address(this)); } /// @return Address of ACL contract function getACL() external view returns (address) { return _getAddress(ACL); // T:[AP-3] } /// @dev Sets address of ACL contract /// @param _address Address of ACL contract function setACL(address _address) external onlyOwner // T:[AP-15] { _setAddress(ACL, _address); // T:[AP-3] } /// @return Address of ContractsRegister function getContractsRegister() external view returns (address) { return _getAddress(CONTRACTS_REGISTER); // T:[AP-4] } /// @dev Sets address of ContractsRegister /// @param _address Address of ContractsRegister function setContractsRegister(address _address) external onlyOwner // T:[AP-15] { _setAddress(CONTRACTS_REGISTER, _address); // T:[AP-4] } /// @return Address of PriceOracle function getPriceOracle() external view override returns (address) { return _getAddress(PRICE_ORACLE); // T:[AP-5] } /// @dev Sets address of PriceOracle /// @param _address Address of PriceOracle function setPriceOracle(address _address) external onlyOwner // T:[AP-15] { _setAddress(PRICE_ORACLE, _address); // T:[AP-5] } /// @return Address of AccountFactory function getAccountFactory() external view returns (address) { return _getAddress(ACCOUNT_FACTORY); // T:[AP-6] } /// @dev Sets address of AccountFactory /// @param _address Address of AccountFactory function setAccountFactory(address _address) external onlyOwner // T:[AP-15] { _setAddress(ACCOUNT_FACTORY, _address); // T:[AP-7] } /// @return Address of AccountFactory function getDataCompressor() external view override returns (address) { return _getAddress(DATA_COMPRESSOR); // T:[AP-8] } /// @dev Sets address of AccountFactory /// @param _address Address of AccountFactory function setDataCompressor(address _address) external onlyOwner // T:[AP-15] { _setAddress(DATA_COMPRESSOR, _address); // T:[AP-8] } /// @return Address of Treasury contract function getTreasuryContract() external view returns (address) { return _getAddress(TREASURY_CONTRACT); //T:[AP-11] } /// @dev Sets address of Treasury Contract /// @param _address Address of Treasury Contract function setTreasuryContract(address _address) external onlyOwner // T:[AP-15] { _setAddress(TREASURY_CONTRACT, _address); //T:[AP-11] } /// @return Address of GEAR token function getGearToken() external view override returns (address) { return _getAddress(GEAR_TOKEN); // T:[AP-12] } /// @dev Sets address of GEAR token /// @param _address Address of GEAR token function setGearToken(address _address) external onlyOwner // T:[AP-15] { _setAddress(GEAR_TOKEN, _address); // T:[AP-12] } /// @return Address of WETH token function getWethToken() external view override returns (address) { return _getAddress(WETH_TOKEN); // T:[AP-13] } /// @dev Sets address of WETH token /// @param _address Address of WETH token function setWethToken(address _address) external onlyOwner // T:[AP-15] { _setAddress(WETH_TOKEN, _address); // T:[AP-13] } /// @return Address of WETH token function getWETHGateway() external view override returns (address) { return _getAddress(WETH_GATEWAY); // T:[AP-14] } /// @dev Sets address of WETH token /// @param _address Address of WETH token function setWETHGateway(address _address) external onlyOwner // T:[AP-15] { _setAddress(WETH_GATEWAY, _address); // T:[AP-14] } /// @return Address of WETH token function getLeveragedActions() external view override returns (address) { return _getAddress(LEVERAGED_ACTIONS); // T:[AP-7] } /// @dev Sets address of WETH token /// @param _address Address of WETH token function setLeveragedActions(address _address) external onlyOwner // T:[AP-15] { _setAddress(LEVERAGED_ACTIONS, _address); // T:[AP-7] } /// @return Address of key, reverts if key doesn't exist function _getAddress(bytes32 key) internal view returns (address) { address result = addresses[key]; require(result != address(0), Errors.AS_ADDRESS_NOT_FOUND); // T:[AP-1] return result; // T:[AP-3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] } /// @dev Sets address to map by its key /// @param key Key in string format /// @param value Address function _setAddress(bytes32 key, address value) internal { addresses[key] = value; // T:[AP-3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] emit AddressSet(key, value); // T:[AP-2] } } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title ACL keeps admins addresses /// More info: https://dev.gearbox.fi/security/roles contract ACL is Ownable { mapping(address => bool) public pausableAdminSet; mapping(address => bool) public unpausableAdminSet; // Contract version uint256 public constant version = 1; // emits each time when new pausable admin added event PausableAdminAdded(address indexed newAdmin); // emits each time when pausable admin removed event PausableAdminRemoved(address indexed admin); // emits each time when new unpausable admin added event UnpausableAdminAdded(address indexed newAdmin); // emits each times when unpausable admin removed event UnpausableAdminRemoved(address indexed admin); /// @dev Adds pausable admin address /// @param newAdmin Address of new pausable admin function addPausableAdmin(address newAdmin) external onlyOwner // T:[ACL-1] { pausableAdminSet[newAdmin] = true; // T:[ACL-2] emit PausableAdminAdded(newAdmin); // T:[ACL-2] } /// @dev Removes pausable admin /// @param admin Address of admin which should be removed function removePausableAdmin(address admin) external onlyOwner // T:[ACL-1] { pausableAdminSet[admin] = false; // T:[ACL-3] emit PausableAdminRemoved(admin); // T:[ACL-3] } /// @dev Returns true if the address is pausable admin and false if not function isPausableAdmin(address addr) external view returns (bool) { return pausableAdminSet[addr]; // T:[ACL-2,3] } /// @dev Adds unpausable admin address to the list /// @param newAdmin Address of new unpausable admin function addUnpausableAdmin(address newAdmin) external onlyOwner // T:[ACL-1] { unpausableAdminSet[newAdmin] = true; // T:[ACL-4] emit UnpausableAdminAdded(newAdmin); // T:[ACL-4] } /// @dev Removes unpausable admin /// @param admin Address of admin to be removed function removeUnpausableAdmin(address admin) external onlyOwner // T:[ACL-1] { unpausableAdminSet[admin] = false; // T:[ACL-5] emit UnpausableAdminRemoved(admin); // T:[ACL-5] } /// @dev Returns true if the address is unpausable admin and false if not function isUnpausableAdmin(address addr) external view returns (bool) { return unpausableAdminSet[addr]; // T:[ACL-4,5] } /// @dev Returns true if addr has configurator rights function isConfigurator(address account) external view returns (bool) { return account == owner(); // T:[ACL-6] } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {IAppCreditManager} from "./app/IAppCreditManager.sol"; import {DataTypes} from "../libraries/data/Types.sol"; /// @title Credit Manager interface /// @notice It encapsulates business logic for managing credit accounts /// /// More info: https://dev.gearbox.fi/developers/credit/credit_manager interface ICreditManager is IAppCreditManager { // Emits each time when the credit account is opened event OpenCreditAccount( address indexed sender, address indexed onBehalfOf, address indexed creditAccount, uint256 amount, uint256 borrowAmount, uint256 referralCode ); // Emits each time when the credit account is closed event CloseCreditAccount( address indexed owner, address indexed to, uint256 remainingFunds ); // Emits each time when the credit account is liquidated event LiquidateCreditAccount( address indexed owner, address indexed liquidator, uint256 remainingFunds ); // Emits each time when borrower increases borrowed amount event IncreaseBorrowedAmount(address indexed borrower, uint256 amount); // Emits each time when borrower adds collateral event AddCollateral( address indexed onBehalfOf, address indexed token, uint256 value ); // Emits each time when the credit account is repaid event RepayCreditAccount(address indexed owner, address indexed to); // Emit each time when financial order is executed event ExecuteOrder(address indexed borrower, address indexed target); // Emits each time when new fees are set event NewParameters( uint256 minAmount, uint256 maxAmount, uint256 maxLeverage, uint256 feeInterest, uint256 feeLiquidation, uint256 liquidationDiscount ); event TransferAccount(address indexed oldOwner, address indexed newOwner); // // CREDIT ACCOUNT MANAGEMENT // /** * @dev Opens credit account and provides credit funds. * - Opens credit account (take it from account factory) * - Transfers trader /farmers initial funds to credit account * - Transfers borrowed leveraged amount from pool (= amount x leverageFactor) calling lendCreditAccount() on connected Pool contract. * - Emits OpenCreditAccount event * Function reverts if user has already opened position * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#open-credit-account * * @param amount Borrowers own funds * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param leverageFactor Multiplier to borrowers own funds * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function openCreditAccount( uint256 amount, address onBehalfOf, uint256 leverageFactor, uint256 referralCode ) external override; /** * @dev Closes credit account * - Swaps all assets to underlying one using default swap protocol * - Pays borrowed amount + interest accrued + fees back to the pool by calling repayCreditAccount * - Transfers remaining funds to the trader / farmer * - Closes the credit account and return it to account factory * - Emits CloseCreditAccount event * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#close-credit-account * * @param to Address to send remaining funds * @param paths Exchange type data which provides paths + amountMinOut */ function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths) external override; /** * @dev Liquidates credit account * - Transfers discounted total credit account value from liquidators account * - Pays borrowed funds + interest + fees back to pool, than transfers remaining funds to credit account owner * - Transfer all assets from credit account to liquidator ("to") account * - Returns credit account to factory * - Emits LiquidateCreditAccount event * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#liquidate-credit-account * * @param borrower Borrower address * @param to Address to transfer all assets from credit account * @param force If true, use transfer function for transferring tokens instead of safeTransfer */ function liquidateCreditAccount( address borrower, address to, bool force ) external; /// @dev Repays credit account /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#repay-credit-account /// /// @param to Address to send credit account assets function repayCreditAccount(address to) external override; /// @dev Repays credit account with ETH. Restricted to be called by WETH Gateway only /// /// @param borrower Address of borrower /// @param to Address to send credit account assets function repayCreditAccountETH(address borrower, address to) external returns (uint256); /// @dev Increases borrowed amount by transferring additional funds from /// the pool if after that HealthFactor > minHealth /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrowed-amount /// /// @param amount Amount to increase borrowed amount function increaseBorrowedAmount(uint256 amount) external override; /// @dev Adds collateral to borrower's credit account /// @param onBehalfOf Address of borrower to add funds /// @param token Token address /// @param amount Amount to add function addCollateral( address onBehalfOf, address token, uint256 amount ) external override; /// @dev Returns true if the borrower has opened a credit account /// @param borrower Borrower account function hasOpenedCreditAccount(address borrower) external view override returns (bool); /// @dev Calculates Repay amount = borrow amount + interest accrued + fee /// /// More info: https://dev.gearbox.fi/developers/credit/economy#repay /// https://dev.gearbox.fi/developers/credit/economy#liquidate /// /// @param borrower Borrower address /// @param isLiquidated True if calculated repay amount for liquidator function calcRepayAmount(address borrower, bool isLiquidated) external view override returns (uint256); /// @dev Returns minimal amount for open credit account function minAmount() external view returns (uint256); /// @dev Returns maximum amount for open credit account function maxAmount() external view returns (uint256); /// @dev Returns maximum leveraged factor allowed for this pool function maxLeverageFactor() external view returns (uint256); /// @dev Returns underlying token address function underlyingToken() external view returns (address); /// @dev Returns address of connected pool function poolService() external view returns (address); /// @dev Returns address of CreditFilter function creditFilter() external view returns (ICreditFilter); /// @dev Returns address of CreditFilter function creditAccounts(address borrower) external view returns (address); /// @dev Executes filtered order on credit account which is connected with particular borrowers /// @param borrower Borrower address /// @param target Target smart-contract /// @param data Call data for call function executeOrder( address borrower, address target, bytes memory data ) external returns (bytes memory); /// @dev Approves token for msg.sender's credit account function approve(address targetContract, address token) external; /// @dev Approve tokens for credit accounts. Restricted for adapters only function provideCreditAccountAllowance( address creditAccount, address toContract, address token ) external; function transferAccountOwnership(address newOwner) external; /// @dev Returns address of borrower's credit account and reverts of borrower has no one. /// @param borrower Borrower address function getCreditAccountOrRevert(address borrower) external view override returns (address); // function feeSuccess() external view returns (uint256); function feeInterest() external view returns (uint256); function feeLiquidation() external view returns (uint256); function liquidationDiscount() external view returns (uint256); function minHealthFactor() external view returns (uint256); function defaultSwapContract() external view override returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; interface ICreditFilter { // Emits each time token is allowed or liquidtion threshold changed event TokenAllowed(address indexed token, uint256 liquidityThreshold); // Emits each time token is allowed or liquidtion threshold changed event TokenForbidden(address indexed token); // Emits each time contract is allowed or adapter changed event ContractAllowed(address indexed protocol, address indexed adapter); // Emits each time contract is forbidden event ContractForbidden(address indexed protocol); // Emits each time when fast check parameters are updated event NewFastCheckParameters(uint256 chiThreshold, uint256 fastCheckDelay); event TransferAccountAllowed( address indexed from, address indexed to, bool state ); event TransferPluginAllowed( address indexed pugin, bool state ); event PriceOracleUpdated(address indexed newPriceOracle); // // STATE-CHANGING FUNCTIONS // /// @dev Adds token to the list of allowed tokens /// @param token Address of allowed token /// @param liquidationThreshold The constant showing the maximum allowable ratio of Loan-To-Value for the i-th asset. function allowToken(address token, uint256 liquidationThreshold) external; /// @dev Adds contract to the list of allowed contracts /// @param targetContract Address of contract to be allowed /// @param adapter Adapter contract address function allowContract(address targetContract, address adapter) external; /// @dev Forbids contract and removes it from the list of allowed contracts /// @param targetContract Address of allowed contract function forbidContract(address targetContract) external; /// @dev Checks financial order and reverts if tokens aren't in list or collateral protection alerts /// @param creditAccount Address of credit account /// @param tokenIn Address of token In in swap operation /// @param tokenOut Address of token Out in swap operation /// @param amountIn Amount of tokens in /// @param amountOut Amount of tokens out function checkCollateralChange( address creditAccount, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut ) external; function checkMultiTokenCollateral( address creditAccount, uint256[] memory amountIn, uint256[] memory amountOut, address[] memory tokenIn, address[] memory tokenOut ) external; /// @dev Connects credit managaer, hecks that all needed price feeds exists and finalize config function connectCreditManager(address poolService) external; /// @dev Sets collateral protection for new credit accounts function initEnabledTokens(address creditAccount) external; function checkAndEnableToken(address creditAccount, address token) external; // // GETTERS // /// @dev Returns quantity of contracts in allowed list function allowedContractsCount() external view returns (uint256); /// @dev Returns of contract address from the allowed list by its id function allowedContracts(uint256 id) external view returns (address); /// @dev Reverts if token isn't in token allowed list function revertIfTokenNotAllowed(address token) external view; /// @dev Returns true if token is in allowed list otherwise false function isTokenAllowed(address token) external view returns (bool); /// @dev Returns quantity of tokens in allowed list function allowedTokensCount() external view returns (uint256); /// @dev Returns of token address from allowed list by its id function allowedTokens(uint256 id) external view returns (address); /// @dev Calculates total value for provided address /// More: https://dev.gearbox.fi/developers/credit/economy#total-value /// /// @param creditAccount Token creditAccount address function calcTotalValue(address creditAccount) external view returns (uint256 total); /// @dev Calculates Threshold Weighted Total Value /// More: https://dev.gearbox.fi/developers/credit/economy#threshold-weighted-value /// ///@param creditAccount Credit account address function calcThresholdWeightedValue(address creditAccount) external view returns (uint256 total); function contractToAdapter(address allowedContract) external view returns (address); /// @dev Returns address of underlying token function underlyingToken() external view returns (address); /// @dev Returns address & balance of token by the id of allowed token in the list /// @param creditAccount Credit account address /// @param id Id of token in allowed list /// @return token Address of token /// @return balance Token balance function getCreditAccountTokenById(address creditAccount, uint256 id) external view returns ( address token, uint256 balance, uint256 tv, uint256 twv ); /** * @dev Calculates health factor for the credit account * * sum(asset[i] * liquidation threshold[i]) * Hf = -------------------------------------------- * borrowed amount + interest accrued * * * More info: https://dev.gearbox.fi/developers/credit/economy#health-factor * * @param creditAccount Credit account address * @return Health factor in percents (see PERCENTAGE FACTOR in PercentageMath.sol) */ function calcCreditAccountHealthFactor(address creditAccount) external view returns (uint256); /// @dev Calculates credit account interest accrued /// More: https://dev.gearbox.fi/developers/credit/economy#interest-rate-accrued /// /// @param creditAccount Credit account address function calcCreditAccountAccruedInterest(address creditAccount) external view returns (uint256); /// @dev Return enabled tokens - token masks where each bit is "1" is token is enabled function enabledTokens(address creditAccount) external view returns (uint256); function liquidationThresholds(address token) external view returns (uint256); function priceOracle() external view returns (address); function updateUnderlyingTokenLiquidationThreshold() external; function revertIfCantIncreaseBorrowing( address creditAccount, uint256 minHealthFactor ) external view; function revertIfAccountTransferIsNotAllowed( address onwer, address creditAccount ) external view; function approveAccountTransfers(address from, bool state) external; function allowanceForAccountTransfers(address from, address to) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {PercentageMath} from "../math/PercentageMath.sol"; library Constants { uint256 constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // 25% of MAX_INT uint256 constant MAX_INT_4 = 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // REWARD FOR LEAN DEPLOYMENT MINING uint256 constant ACCOUNT_CREATION_REWARD = 1e5; uint256 constant DEPLOYMENT_COST = 1e17; // FEE = 10% uint256 constant FEE_INTEREST = 1000; // 10% // FEE + LIQUIDATION_FEE 2% uint256 constant FEE_LIQUIDATION = 200; // Liquidation premium 5% uint256 constant LIQUIDATION_DISCOUNTED_SUM = 9500; // 100% - LIQUIDATION_FEE - LIQUIDATION_PREMIUM uint256 constant UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD = LIQUIDATION_DISCOUNTED_SUM - FEE_LIQUIDATION; // Seconds in a year uint256 constant SECONDS_PER_YEAR = 365 days; uint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = SECONDS_PER_YEAR * 3 /2; // 1e18 uint256 constant RAY = 1e27; uint256 constant WAD = 1e18; // OPERATIONS uint8 constant OPERATION_CLOSURE = 1; uint8 constant OPERATION_REPAY = 2; uint8 constant OPERATION_LIQUIDATION = 3; // Decimals for leverage, so x4 = 4*LEVERAGE_DECIMALS for openCreditAccount function uint8 constant LEVERAGE_DECIMALS = 100; // Maximum withdraw fee for pool in percentage math format. 100 = 1% uint8 constant MAX_WITHDRAW_FEE = 100; uint256 constant CHI_THRESHOLD = 9950; uint256 constant HF_CHECK_INTERVAL_DEFAULT = 4; uint256 constant NO_SWAP = 0; uint256 constant UNISWAP_V2 = 1; uint256 constant UNISWAP_V3 = 2; uint256 constant CURVE_V1 = 3; uint256 constant LP_YEARN = 4; uint256 constant EXACT_INPUT = 1; uint256 constant EXACT_OUTPUT = 2; } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title Errors library library Errors { // // COMMON // string public constant ZERO_ADDRESS_IS_NOT_ALLOWED = "Z0"; string public constant NOT_IMPLEMENTED = "NI"; string public constant INCORRECT_PATH_LENGTH = "PL"; string public constant INCORRECT_ARRAY_LENGTH = "CR"; string public constant REGISTERED_CREDIT_ACCOUNT_MANAGERS_ONLY = "CP"; string public constant REGISTERED_POOLS_ONLY = "RP"; string public constant INCORRECT_PARAMETER = "IP"; // // MATH // string public constant MATH_MULTIPLICATION_OVERFLOW = "M1"; string public constant MATH_ADDITION_OVERFLOW = "M2"; string public constant MATH_DIVISION_BY_ZERO = "M3"; // // POOL // string public constant POOL_CONNECTED_CREDIT_MANAGERS_ONLY = "PS0"; string public constant POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER = "PS1"; string public constant POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT = "PS2"; string public constant POOL_INCORRECT_WITHDRAW_FEE = "PS3"; string public constant POOL_CANT_ADD_CREDIT_MANAGER_TWICE = "PS4"; // // CREDIT MANAGER // string public constant CM_NO_OPEN_ACCOUNT = "CM1"; string public constant CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT = "CM2"; string public constant CM_INCORRECT_AMOUNT = "CM3"; string public constant CM_CAN_LIQUIDATE_WITH_SUCH_HEALTH_FACTOR = "CM4"; string public constant CM_CAN_UPDATE_WITH_SUCH_HEALTH_FACTOR = "CM5"; string public constant CM_WETH_GATEWAY_ONLY = "CM6"; string public constant CM_INCORRECT_PARAMS = "CM7"; string public constant CM_INCORRECT_FEES = "CM8"; string public constant CM_MAX_LEVERAGE_IS_TOO_HIGH = "CM9"; string public constant CM_CANT_CLOSE_WITH_LOSS = "CMA"; string public constant CM_TARGET_CONTRACT_iS_NOT_ALLOWED = "CMB"; string public constant CM_TRANSFER_FAILED = "CMC"; string public constant CM_INCORRECT_NEW_OWNER = "CME"; // // ACCOUNT FACTORY // string public constant AF_CANT_CLOSE_CREDIT_ACCOUNT_IN_THE_SAME_BLOCK = "AF1"; string public constant AF_MINING_IS_FINISHED = "AF2"; string public constant AF_CREDIT_ACCOUNT_NOT_IN_STOCK = "AF3"; string public constant AF_EXTERNAL_ACCOUNTS_ARE_FORBIDDEN = "AF4"; // // ADDRESS PROVIDER // string public constant AS_ADDRESS_NOT_FOUND = "AP1"; // // CONTRACTS REGISTER // string public constant CR_POOL_ALREADY_ADDED = "CR1"; string public constant CR_CREDIT_MANAGER_ALREADY_ADDED = "CR2"; // // CREDIT_FILTER // string public constant CF_UNDERLYING_TOKEN_FILTER_CONFLICT = "CF0"; string public constant CF_INCORRECT_LIQUIDATION_THRESHOLD = "CF1"; string public constant CF_TOKEN_IS_NOT_ALLOWED = "CF2"; string public constant CF_CREDIT_MANAGERS_ONLY = "CF3"; string public constant CF_ADAPTERS_ONLY = "CF4"; string public constant CF_OPERATION_LOW_HEALTH_FACTOR = "CF5"; string public constant CF_TOO_MUCH_ALLOWED_TOKENS = "CF6"; string public constant CF_INCORRECT_CHI_THRESHOLD = "CF7"; string public constant CF_INCORRECT_FAST_CHECK = "CF8"; string public constant CF_NON_TOKEN_CONTRACT = "CF9"; string public constant CF_CONTRACT_IS_NOT_IN_ALLOWED_LIST = "CFA"; string public constant CF_FAST_CHECK_NOT_COVERED_COLLATERAL_DROP = "CFB"; string public constant CF_SOME_LIQUIDATION_THRESHOLD_MORE_THAN_NEW_ONE = "CFC"; string public constant CF_ADAPTER_CAN_BE_USED_ONLY_ONCE = "CFD"; string public constant CF_INCORRECT_PRICEFEED = "CFE"; string public constant CF_TRANSFER_IS_NOT_ALLOWED = "CFF"; string public constant CF_CREDIT_MANAGER_IS_ALREADY_SET = "CFG"; // // CREDIT ACCOUNT // string public constant CA_CONNECTED_CREDIT_MANAGER_ONLY = "CA1"; string public constant CA_FACTORY_ONLY = "CA2"; // // PRICE ORACLE // string public constant PO_PRICE_FEED_DOESNT_EXIST = "PO0"; string public constant PO_TOKENS_WITH_DECIMALS_MORE_18_ISNT_ALLOWED = "PO1"; string public constant PO_AGGREGATOR_DECIMALS_SHOULD_BE_18 = "PO2"; // // ACL // string public constant ACL_CALLER_NOT_PAUSABLE_ADMIN = "ACL1"; string public constant ACL_CALLER_NOT_CONFIGURATOR = "ACL2"; // // WETH GATEWAY // string public constant WG_DESTINATION_IS_NOT_WETH_COMPATIBLE = "WG1"; string public constant WG_RECEIVE_IS_NOT_ALLOWED = "WG2"; string public constant WG_NOT_ENOUGH_FUNDS = "WG3"; // // LEVERAGED ACTIONS // string public constant LA_INCORRECT_VALUE = "LA1"; string public constant LA_HAS_VALUE_WITH_TOKEN_TRANSFER = "LA2"; string public constant LA_UNKNOWN_SWAP_INTERFACE = "LA3"; string public constant LA_UNKNOWN_LP_INTERFACE = "LA4"; string public constant LA_LOWER_THAN_AMOUNT_MIN = "LA5"; string public constant LA_TOKEN_OUT_IS_NOT_COLLATERAL = "LA6"; // // YEARN PRICE FEED // string public constant YPF_PRICE_PER_SHARE_OUT_OF_RANGE = "YP1"; string public constant YPF_INCORRECT_LIMITER_PARAMETERS = "YP2"; // // TOKEN DISTRIBUTOR // string public constant TD_WALLET_IS_ALREADY_CONNECTED_TO_VC = "TD1"; string public constant TD_INCORRECT_WEIGHTS = "TD2"; string public constant TD_NON_ZERO_BALANCE_AFTER_DISTRIBUTION = "TD3"; string public constant TD_CONTRIBUTOR_IS_NOT_REGISTERED = "TD4"; } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {ICurvePool} from "../integrations/curve/ICurvePool.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {CreditAccount} from "../credit/CreditAccount.sol"; import {CreditManager} from "../credit/CreditManager.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title CurveV1 adapter contract CurveV1Adapter is ICurvePool, ReentrancyGuard { using SafeMath for uint256; // Original pool contract ICurvePool public curvePool; ICreditManager public creditManager; ICreditFilter public creditFilter; /// @dev Constructor /// @param _creditManager Address Credit manager /// @param _curvePool Address of curve-compatible pool constructor(address _creditManager, address _curvePool) { require( _creditManager != address(0) && _creditManager != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); creditManager = ICreditManager(_creditManager); creditFilter = ICreditFilter(creditManager.creditFilter()); curvePool = ICurvePool(_curvePool); } function coins(uint256 i) external view override returns (address) { return ICurvePool(curvePool).coins(i); } /// @dev Exchanges two assets on Curve-compatible pools. Restricted for pool calls only /// @param i Index value for the coin to send /// @param j Index value of the coin to receive /// @param dx Amount of i being exchanged /// @param min_dy Minimum amount of j to receive function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external override nonReentrant { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); // M:[CVA-1] address tokenIn = curvePool.coins(uint256(i)); // M:[CVA-1] address tokenOut = curvePool.coins(uint256(j)); // M:[CVA-1] creditManager.provideCreditAccountAllowance( creditAccount, address(curvePool), tokenIn ); // M:[CVA-1] uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // M:[CVA-1] uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); // M:[CVA-1] bytes memory data = abi.encodeWithSelector( bytes4(0x3df02124), // "exchange(int128,int128,uint256,uint256)", i, j, dx, min_dy ); // M:[CVA-1] creditManager.executeOrder(msg.sender, address(curvePool), data); // M:[CVA-1] creditFilter.checkCollateralChange( creditAccount, tokenIn, tokenOut, balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)), IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore) ); // M:[CVA-1] } function exchange_underlying( int128, // i int128, // j uint256, // dx uint256 // min_dy ) external pure override { revert(Errors.NOT_IMPLEMENTED); } function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view override returns (uint256) { return curvePool.get_dy_underlying(i, j, dx); } function get_dy( int128 i, int128 j, uint256 dx ) external view override returns (uint256) { return curvePool.get_dy(i, j, dx); } function get_virtual_price() external view override returns (uint256) { return curvePool.get_virtual_price(); } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IUniswapV2Router02} from "../integrations/uniswap/IUniswapV2Router02.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {CreditManager} from "../credit/CreditManager.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; /// @title UniswapV2 Router adapter contract UniswapV2Adapter is IUniswapV2Router02, ReentrancyGuard { using SafeMath for uint256; ICreditManager public creditManager; ICreditFilter public creditFilter; address public router; /// @dev Constructor /// @param _creditManager Address Credit manager /// @param _router Address of IUniswapV2Router02 constructor(address _creditManager, address _router) { require( _creditManager != address(0) && _router != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); creditManager = ICreditManager(_creditManager); creditFilter = ICreditFilter(creditManager.creditFilter()); router = _router; } /** * @dev Swap tokens to exact tokens using Uniswap-compatible protocol * - checks that swap contract is allowed * - checks that in/out tokens are in allowed list * - checks that required allowance is enough, if not - set it to MAX_INT * - call swap function on credit account contracts * @param amountOut The amount of output tokens to receive. * @param amountInMax The maximum amount of input tokens that can be required before the transaction reverts. * @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of * addresses must exist and have liquidity. * @param deadline Unix timestamp after which the transaction will revert. * for more information check uniswap documentation: https://uniswap.org/docs/v2/smart-contracts/router02/ */ function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address, uint256 deadline ) external override nonReentrant returns (uint256[] memory amounts) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); address tokenIn = path[0]; address tokenOut = path[path.length - 1]; creditManager.provideCreditAccountAllowance( creditAccount, router, tokenIn ); uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // M:[CVA-1] uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); // M:[CVA-1] bytes memory data = abi.encodeWithSelector( bytes4(0x8803dbee), // "swapTokensForExactTokens(uint256,uint256,address[],address,uint256)", amountOut, amountInMax, path, creditAccount, deadline ); amounts = abi.decode( creditManager.executeOrder(msg.sender, router, data), (uint256[]) ); creditFilter.checkCollateralChange( creditAccount, tokenIn, tokenOut, balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)), IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore) ); // ToDo: CHECK(!) } /** * Swaps exact tokens to tokens on Uniswap compatible protocols * - checks that swap contract is allowed * - checks that in/out tokens are in allowed list * - checks that required allowance is enough, if not - set it to MAX_INT * - call swap function on credit account contracts * @param amountIn The amount of input tokens to send. * @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert. * @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of * addresses must exist and have liquidity. * deadline Unix timestamp after which the transaction will revert. * for more information check uniswap documentation: https://uniswap.org/docs/v2/smart-contracts/router02/ */ /// #limit amountOutMin == 0 && /// amountIn > 0 && /// deadline > block.timestamp; /// #hint path.length == 2 && /// (path[0] == 0x0eb775F99A28cb591Fa449ca74eF8E7cEd3A609a || /// path[0] == 0x47f93809340CAA8108f8D62A4E4f6C2A815e882E || /// path[0] == 0xcFB04485A211b0573Ace62EBDCcC5cFC51107EaA || /// path[0] == 0x7FA12843d541A1Fd905d620cD810D05BfDC3226e || /// path[0] == 0x171A8DEa3fd87D46421DFc6F0d11Cc3c8C75f54D) && /// (path[1] == 0x0eb775F99A28cb591Fa449ca74eF8E7cEd3A609a || /// path[1] == 0x47f93809340CAA8108f8D62A4E4f6C2A815e882E || /// path[1] == 0xcFB04485A211b0573Ace62EBDCcC5cFC51107EaA || /// path[1] == 0x7FA12843d541A1Fd905d620cD810D05BfDC3226e || /// path[1] == 0x171A8DEa3fd87D46421DFc6F0d11Cc3c8C75f54D); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address, uint256 deadline ) external override nonReentrant returns (uint256[] memory amounts) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); address tokenIn = path[0]; address tokenOut = path[path.length - 1]; creditManager.provideCreditAccountAllowance( creditAccount, router, tokenIn ); uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // M: uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); // M: bytes memory data = abi.encodeWithSelector( bytes4(0x38ed1739), // "swapExactTokensForTokens(uint256,uint256,address[],address,uint256)", amountIn, amountOutMin, path, creditAccount, deadline ); amounts = abi.decode( creditManager.executeOrder(msg.sender, router, data), (uint256[]) ); creditFilter.checkCollateralChange( creditAccount, tokenIn, tokenOut, balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)), IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore) ); // ToDo: CHECK(!) } function removeLiquidityETHSupportingFeeOnTransferTokens( address, // token, uint256, // liquidity, uint256, // amountTokenMin, uint256, // amountETHMin, address, // to, uint256 // deadline ) external pure override returns (uint256) { revert(Errors.NOT_IMPLEMENTED); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address, // token, uint256, // liquidity, uint256, // amountTokenMin, uint256, // amountETHMin, address, // to, uint256, // deadline, bool, // approveMax, uint8, // v, bytes32, // r, bytes32 // s ) external pure override returns (uint256) { revert(Errors.NOT_IMPLEMENTED); } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256, // amountIn, uint256, // amountOutMin, address[] calldata, // path, address, // to, uint256 // deadline ) external pure override { revert(Errors.NOT_IMPLEMENTED); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256, // amountOutMin, address[] calldata, // path, address, // to, uint256 // deadline ) external payable override { revert(Errors.NOT_IMPLEMENTED); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256, // amountIn, uint256, // amountOutMin, address[] calldata, // path, address, // to, uint256 // deadline ) external pure override { revert(Errors.NOT_IMPLEMENTED); } function factory() external view override returns (address) { return IUniswapV2Router02(router).factory(); } function WETH() external view override returns (address) { return IUniswapV2Router02(router).WETH(); } function addLiquidity( address, // tokenA, address, // tokenB, uint256, // amountADesired, uint256, // amountBDesired, uint256, // amountAMin, uint256, // amountBMin, address, // to, uint256 // deadline ) external pure override returns ( uint256, uint256, uint256 ) { revert(Errors.NOT_IMPLEMENTED); } function addLiquidityETH( address, // token, uint256, // amountTokenDesired, uint256, // amountTokenMin, uint256, // amountETHMin, address, // to, uint256 // deadline ) external payable override returns ( uint256, uint256, uint256 ) { revert(Errors.NOT_IMPLEMENTED); } function removeLiquidity( address, // tokenA, address, // tokenB, uint256, // liquidity, uint256, // amountAMin, uint256, // amountBMin, address, // to, uint256 // deadline ) external pure override returns (uint256, uint256) { revert(Errors.NOT_IMPLEMENTED); } function removeLiquidityETH( address, // token, uint256, // liquidity, uint256, // amountTokenMin, uint256, // amountETHMin, address, // to, uint256 // deadline ) external pure override returns (uint256, uint256) { revert(Errors.NOT_IMPLEMENTED); } function removeLiquidityWithPermit( address, // tokenA, address, // tokenB, uint256, // liquidity, uint256, // amountAMin, uint256, // amountBMin, address, // to, uint256, // deadline, bool, // approveMax, uint8, // v, bytes32, // r, bytes32 // s ) external pure override returns (uint256, uint256) { revert(Errors.NOT_IMPLEMENTED); } function removeLiquidityETHWithPermit( address, // token, uint256, // liquidity, uint256, // amountTokenMin, uint256, // amountETHMin, address, // to, uint256, // deadline, bool, // approveMax, uint8, // v, bytes32, // r, bytes32 // s ) external pure override returns (uint256, uint256) { revert(Errors.NOT_IMPLEMENTED); } function swapExactETHForTokens( uint256, // amountOutMin, address[] calldata, // path, address, // to, uint256 // deadline ) external payable override returns (uint256[] memory) { revert(Errors.NOT_IMPLEMENTED); } function swapTokensForExactETH( uint256, // amountOut, uint256, // amountInMax, address[] calldata, // path, address, // to, uint256 // deadline ) external pure override returns (uint256[] memory) { revert(Errors.NOT_IMPLEMENTED); } function swapExactTokensForETH( uint256, // amountIn, uint256, //amountOutMin, address[] calldata, // path, address, // to, uint256 // deadline ) external pure override returns (uint256[] memory) { revert(Errors.NOT_IMPLEMENTED); } function swapETHForExactTokens( uint256, // amountOut, address[] calldata, // path, address, // to, uint256 // deadline ) external payable override returns (uint256[] memory) { revert(Errors.NOT_IMPLEMENTED); } function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external view override returns (uint256 amountB) { return IUniswapV2Router02(router).quote(amountA, reserveA, reserveB); } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external view override returns (uint256 amountOut) { return IUniswapV2Router02(router).getAmountOut( amountIn, reserveIn, reserveOut ); } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external view override returns (uint256 amountIn) { return IUniswapV2Router02(router).getAmountIn( amountOut, reserveIn, reserveOut ); } function getAmountsOut(uint256 amountIn, address[] calldata path) external view override returns (uint256[] memory amounts) { return IUniswapV2Router02(router).getAmountsOut(amountIn, path); } function getAmountsIn(uint256 amountOut, address[] calldata path) external view override returns (uint256[] memory amounts) { return IUniswapV2Router02(router).getAmountsIn(amountOut, path); } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ISwapRouter} from "../integrations/uniswap/IUniswapV3.sol"; import {BytesLib} from "../integrations/uniswap/BytesLib.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {CreditManager} from "../credit/CreditManager.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title UniswapV3 Router adapter contract UniswapV3Adapter is ISwapRouter, ReentrancyGuard { using BytesLib for bytes; using SafeMath for uint256; ICreditManager public creditManager; ICreditFilter public creditFilter; address public router; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev Constructor /// @param _creditManager Address Credit manager /// @param _router Address of ISwapRouter constructor(address _creditManager, address _router) { require( _creditManager != address(0) && _router != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); creditManager = ICreditManager(_creditManager); creditFilter = ICreditFilter(creditManager.creditFilter()); router = _router; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable override nonReentrant returns (uint256 amountOut) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); creditManager.provideCreditAccountAllowance( creditAccount, router, params.tokenIn ); ExactInputSingleParams memory paramsUpdate = params; paramsUpdate.recipient = creditAccount; // 0x414bf389 = exactInputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160)) bytes memory data = abi.encodeWithSelector( bytes4(0x414bf389), // + paramsUpdate ); uint256 balanceInBefore = IERC20(paramsUpdate.tokenIn).balanceOf( creditAccount ); uint256 balanceOutBefore = IERC20(paramsUpdate.tokenOut).balanceOf( creditAccount ); (amountOut) = abi.decode( creditManager.executeOrder(msg.sender, router, data), (uint256) ); creditFilter.checkCollateralChange( creditAccount, params.tokenIn, params.tokenOut, balanceInBefore.sub( IERC20(paramsUpdate.tokenIn).balanceOf(creditAccount) ), IERC20(paramsUpdate.tokenOut).balanceOf(creditAccount).sub( balanceOutBefore ) ); } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable override nonReentrant returns (uint256 amountOut) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); (address tokenIn, address tokenOut) = _extractTokens(params.path); creditManager.provideCreditAccountAllowance( creditAccount, router, tokenIn ); ExactInputParams memory paramsUpdate = params; paramsUpdate.recipient = creditAccount; uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); { // 0xc04b8d59 = exactInput((bytes,address,uint256,uint256,uint256)) bytes memory data = abi.encodeWithSelector( bytes4(0xc04b8d59), // + paramsUpdate ); (amountOut) = abi.decode( creditManager.executeOrder(msg.sender, router, data), (uint256) ); } creditFilter.checkCollateralChange( creditAccount, tokenIn, tokenOut, balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)), IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore) ); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable override nonReentrant returns (uint256 amountIn) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); creditManager.provideCreditAccountAllowance( creditAccount, router, params.tokenIn ); ExactOutputSingleParams memory paramsUpdate = params; paramsUpdate.recipient = creditAccount; // bytes memory data = abi.encodeWithSelector( bytes4(0xdb3e2198), //+ paramsUpdate ); uint256 balanceInBefore = IERC20(paramsUpdate.tokenIn).balanceOf( creditAccount ); uint256 balanceOutBefore = IERC20(paramsUpdate.tokenOut).balanceOf( creditAccount ); (amountIn) = abi.decode( creditManager.executeOrder(msg.sender, router, data), (uint256) ); creditFilter.checkCollateralChange( creditAccount, params.tokenIn, params.tokenOut, balanceInBefore.sub( IERC20(paramsUpdate.tokenIn).balanceOf(creditAccount) ), IERC20(paramsUpdate.tokenOut).balanceOf(creditAccount).sub( balanceOutBefore ) ); } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable override nonReentrant returns (uint256 amountIn) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); (address tokenOut, address tokenIn) = _extractTokens(params.path); creditManager.provideCreditAccountAllowance( creditAccount, router, tokenIn ); ExactOutputParams memory paramsUpdate = params; paramsUpdate.recipient = creditAccount; uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); { bytes memory data = abi.encodeWithSelector( bytes4(0xf28c0498), // exactOutput((bytes,address,uint256,uint256,uint256)) paramsUpdate ); (amountIn) = abi.decode( creditManager.executeOrder(msg.sender, router, data), (uint256) ); } creditFilter.checkCollateralChange( creditAccount, tokenIn, tokenOut, balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)), IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore) ); } function _extractTokens(bytes memory path) internal pure returns (address tokenA, address tokenB) { tokenA = path.toAddress(0); tokenB = path.toAddress(path.length - ADDR_SIZE); } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {IYVault} from "../integrations/yearn/IYVault.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {CreditAccount} from "../credit/CreditAccount.sol"; import {CreditManager} from "../credit/CreditManager.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title Yearn adapter contract YearnAdapter is IYVault, ReentrancyGuard { using SafeMath for uint256; address public yVault; address public override token; ICreditManager public creditManager; ICreditFilter public creditFilter; /// @dev Constructor /// @param _creditManager Address Credit manager /// @param _yVault Address of yVault constructor(address _creditManager, address _yVault) { require( _creditManager != address(0) && _yVault != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); creditManager = ICreditManager(_creditManager); creditFilter = ICreditFilter(creditManager.creditFilter()); yVault = _yVault; // Check that we have token connected with this yearn pool token = IYVault(yVault).token(); creditFilter.revertIfTokenNotAllowed(token); } /// @dev Deposit credit account tokens to Yearn function deposit() external override nonReentrant returns (uint256) { // bytes4(0xd0e30db0) = deposit() return _deposit(abi.encodeWithSelector(bytes4(0xd0e30db0))); // M:[YA-1] } /// @dev Deposit credit account tokens to Yearn /// @param amount in tokens function deposit(uint256 amount) external override nonReentrant returns (uint256) { // bytes4(0xb6b55f25) = deposit return _deposit(abi.encodeWithSelector(bytes4(0xb6b55f25), amount)); // M:[YA-2] } /// @dev Deposit credit account tokens to Yearn /// @param amount in tokens function deposit(uint256 amount, address) external override nonReentrant returns (uint256) { // bytes4(0xb6b55f25) = deposit return _deposit(abi.encodeWithSelector(bytes4(0xb6b55f25), amount)); // M:[YA-2] } function _deposit(bytes memory data) internal returns (uint256 shares) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); // M:[YA-1,2] creditManager.provideCreditAccountAllowance( creditAccount, yVault, token ); // M:[YA-1,2] uint256 balanceInBefore = IERC20(token).balanceOf(creditAccount); // M:[YA-1,2] uint256 balanceOutBefore = IERC20(yVault).balanceOf(creditAccount); // M:[YA-1,2] shares = abi.decode( creditManager.executeOrder(msg.sender, yVault, data), (uint256) ); // M:[YA-1,2] creditFilter.checkCollateralChange( creditAccount, token, yVault, balanceInBefore.sub(IERC20(token).balanceOf(creditAccount)), IERC20(yVault).balanceOf(creditAccount).sub(balanceOutBefore) ); // M:[YA-1,2] } function withdraw() external override nonReentrant returns (uint256) { // bytes4(0x3ccfd60b) = withdraw() return _withdraw(abi.encodeWithSelector(bytes4(0x3ccfd60b))); // M:[YA-3] } function withdraw(uint256 maxShares) external override nonReentrant returns (uint256) { // bytes4(0x2e1a7d4d) = withdraw(uint256) return _withdraw(abi.encodeWithSelector(bytes4(0x2e1a7d4d), maxShares)); } function withdraw(uint256 maxShares, address) external override nonReentrant returns (uint256) { // Call the function with MaxShares only, cause recepient doesn't make sense here // bytes4(0x2e1a7d4d) = withdraw(uint256) return _withdraw(abi.encodeWithSelector(bytes4(0x2e1a7d4d), maxShares)); } /// @dev Withdraw yVaults from credit account /// @param maxShares How many shares to try and redeem for tokens, defaults to all. // @param recipient The address to issue the shares in this Vault to. Defaults to the caller's address. // @param maxLoss The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%. // If a loss is specified, up to that amount of shares may be burnt to cover losses on withdrawal. // @return The quantity of tokens redeemed for `_shares`. function withdraw( uint256 maxShares, address, uint256 maxLoss ) public override nonReentrant returns (uint256 shares) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); // M:[YA-3] return _withdraw( abi.encodeWithSelector( bytes4(0xe63697c8), //"withdraw(uint256,address,uint256)", maxShares, creditAccount, maxLoss ) ); // M:[YA-3]) } function _withdraw(bytes memory data) internal returns (uint256 shares) { address creditAccount = creditManager.getCreditAccountOrRevert( msg.sender ); // M:[YA-3] uint256 balanceInBefore = IERC20(yVault).balanceOf(creditAccount); // M:[YA-3] uint256 balanceOutBefore = IERC20(token).balanceOf(creditAccount); // M:[YA-3] shares = abi.decode( creditManager.executeOrder(msg.sender, yVault, data), (uint256) ); // M:[YA-3] creditFilter.checkCollateralChange( creditAccount, yVault, token, balanceInBefore.sub(IERC20(yVault).balanceOf(creditAccount)), IERC20(token).balanceOf(creditAccount).sub(balanceOutBefore) ); // M:[YA-3] } function pricePerShare() external view override returns (uint256) { return IYVault(yVault).pricePerShare(); } function name() external view override returns (string memory) { return IYVault(yVault).name(); } function symbol() external view override returns (string memory) { return IYVault(yVault).symbol(); } function decimals() external view override returns (uint8) { return IYVault(yVault).decimals(); } function allowance(address owner, address spender) external view override returns (uint256) { return IYVault(yVault).allowance(owner, spender); } function approve(address, uint256) external pure override returns (bool) { return true; } function balanceOf(address account) external view override returns (uint256) { return IYVault(yVault).balanceOf(account); } function totalSupply() external view override returns (uint256) { return IYVault(yVault).totalSupply(); } function transfer(address, uint256) external pure override returns (bool) { revert(Errors.NOT_IMPLEMENTED); } function transferFrom( address, address, uint256 ) external pure override returns (bool) { revert(Errors.NOT_IMPLEMENTED); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title Optimised for front-end Address Provider interface interface IAppAddressProvider { function getDataCompressor() external view returns (address); function getGearToken() external view returns (address); function getWethToken() external view returns (address); function getWETHGateway() external view returns (address); function getPriceOracle() external view returns (address); function getLeveragedActions() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {DataTypes} from "../../libraries/data/Types.sol"; /// @title Optimised for front-end credit Manager interface /// @notice It's optimised for light-weight abi interface IAppCreditManager { function openCreditAccount( uint256 amount, address onBehalfOf, uint256 leverageFactor, uint256 referralCode ) external; function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths) external; function repayCreditAccount(address to) external; function increaseBorrowedAmount(uint256 amount) external; function addCollateral( address onBehalfOf, address token, uint256 amount ) external; function calcRepayAmount(address borrower, bool isLiquidated) external view returns (uint256); function getCreditAccountOrRevert(address borrower) external view returns (address); function hasOpenedCreditAccount(address borrower) external view returns (bool); function defaultSwapContract() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title DataType library /// @notice Contains data types used in data compressor. library DataTypes { struct Exchange { address[] path; uint256 amountOutMin; } struct TokenBalance { address token; uint256 balance; bool isAllowed; } struct ContractAdapter { address allowedContract; address adapter; } struct CreditAccountData { address addr; address borrower; bool inUse; address creditManager; address underlyingToken; uint256 borrowedAmountPlusInterest; uint256 totalValue; uint256 healthFactor; uint256 borrowRate; TokenBalance[] balances; } struct CreditAccountDataExtended { address addr; address borrower; bool inUse; address creditManager; address underlyingToken; uint256 borrowedAmountPlusInterest; uint256 totalValue; uint256 healthFactor; uint256 borrowRate; TokenBalance[] balances; uint256 repayAmount; uint256 liquidationAmount; bool canBeClosed; uint256 borrowedAmount; uint256 cumulativeIndexAtOpen; uint256 since; } struct CreditManagerData { address addr; bool hasAccount; address underlyingToken; bool isWETH; bool canBorrow; uint256 borrowRate; uint256 minAmount; uint256 maxAmount; uint256 maxLeverageFactor; uint256 availableLiquidity; address[] allowedTokens; ContractAdapter[] adapters; } struct PoolData { address addr; bool isWETH; address underlyingToken; address dieselToken; uint256 linearCumulativeIndex; uint256 availableLiquidity; uint256 expectedLiquidity; uint256 expectedLiquidityLimit; uint256 totalBorrowed; uint256 depositAPY_RAY; uint256 borrowAPY_RAY; uint256 dieselRate_RAY; uint256 withdrawFee; uint256 cumulativeIndex_RAY; uint256 timestampLU; } struct TokenInfo { address addr; string symbol; uint8 decimals; } struct AddressProviderData { address contractRegister; address acl; address priceOracle; address traderAccountFactory; address dataCompressor; address farmingFactory; address accountMiner; address treasuryContract; address gearToken; address wethToken; address wethGateway; } struct MiningApproval { address token; address swapContract; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.7.4; import {Errors} from "../helpers/Errors.sol"; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; // T:[PM-1] } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[PM-1] return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; // T:[PM-1] } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[PM-2] uint256 halfPercentage = percentage / 2; // T:[PM-2] require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[PM-2] return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // 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: UNLICENSED pragma solidity ^0.7.4; interface ICurvePool { function coins(uint256) external view returns (address); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {ICreditAccount} from "../interfaces/ICreditAccount.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title Credit Account /// @notice Implements generic credit account logic: /// - Keeps token balances /// - Stores general parameters: borrowed amount, cumulative index at open and block when it was initialized /// - Approves tokens for 3rd party contracts /// - Transfers assets /// - Execute financial orders /// /// More: https://dev.gearbox.fi/developers/credit/credit_account contract CreditAccount is ICreditAccount, Initializable { using SafeERC20 for IERC20; using Address for address; address public override factory; // Keeps address of current credit Manager address public override creditManager; // Amount borrowed to this account uint256 public override borrowedAmount; // Cumulative index at credit account opening uint256 public override cumulativeIndexAtOpen; // Block number when it was initialised last time uint256 public override since; // Contract version uint constant public version = 1; /// @dev Restricts operation for current credit manager only modifier creditManagerOnly { require(msg.sender == creditManager, Errors.CA_CONNECTED_CREDIT_MANAGER_ONLY); _; } /// @dev Initialise used instead of constructor cause we use contract cloning function initialize() external override initializer { factory = msg.sender; } /// @dev Connects credit account to credit account address. Restricted to account factory (owner) only /// @param _creditManager Credit manager address function connectTo( address _creditManager, uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen ) external override { require(msg.sender == factory, Errors.CA_FACTORY_ONLY); creditManager = _creditManager; // T:[CA-7] borrowedAmount = _borrowedAmount; // T:[CA-3,7] cumulativeIndexAtOpen = _cumulativeIndexAtOpen; // T:[CA-3,7] since = block.number; // T:[CA-7] } /// @dev Updates borrowed amount. Restricted for current credit manager only /// @param _borrowedAmount Amount which pool lent to credit account function updateParameters(uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen) external override creditManagerOnly // T:[CA-2] { borrowedAmount = _borrowedAmount; // T:[CA-4] cumulativeIndexAtOpen = _cumulativeIndexAtOpen; } /// @dev Approves token for 3rd party contract. Restricted for current credit manager only /// @param token ERC20 token for allowance /// @param swapContract Swap contract address function approveToken(address token, address swapContract) external override creditManagerOnly // T:[CA-2] { IERC20(token).safeApprove(swapContract, 0); // T:[CA-5] IERC20(token).safeApprove(swapContract, Constants.MAX_INT); // T:[CA-5] } /// @dev Removes allowance token for 3rd party contract. Restricted for factory only /// @param token ERC20 token for allowance /// @param targetContract Swap contract address function cancelAllowance(address token, address targetContract) external override { require(msg.sender == factory, Errors.CA_FACTORY_ONLY); IERC20(token).safeApprove(targetContract, 0); } /// @dev Transfers tokens from credit account to provided address. Restricted for current credit manager only /// @param token Token which should be transferred from credit account /// @param to Address of recipient /// @param amount Amount to be transferred function safeTransfer( address token, address to, uint256 amount ) external override creditManagerOnly // T:[CA-2] { IERC20(token).safeTransfer(to, amount); // T:[CA-6] } /// @dev Executes financial order on 3rd party service. Restricted for current credit manager only /// @param destination Contract address which should be called /// @param data Call data which should be sent function execute(address destination, bytes memory data) external override creditManagerOnly returns (bytes memory) { return destination.functionCall(data); // T: [CM-48] } } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {PercentageMath} from "../libraries/math/PercentageMath.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IAccountFactory} from "../interfaces/IAccountFactory.sol"; import {ICreditAccount} from "../interfaces/ICreditAccount.sol"; import {IPoolService} from "../interfaces/IPoolService.sol"; import {IWETHGateway} from "../interfaces/IWETHGateway.sol"; import {ICreditManager} from "../interfaces/ICreditManager.sol"; import {ICreditFilter} from "../interfaces/ICreditFilter.sol"; import {AddressProvider} from "../core/AddressProvider.sol"; import {ACLTrait} from "../core/ACLTrait.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; import {DataTypes} from "../libraries/data/Types.sol"; /// @title Credit Manager /// @notice It encapsulates business logic for managing credit accounts /// /// More info: https://dev.gearbox.fi/developers/credit/credit_manager /// /// #define roughEq(uint256 a, uint256 b) bool = /// a == b || a + 1 == b || a == b + 1; /// /// #define borrowedPlusInterest(address creditAccount) uint = /// let borrowedAmount, cumIndexAtOpen := getCreditAccountParameters(creditAccount) in /// let curCumulativeIndex := IPoolService(poolService).calcLinearCumulative_RAY() in /// borrowedAmount.mul(curCumulativeIndex).div(cumIndexAtOpen); contract CreditManager is ICreditManager, ACLTrait, ReentrancyGuard { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using Address for address payable; // Minimal amount for open credit account uint256 public override minAmount; // Maximum amount for open credit account uint256 public override maxAmount; // Maximum leveraged factor allowed for this pool uint256 public override maxLeverageFactor; // Minimal allowed Hf after increasing borrow amount uint256 public override minHealthFactor; // Mapping between borrowers'/farmers' address and credit account mapping(address => address) public override creditAccounts; // Account manager - provides credit accounts to pool IAccountFactory internal _accountFactory; // Credit Manager filter ICreditFilter public override creditFilter; // Underlying token address address public override underlyingToken; // Address of connected pool address public override poolService; // Address of WETH token address public wethAddress; // Address of WETH Gateway address public wethGateway; // Default swap contracts - uses for automatic close address public override defaultSwapContract; uint256 public override feeInterest; uint256 public override feeLiquidation; uint256 public override liquidationDiscount; // Contract version uint constant public version = 1; // // MODIFIERS // /// @dev Restricts actions for users with opened credit accounts only modifier allowedAdaptersOnly(address targetContract) { require( creditFilter.contractToAdapter(targetContract) == msg.sender, Errors.CM_TARGET_CONTRACT_iS_NOT_ALLOWED ); _; } /// @dev Constructor /// @param _addressProvider Address Repository for upgradable contract model /// @param _minAmount Minimal amount for open credit account /// @param _maxAmount Maximum amount for open credit account /// @param _maxLeverage Maximum allowed leverage factor /// @param _poolService Address of pool service /// @param _creditFilterAddress CreditFilter address. It should be finalised /// @param _defaultSwapContract Default IUniswapV2Router02 contract to change assets in case of closing account constructor( address _addressProvider, uint256 _minAmount, uint256 _maxAmount, uint256 _maxLeverage, address _poolService, address _creditFilterAddress, address _defaultSwapContract ) ACLTrait(_addressProvider) { require( _addressProvider != address(0) && _poolService != address(0) && _creditFilterAddress != address(0) && _defaultSwapContract != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); AddressProvider addressProvider = AddressProvider(_addressProvider); // T:[CM-1] poolService = _poolService; // T:[CM-1] underlyingToken = IPoolService(_poolService).underlyingToken(); // T:[CM-1] wethAddress = addressProvider.getWethToken(); // T:[CM-1] wethGateway = addressProvider.getWETHGateway(); // T:[CM-1] defaultSwapContract = _defaultSwapContract; // T:[CM-1] _accountFactory = IAccountFactory(addressProvider.getAccountFactory()); // T:[CM-1] _setParams( _minAmount, _maxAmount, _maxLeverage, Constants.FEE_INTEREST, Constants.FEE_LIQUIDATION, Constants.LIQUIDATION_DISCOUNTED_SUM ); // T:[CM-1] creditFilter = ICreditFilter(_creditFilterAddress); // T:[CM-1] } // // CREDIT ACCOUNT MANAGEMENT // /** * @dev Opens credit account and provides credit funds. * - Opens credit account (take it from account factory^1) * - Transfers trader /farmers initial funds to credit account * - Transfers borrowed leveraged amount from pool (= amount x leverageFactor) calling lendCreditAccount() on connected Pool contract. * - Emits OpenCreditAccount event * Function reverts if user has already opened position * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#open-credit-account * * @param amount Borrowers own funds * @param onBehalfOf The address that we open credit account. Same as msg.sender if the user wants to open it for his own wallet, * or a different address if the beneficiary is a different wallet * @param leverageFactor Multiplier to borrowers own funds * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * * #if_succeeds {:msg "A credit account with the correct balance is opened."} * let newAccount := creditAccounts[onBehalfOf] in * newAccount != address(0) && * IERC20(underlyingToken).balanceOf(newAccount) >= * amount.add(amount.mul(leverageFactor).div(Constants.LEVERAGE_DECIMALS)); * * #if_succeeds {:msg "Sender looses amount tokens." } * IERC20(underlyingToken).balanceOf(msg.sender) == old(IERC20(underlyingToken).balanceOf(msg.sender)) - amount; * * #if_succeeds {:msg "Pool provides correct leverage (amount x leverageFactor)." } * IERC20(underlyingToken).balanceOf(poolService) == old(IERC20(underlyingToken).balanceOf(poolService)) - amount.mul(leverageFactor).div(Constants.LEVERAGE_DECIMALS); * * #if_succeeds {:msg "The new account is healthy."} * creditFilter.calcCreditAccountHealthFactor(creditAccounts[onBehalfOf]) >= PercentageMath.PERCENTAGE_FACTOR; * * #if_succeeds {:msg "The new account has balance <= 1 for all tokens other than the underlying token."} * let newAccount := creditAccounts[onBehalfOf] in * forall (uint i in 1...creditFilter.allowedTokensCount()) * IERC20(creditFilter.allowedTokens(i)).balanceOf(newAccount) <= 1; */ function openCreditAccount( uint256 amount, address onBehalfOf, uint256 leverageFactor, uint256 referralCode ) external override whenNotPaused // T:[CM-39] nonReentrant { // Checks that amount is in limits require( amount >= minAmount && amount <= maxAmount && leverageFactor > 0 && leverageFactor <= maxLeverageFactor, Errors.CM_INCORRECT_PARAMS ); // T:[CM-2] // Checks that user "onBehalfOf" has no opened accounts // require( // !hasOpenedCreditAccount(onBehalfOf) && onBehalfOf != address(0), // Errors.CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT // ); // T:[CM-3] _checkAccountTransfer(onBehalfOf); // borrowedAmount = amount * leverageFactor uint256 borrowedAmount = amount.mul(leverageFactor).div( Constants.LEVERAGE_DECIMALS ); // T:[CM-7] // Get Reusable Credit account creditAccount address creditAccount = _accountFactory.takeCreditAccount( borrowedAmount, IPoolService(poolService).calcLinearCumulative_RAY() ); // T:[CM-5] // Initializes enabled tokens for the account. Enabled tokens is a bit mask which // holds information which tokens were used by user creditFilter.initEnabledTokens(creditAccount); // T:[CM-5] // Transfer pool tokens to new credit account IPoolService(poolService).lendCreditAccount( borrowedAmount, creditAccount ); // T:[CM-7] // Transfer borrower own fund to credit account IERC20(underlyingToken).safeTransferFrom( msg.sender, creditAccount, amount ); // T:[CM-6] // link credit account address with borrower address creditAccounts[onBehalfOf] = creditAccount; // T:[CM-5] // emit new event emit OpenCreditAccount( msg.sender, onBehalfOf, creditAccount, amount, borrowedAmount, referralCode ); // T:[CM-8] } /** * @dev Closes credit account * - Swaps all assets to underlying one using default swap protocol * - Pays borrowed amount + interest accrued + fees back to the pool by calling repayCreditAccount * - Transfers remaining funds to the trader / farmer * - Closes the credit account and return it to account factory * - Emits CloseCreditAccount event * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#close-credit-account * * @param to Address to send remaining funds * @param paths Exchange type data which provides paths + amountMinOut * * #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0); * #if_succeeds {:msg "Can only close healthy accounts" } old(creditFilter.calcCreditAccountHealthFactor(creditAccounts[msg.sender])) > PercentageMath.PERCENTAGE_FACTOR; * #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"} * let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[msg.sender])) in * IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool); */ function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(msg.sender); // T: [CM-9, 44] // Converts all assets to underlying one. _convertAllAssetsToUnderlying is virtual _convertAllAssetsToUnderlying(creditAccount, paths); // T: [CM-44] // total value equals underlying assets after converting all assets uint256 totalValue = IERC20(underlyingToken).balanceOf(creditAccount); // T: [CM-44] (, uint256 remainingFunds) = _closeCreditAccountImpl( creditAccount, Constants.OPERATION_CLOSURE, totalValue, msg.sender, address(0), to ); // T: [CM-44] emit CloseCreditAccount(msg.sender, to, remainingFunds); // T: [CM-44] } /** * @dev Liquidates credit account * - Transfers discounted total credit account value from liquidators account * - Pays borrowed funds + interest + fees back to pool, than transfers remaining funds to credit account owner * - Transfer all assets from credit account to liquidator ("to") account * - Returns credit account to factory * - Emits LiquidateCreditAccount event * * More info: https://dev.gearbox.fi/developers/credit/credit_manager#liquidate-credit-account * * @param borrower Borrower address * @param to Address to transfer all assets from credit account * * #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0); * #if_succeeds {:msg "Can only liquidate an un-healthy accounts" } old(creditFilter.calcCreditAccountHealthFactor(creditAccounts[msg.sender])) < PercentageMath.PERCENTAGE_FACTOR; */ function liquidateCreditAccount( address borrower, address to, bool force ) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(borrower); // T: [CM-9] // transfers assets to "to" address and compute total value (tv) & threshold weighted value (twv) (uint256 totalValue, uint256 tvw) = _transferAssetsTo( creditAccount, to, force ); // T:[CM-13, 16, 17] // Checks that current Hf < 1 require( tvw < creditFilter .calcCreditAccountAccruedInterest(creditAccount) .mul(PercentageMath.PERCENTAGE_FACTOR), Errors.CM_CAN_LIQUIDATE_WITH_SUCH_HEALTH_FACTOR ); // T:[CM-13, 16, 17] // Liquidate credit account (, uint256 remainingFunds) = _closeCreditAccountImpl( creditAccount, Constants.OPERATION_LIQUIDATION, totalValue, borrower, msg.sender, to ); // T:[CM-13] emit LiquidateCreditAccount(borrower, msg.sender, remainingFunds); // T:[CM-13] } /// @dev Repays credit account /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#repay-credit-account /// /// @param to Address to send credit account assets /// #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0); /// #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"} /// let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[msg.sender])) in /// IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool); function repayCreditAccount(address to) external override whenNotPaused // T:[CM-39] nonReentrant { _repayCreditAccountImpl(msg.sender, to); // T:[CM-17] } /// @dev Repay credit account with ETH. Restricted to be called by WETH Gateway only /// /// @param borrower Address of borrower /// @param to Address to send credit account assets /// #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"} /// let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[borrower])) in /// IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool); function repayCreditAccountETH(address borrower, address to) external override whenNotPaused // T:[CM-39] nonReentrant returns (uint256) { // Checks that msg.sender is WETH Gateway require(msg.sender == wethGateway, Errors.CM_WETH_GATEWAY_ONLY); // T:[CM-38] // Difference with usual Repay is that there is borrower in repay implementation call return _repayCreditAccountImpl(borrower, to); // T:[WG-11] } /// @dev Implements logic for repay credit accounts /// /// @param borrower Borrower address /// @param to Address to transfer assets from credit account function _repayCreditAccountImpl(address borrower, address to) internal returns (uint256) { address creditAccount = getCreditAccountOrRevert(borrower); (uint256 totalValue, ) = _transferAssetsTo(creditAccount, to, false); // T:[CM-17, 23] (uint256 amountToPool, ) = _closeCreditAccountImpl( creditAccount, Constants.OPERATION_REPAY, totalValue, borrower, borrower, to ); // T:[CM-17] emit RepayCreditAccount(borrower, to); // T:[CM-18] return amountToPool; } /// @dev Implementation for all closing account procedures /// #if_succeeds {:msg "Credit account balances should be <= 1 for all allowed tokens after closing"} /// forall (uint i in 0...creditFilter.allowedTokensCount()) /// IERC20(creditFilter.allowedTokens(i)).balanceOf(creditAccount) <= 1; function _closeCreditAccountImpl( address creditAccount, uint8 operation, uint256 totalValue, address borrower, address liquidator, address to ) internal returns (uint256, uint256) { bool isLiquidated = operation == Constants.OPERATION_LIQUIDATION; ( uint256 borrowedAmount, uint256 amountToPool, uint256 remainingFunds, uint256 profit, uint256 loss ) = _calcClosePayments(creditAccount, totalValue, isLiquidated); // T:[CM-11, 15, 17] if (operation == Constants.OPERATION_CLOSURE) { ICreditAccount(creditAccount).safeTransfer( underlyingToken, poolService, amountToPool ); // T:[CM-11] // close operation with loss is not allowed require(remainingFunds > 0, Errors.CM_CANT_CLOSE_WITH_LOSS); // T:[CM-42] // transfer remaining funds to borrower _safeTokenTransfer( creditAccount, underlyingToken, to, remainingFunds, false ); // T:[CM-11] } // LIQUIDATION else if (operation == Constants.OPERATION_LIQUIDATION) { // repay amount to pool IERC20(underlyingToken).safeTransferFrom( liquidator, poolService, amountToPool ); // T:[CM-14] // transfer remaining funds to borrower if (remainingFunds > 0) { IERC20(underlyingToken).safeTransferFrom( liquidator, borrower, remainingFunds ); //T:[CM-14] } } // REPAY else { // repay amount to pool IERC20(underlyingToken).safeTransferFrom( msg.sender, // msg.sender in case of WETH Gateway poolService, amountToPool ); // T:[CM-17] } // Return creditAccount _accountFactory.returnCreditAccount(creditAccount); // T:[CM-21] // Release memory delete creditAccounts[borrower]; // T:[CM-27] // Transfer pool tokens to new credit account IPoolService(poolService).repayCreditAccount( borrowedAmount, profit, loss ); // T:[CM-11, 15] return (amountToPool, remainingFunds); // T:[CM-11] } /// @dev Collects data and call calc payments pure function during closure procedures /// @param creditAccount Credit account address /// @param totalValue Credit account total value /// @param isLiquidated True if calculations needed for liquidation function _calcClosePayments( address creditAccount, uint256 totalValue, bool isLiquidated ) public view returns ( uint256 _borrowedAmount, uint256 amountToPool, uint256 remainingFunds, uint256 profit, uint256 loss ) { // Gets credit account parameters ( uint256 borrowedAmount, uint256 cumulativeIndexAtCreditAccountOpen_RAY ) = getCreditAccountParameters(creditAccount); // T:[CM-13] return _calcClosePaymentsPure( totalValue, isLiquidated, borrowedAmount, cumulativeIndexAtCreditAccountOpen_RAY, IPoolService(poolService).calcLinearCumulative_RAY() ); } /// @dev Computes all close parameters based on data /// @param totalValue Credit account total value /// @param isLiquidated True if calculations needed for liquidation /// @param borrowedAmount Credit account borrow amount /// @param cumulativeIndexAtCreditAccountOpen_RAY Cumulative index at opening credit account in RAY format /// @param cumulativeIndexNow_RAY Current value of cumulative index in RAY format function _calcClosePaymentsPure( uint256 totalValue, bool isLiquidated, uint256 borrowedAmount, uint256 cumulativeIndexAtCreditAccountOpen_RAY, uint256 cumulativeIndexNow_RAY ) public view returns ( uint256 _borrowedAmount, uint256 amountToPool, uint256 remainingFunds, uint256 profit, uint256 loss ) { uint256 totalFunds = isLiquidated ? totalValue.mul(liquidationDiscount).div( PercentageMath.PERCENTAGE_FACTOR ) : totalValue; // T:[CM-45] _borrowedAmount = borrowedAmount; // T:[CM-45] uint256 borrowedAmountWithInterest = borrowedAmount .mul(cumulativeIndexNow_RAY) .div(cumulativeIndexAtCreditAccountOpen_RAY); // T:[CM-45] if (totalFunds < borrowedAmountWithInterest) { amountToPool = totalFunds.sub(1); // T:[CM-45] loss = borrowedAmountWithInterest.sub(amountToPool); // T:[CM-45] } else { amountToPool = isLiquidated ? totalFunds.percentMul(feeLiquidation).add( borrowedAmountWithInterest ) : borrowedAmountWithInterest.add( borrowedAmountWithInterest.sub(borrowedAmount).percentMul( feeInterest ) ); // T:[CM-45] if (totalFunds > amountToPool) { remainingFunds = totalFunds.sub(amountToPool).sub(1); // T:[CM-45] } else { amountToPool = totalFunds.sub(1); // T:[CM-45] } profit = amountToPool.sub(borrowedAmountWithInterest); // T:[CM-45] } } /// @dev Transfers all assets from borrower credit account to "to" account and converts WETH => ETH if applicable /// @param creditAccount Credit account address /// @param to Address to transfer all assets to function _transferAssetsTo( address creditAccount, address to, bool force ) internal returns (uint256 totalValue, uint256 totalWeightedValue) { uint256 tokenMask; uint256 enabledTokens = creditFilter.enabledTokens(creditAccount); require(to != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED); for (uint256 i = 0; i < creditFilter.allowedTokensCount(); i++) { tokenMask = 1 << i; if (enabledTokens & tokenMask > 0) { ( address token, uint256 amount, uint256 tv, uint256 tvw ) = creditFilter.getCreditAccountTokenById(creditAccount, i); // T:[CM-14, 17, 22, 23] if (amount > 1) { if ( _safeTokenTransfer( creditAccount, token, to, amount.sub(1), // Michael Egorov gas efficiency trick force ) ) { totalValue = totalValue.add(tv); // T:[CM-14, 17, 22, 23] totalWeightedValue = totalWeightedValue.add(tvw); // T:[CM-14, 17, 22, 23] } } } } } /// @dev Transfers token to particular address from credit account and converts WETH => ETH if applicable /// @param creditAccount Address of credit account /// @param token Token address /// @param to Address to transfer asset /// @param amount Amount to be transferred /// @param force If true it will skip reverts of safeTransfer function. Used for force liquidation if there is /// a blocked token on creditAccount /// @return true if transfer were successful otherwise false function _safeTokenTransfer( address creditAccount, address token, address to, uint256 amount, bool force ) internal returns (bool) { if (token != wethAddress) { try ICreditAccount(creditAccount).safeTransfer(token, to, amount) // T:[CM-14, 17] {} catch { require(force, Errors.CM_TRANSFER_FAILED); // T:[CM-50] return false; } } else { ICreditAccount(creditAccount).safeTransfer( token, wethGateway, amount ); // T:[CM-22, 23] IWETHGateway(wethGateway).unwrapWETH(to, amount); // T:[CM-22, 23] } return true; } /// @dev Increases borrowed amount by transferring additional funds from /// the pool if after that HealthFactor > minHealth /// More info: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrowed-amount /// /// @param amount Amount to increase borrowed amount function increaseBorrowedAmount(uint256 amount) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(msg.sender); // T: [CM-9, 30] ( uint256 borrowedAmount, uint256 cumulativeIndexAtOpen ) = getCreditAccountParameters(creditAccount); // T:[CM-30] // uint256 newBorrowedAmount = borrowedAmount.add(amount); uint256 newCumulativeIndex = IPoolService(poolService) .calcCumulativeIndexAtBorrowMore( borrowedAmount, amount, cumulativeIndexAtOpen ); // T:[CM-30] require( newBorrowedAmount.mul(Constants.LEVERAGE_DECIMALS) < maxAmount.mul(maxLeverageFactor), Errors.CM_INCORRECT_AMOUNT ); // T:[CM-51] // // Increase _totalBorrowed, it used to compute forecasted interest IPoolService(poolService).lendCreditAccount(amount, creditAccount); // T:[CM-29] // // Set parameters for new credit account ICreditAccount(creditAccount).updateParameters( newBorrowedAmount, newCumulativeIndex ); // T:[CM-30] // creditFilter.revertIfCantIncreaseBorrowing( creditAccount, minHealthFactor ); // T:[CM-28] emit IncreaseBorrowedAmount(msg.sender, amount); // T:[CM-29] } /// @dev Adds collateral to borrower's credit account /// @param onBehalfOf Address of borrower to add funds /// @param token Token address /// @param amount Amount to add function addCollateral( address onBehalfOf, address token, uint256 amount ) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(onBehalfOf); // T: [CM-9] creditFilter.checkAndEnableToken(creditAccount, token); // T:[CM-48] IERC20(token).safeTransferFrom(msg.sender, creditAccount, amount); // T:[CM-48] emit AddCollateral(onBehalfOf, token, amount); // T: [CM-48] } /// @dev Sets fees. Restricted for configurator role only /// @param _minAmount Minimum amount to open account /// @param _maxAmount Maximum amount to open account /// @param _maxLeverageFactor Maximum leverage factor /// @param _feeInterest Interest fee multiplier /// @param _feeLiquidation Liquidation fee multiplier (for totalValue) /// @param _liquidationDiscount Liquidation premium multiplier (= PERCENTAGE_FACTOR - premium) function setParams( uint256 _minAmount, uint256 _maxAmount, uint256 _maxLeverageFactor, uint256 _feeInterest, uint256 _feeLiquidation, uint256 _liquidationDiscount ) public configuratorOnly // T:[CM-36] { _setParams( _minAmount, _maxAmount, _maxLeverageFactor, _feeInterest, _feeLiquidation, _liquidationDiscount ); } function _setParams( uint256 _minAmount, uint256 _maxAmount, uint256 _maxLeverageFactor, uint256 _feeInterest, uint256 _feeLiquidation, uint256 _liquidationDiscount ) internal { require( _minAmount <= _maxAmount && _maxLeverageFactor > 0, Errors.CM_INCORRECT_PARAMS ); // T:[CM-34] minAmount = _minAmount; // T:[CM-32] maxAmount = _maxAmount; // T:[CM-32] maxLeverageFactor = _maxLeverageFactor; feeInterest = _feeInterest; // T:[CM-37] feeLiquidation = _feeLiquidation; // T:[CM-37] liquidationDiscount = _liquidationDiscount; // T:[CM-37] // Compute minHealthFactor: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrow-amount // LT_U = liquidationDiscount - feeLiquidation minHealthFactor = liquidationDiscount .sub(feeLiquidation) .mul(maxLeverageFactor.add(Constants.LEVERAGE_DECIMALS)) .div(maxLeverageFactor); // T:[CM-41] if (address(creditFilter) != address(0)) { creditFilter.updateUnderlyingTokenLiquidationThreshold(); // T:[CM-49] } emit NewParameters( minAmount, maxAmount, maxLeverageFactor, feeInterest, feeLiquidation, liquidationDiscount ); // T:[CM-37] } /// @dev Approves credit account for 3rd party contract /// @param targetContract Contract to check allowance /// @param token Token address of contract function approve(address targetContract, address token) external override whenNotPaused // T:[CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(msg.sender); // Checks that targetContract is allowed - it has non-zero address adapter require( creditFilter.contractToAdapter(targetContract) != address(0), Errors.CM_TARGET_CONTRACT_iS_NOT_ALLOWED ); creditFilter.revertIfTokenNotAllowed(token); // ToDo: add test _provideCreditAccountAllowance(creditAccount, targetContract, token); } /// @dev Approve tokens for credit accounts. Restricted for adapters only /// @param creditAccount Credit account address /// @param targetContract Contract to check allowance /// @param token Token address of contract function provideCreditAccountAllowance( address creditAccount, address targetContract, address token ) external override allowedAdaptersOnly(targetContract) // T:[CM-46] whenNotPaused // T:[CM-39] nonReentrant { _provideCreditAccountAllowance(creditAccount, targetContract, token); // T:[CM-35] } /// @dev Checks that credit account has enough allowance for operation by comparing existing one with x10 times more than needed /// @param creditAccount Credit account address /// @param toContract Contract to check allowance /// @param token Token address of contract function _provideCreditAccountAllowance( address creditAccount, address toContract, address token ) internal { // Get 10x reserve in allowance if ( IERC20(token).allowance(creditAccount, toContract) < Constants.MAX_INT_4 ) { ICreditAccount(creditAccount).approveToken(token, toContract); // T:[CM-35] } } /// @dev Converts all assets to underlying one using uniswap V2 protocol /// @param creditAccount Credit Account address /// @param paths Exchange type data which provides paths + amountMinOut function _convertAllAssetsToUnderlying( address creditAccount, DataTypes.Exchange[] calldata paths ) internal { uint256 tokenMask; uint256 enabledTokens = creditFilter.enabledTokens(creditAccount); // T: [CM-44] require( paths.length == creditFilter.allowedTokensCount(), Errors.INCORRECT_PATH_LENGTH ); // ToDo: check for (uint256 i = 1; i < paths.length; i++) { tokenMask = 1 << i; if (enabledTokens & tokenMask > 0) { (address tokenAddr, uint256 amount, , ) = creditFilter .getCreditAccountTokenById(creditAccount, i); // T: [CM-44] if (amount > 1) { _provideCreditAccountAllowance( creditAccount, defaultSwapContract, tokenAddr ); // T: [CM-44] address[] memory currentPath = paths[i].path; currentPath[0] = tokenAddr; currentPath[paths[i].path.length - 1] = underlyingToken; bytes memory data = abi.encodeWithSelector( bytes4(0x38ed1739), // "swapExactTokensForTokens(uint256,uint256,address[],address,uint256)", amount.sub(1), paths[i].amountOutMin, // T: [CM-45] currentPath, creditAccount, block.timestamp ); // T: [CM-44] ICreditAccount(creditAccount).execute( defaultSwapContract, data ); // T: [CM-44] } } } } /// @dev Executes filtered order on credit account which is connected with particular borrower /// @param borrower Borrower address /// @param target Target smart-contract /// @param data Call data for call function executeOrder( address borrower, address target, bytes memory data ) external override allowedAdaptersOnly(target) // T:[CM-46] whenNotPaused // T:[CM-39] nonReentrant returns (bytes memory) { address creditAccount = getCreditAccountOrRevert(borrower); // T:[CM-9] emit ExecuteOrder(borrower, target); return ICreditAccount(creditAccount).execute(target, data); // : [CM-47] } // // GETTERS // /// @dev Returns true if the borrower has opened a credit account /// @param borrower Borrower account function hasOpenedCreditAccount(address borrower) public view override returns (bool) { return creditAccounts[borrower] != address(0); // T:[CM-26] } /// @dev Returns address of borrower's credit account and reverts of borrower has no one. /// @param borrower Borrower address function getCreditAccountOrRevert(address borrower) public view override returns (address) { address result = creditAccounts[borrower]; // T: [CM-9] require(result != address(0), Errors.CM_NO_OPEN_ACCOUNT); // T: [CM-9] return result; } /// @dev Calculates repay / liquidation amount /// repay amount = borrow amount + interest accrued + fee amount /// /// More info: https://dev.gearbox.fi/developers/credit/economy#repay /// https://dev.gearbox.fi/developers/credit/economy#liquidate /// @param borrower Borrower address /// @param isLiquidated True if calculated repay amount for liquidator function calcRepayAmount(address borrower, bool isLiquidated) external view override returns (uint256) { address creditAccount = getCreditAccountOrRevert(borrower); uint256 totalValue = creditFilter.calcTotalValue(creditAccount); ( , uint256 amountToPool, uint256 remainingFunds, , ) = _calcClosePayments(creditAccount, totalValue, isLiquidated); // T:[CM-14, 17, 31] return isLiquidated ? amountToPool.add(remainingFunds) : amountToPool; // T:[CM-14, 17, 31] } /// @dev Gets credit account generic parameters /// @param creditAccount Credit account address /// @return borrowedAmount Amount which pool lent to credit account /// @return cumulativeIndexAtOpen Cumulative index at open. Used for interest calculation function getCreditAccountParameters(address creditAccount) internal view returns (uint256 borrowedAmount, uint256 cumulativeIndexAtOpen) { borrowedAmount = ICreditAccount(creditAccount).borrowedAmount(); cumulativeIndexAtOpen = ICreditAccount(creditAccount) .cumulativeIndexAtOpen(); } /// @dev Transfers account ownership to another account /// @param newOwner Address of new owner function transferAccountOwnership(address newOwner) external override whenNotPaused // T: [CM-39] nonReentrant { address creditAccount = getCreditAccountOrRevert(msg.sender); // M:[LA-1,2,3,4,5,6,7,8] // T:[CM-52,53, 54] _checkAccountTransfer(newOwner); delete creditAccounts[msg.sender]; // T:[CM-54], M:[LA-1,2,3,4,5,6,7,8] creditAccounts[newOwner] = creditAccount; // T:[CM-54], M:[LA-1,2,3,4,5,6,7,8] emit TransferAccount(msg.sender, newOwner); // T:[CM-54] } function _checkAccountTransfer(address newOwner) internal view { require( newOwner != address(0) && !hasOpenedCreditAccount(newOwner), Errors.CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT ); // T:[CM-52,53] if (msg.sender != newOwner) { creditFilter.revertIfAccountTransferIsNotAllowed( msg.sender, newOwner ); // T:[54,55] } } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.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 !Address.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 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; 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: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title Reusable Credit Account interface /// @notice Implements general credit account: /// - Keeps token balances /// - Keeps token balances /// - Stores general parameters: borrowed amount, cumulative index at open and block when it was initialized /// - Approves tokens for 3rd party contracts /// - Transfers assets /// - Execute financial orders /// /// More: https://dev.gearbox.fi/developers/creditManager/vanillacreditAccount interface ICreditAccount { /// @dev Initializes clone contract function initialize() external; /// @dev Connects credit account to credit manager /// @param _creditManager Credit manager address function connectTo( address _creditManager, uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen ) external; // /// @dev Set general credit account parameters. Restricted to credit managers only // /// @param _borrowedAmount Amount which pool lent to credit account // /// @param _cumulativeIndexAtOpen Cumulative index at open. Uses for interest calculation // function setGenericParameters( // // ) external; /// @dev Updates borrowed amount. Restricted to credit managers only /// @param _borrowedAmount Amount which pool lent to credit account function updateParameters( uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen ) external; /// @dev Approves particular token for swap contract /// @param token ERC20 token for allowance /// @param swapContract Swap contract address function approveToken(address token, address swapContract) external; /// @dev Cancels allowance for particular contract /// @param token Address of token for allowance /// @param targetContract Address of contract to cancel allowance function cancelAllowance(address token, address targetContract) external; /// Transfers tokens from credit account to provided address. Restricted for pool calls only /// @param token Token which should be tranferred from credit account /// @param to Address of recipient /// @param amount Amount to be transferred function safeTransfer( address token, address to, uint256 amount ) external; /// @dev Returns borrowed amount function borrowedAmount() external view returns (uint256); /// @dev Returns cumulative index at time of opening credit account function cumulativeIndexAtOpen() external view returns (uint256); /// @dev Returns Block number when it was initialised last time function since() external view returns (uint256); /// @dev Address of last connected credit manager function creditManager() external view returns (address); /// @dev Address of last connected credit manager function factory() external view returns (address); /// @dev Executed financial order on 3rd party service. Restricted for pool calls only /// @param destination Contract address which should be called /// @param data Call data which should be sent function execute(address destination, bytes memory data) external returns (bytes memory); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; pragma abicoder v2; import {DataTypes} from "../libraries/data/Types.sol"; interface IAccountFactory { // emits if new account miner was changed event AccountMinerChanged(address indexed miner); // emits each time when creditManager takes credit account event NewCreditAccount(address indexed account); // emits each time when creditManager takes credit account event InitializeCreditAccount( address indexed account, address indexed creditManager ); // emits each time when pool returns credit account event ReturnCreditAccount(address indexed account); // emits each time when DAO takes account from account factory forever event TakeForever(address indexed creditAccount, address indexed to); /// @dev Provide new creditAccount to pool. Creates a new one, if needed /// @return Address of creditAccount function takeCreditAccount( uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen ) external returns (address); /// @dev Takes credit account back and stay in tn the queue /// @param usedAccount Address of used credit account function returnCreditAccount(address usedAccount) external; /// @dev Returns address of next available creditAccount function getNext(address creditAccount) external view returns (address); /// @dev Returns head of list of unused credit accounts function head() external view returns (address); /// @dev Returns tail of list of unused credit accounts function tail() external view returns (address); /// @dev Returns quantity of unused credit accounts in the stock function countCreditAccountsInStock() external view returns (uint256); /// @dev Returns credit account address by its id function creditAccounts(uint256 id) external view returns (address); /// @dev Quantity of credit accounts function countCreditAccounts() external view returns (uint256); // function miningApprovals(uint i) external returns(DataTypes.MiningApproval calldata); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {IAppPoolService} from "./app/IAppPoolService.sol"; /// @title Pool Service Interface /// @notice Implements business logic: /// - Adding/removing pool liquidity /// - Managing diesel tokens & diesel rates /// - Lending/repaying funds to credit Manager /// More: https://dev.gearbox.fi/developers/pool/abstractpoolservice interface IPoolService is IAppPoolService { // Emits each time when LP adds liquidity to the pool event AddLiquidity( address indexed sender, address indexed onBehalfOf, uint256 amount, uint256 referralCode ); // Emits each time when LP removes liquidity to the pool event RemoveLiquidity( address indexed sender, address indexed to, uint256 amount ); // Emits each time when Credit Manager borrows money from pool event Borrow( address indexed creditManager, address indexed creditAccount, uint256 amount ); // Emits each time when Credit Manager repays money from pool event Repay( address indexed creditManager, uint256 borrowedAmount, uint256 profit, uint256 loss ); // Emits each time when Interest Rate model was changed event NewInterestRateModel(address indexed newInterestRateModel); // Emits each time when new credit Manager was connected event NewCreditManagerConnected(address indexed creditManager); // Emits each time when borrow forbidden for credit manager event BorrowForbidden(address indexed creditManager); // Emits each time when uncovered (non insured) loss accrued event UncoveredLoss(address indexed creditManager, uint256 loss); // Emits after expected liquidity limit update event NewExpectedLiquidityLimit(uint256 newLimit); // Emits each time when withdraw fee is udpated event NewWithdrawFee(uint256 fee); // // LIQUIDITY MANAGEMENT // /** * @dev Adds liquidity to pool * - transfers lp tokens to pool * - mint diesel (LP) tokens and provide them * @param amount Amount of tokens to be transfer * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man */ function addLiquidity( uint256 amount, address onBehalfOf, uint256 referralCode ) external override; /** * @dev Removes liquidity from pool * - burns lp's diesel (LP) tokens * - returns underlying tokens to lp * @param amount Amount of tokens to be transfer * @param to Address to transfer liquidity */ function removeLiquidity(uint256 amount, address to) external override returns (uint256); /** * @dev Transfers money from the pool to credit account * and updates the pool parameters * @param borrowedAmount Borrowed amount for credit account * @param creditAccount Credit account address */ function lendCreditAccount(uint256 borrowedAmount, address creditAccount) external; /** * @dev Recalculates total borrowed & borrowRate * mints/burns diesel tokens */ function repayCreditAccount( uint256 borrowedAmount, uint256 profit, uint256 loss ) external; // // GETTERS // /** * @return expected pool liquidity */ function expectedLiquidity() external view returns (uint256); /** * @return expected liquidity limit */ function expectedLiquidityLimit() external view returns (uint256); /** * @dev Gets available liquidity in the pool (pool balance) * @return available pool liquidity */ function availableLiquidity() external view returns (uint256); /** * @dev Calculates interest accrued from the last update using the linear model */ function calcLinearCumulative_RAY() external view returns (uint256); /** * @dev Calculates borrow rate * @return borrow rate in RAY format */ function borrowAPY_RAY() external view returns (uint256); /** * @dev Gets the amount of total borrowed funds * @return Amount of borrowed funds at current time */ function totalBorrowed() external view returns (uint256); /** * @return Current diesel rate **/ function getDieselRate_RAY() external view returns (uint256); /** * @dev Underlying token address getter * @return address of underlying ERC-20 token */ function underlyingToken() external view returns (address); /** * @dev Diesel(LP) token address getter * @return address of diesel(LP) ERC-20 token */ function dieselToken() external view returns (address); /** * @dev Credit Manager address getter * @return address of Credit Manager contract by id */ function creditManagers(uint256 id) external view returns (address); /** * @dev Credit Managers quantity * @return quantity of connected credit Managers */ function creditManagersCount() external view returns (uint256); function creditManagersCanBorrow(address id) external view returns (bool); function toDiesel(uint256 amount) external view returns (uint256); function fromDiesel(uint256 amount) external view returns (uint256); function withdrawFee() external view returns (uint256); function _timestampLU() external view returns (uint256); function _cumulativeIndex_RAY() external view returns (uint256); function calcCumulativeIndexAtBorrowMore( uint256 amount, uint256 dAmount, uint256 cumulativeIndexAtOpen ) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; interface IWETHGateway { /// @dev convert ETH to WETH and add liqudity to pool /// @param pool Address of PoolService contract which where user wants to add liquidity. This pool should has WETH as underlying asset /// @param onBehalfOf The address that will receive the diesel tokens, same as msg.sender if the user wants to receive them on his /// own wallet, or a different address if the beneficiary of diesel tokens is a different wallet /// @param referralCode Code used to register the integrator originating the operation, for potential rewards. /// 0 if the action is executed directly by the user, without any middle-man function addLiquidityETH( address pool, address onBehalfOf, uint16 referralCode ) external payable; /// @dev Removes liquidity from pool and convert WETH to ETH /// - burns lp's diesel (LP) tokens /// - returns underlying tokens to lp /// @param pool Address of PoolService contract which where user wants to withdraw liquidity. This pool should has WETH as underlying asset /// @param amount Amount of tokens to be transfer /// @param to Address to transfer liquidity function removeLiquidityETH( address pool, uint256 amount, address payable to ) external; /// @dev Opens credit account in ETH /// @param creditManager Address of credit Manager. Should used WETH as underlying asset /// @param onBehalfOf The address that we open credit account. Same as msg.sender if the user wants to open it for his own wallet, /// or a different address if the beneficiary is a different wallet /// @param leverageFactor Multiplier to borrowers own funds /// @param referralCode Code used to register the integrator originating the operation, for potential rewards. /// 0 if the action is executed directly by the user, without any middle-man function openCreditAccountETH( address creditManager, address payable onBehalfOf, uint256 leverageFactor, uint256 referralCode ) external payable; /// @dev Repays credit account in ETH /// - transfer borrowed money with interest + fee from borrower account to pool /// - transfer all assets to "to" account /// @param creditManager Address of credit Manager. Should used WETH as underlying asset /// @param to Address to send credit account assets function repayCreditAccountETH(address creditManager, address to) external payable; function addCollateralETH(address creditManager, address onBehalfOf) external payable; /// @dev Unwrap WETH => ETH /// @param to Address to send eth /// @param amount Amount of WETH was transferred function unwrapWETH(address to, uint256 amount) external; } // SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {AddressProvider} from "./AddressProvider.sol"; import {ACL} from "./ACL.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title ACL Trait /// @notice Trait which adds acl functions to contract abstract contract ACLTrait is Pausable { // ACL contract to check rights ACL private _acl; /// @dev constructor /// @param addressProvider Address of address repository constructor(address addressProvider) { require( addressProvider != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED ); _acl = ACL(AddressProvider(addressProvider).getACL()); } /// @dev Reverts if msg.sender is not configurator modifier configuratorOnly() { require( _acl.isConfigurator(msg.sender), Errors.ACL_CALLER_NOT_CONFIGURATOR ); // T:[ACLT-8] _; } ///@dev Pause contract function pause() external { require( _acl.isPausableAdmin(msg.sender), Errors.ACL_CALLER_NOT_PAUSABLE_ADMIN ); // T:[ACLT-1] _pause(); } /// @dev Unpause contract function unpause() external { require( _acl.isUnpausableAdmin(msg.sender), Errors.ACL_CALLER_NOT_PAUSABLE_ADMIN ); // T:[ACLT-1],[ACLT-2] _unpause(); } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title POptimised for front-end Pool Service Interface interface IAppPoolService { function addLiquidity( uint256 amount, address onBehalfOf, uint256 referralCode ) external; function removeLiquidity(uint256 amount, address to) external returns(uint256); } // 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: GPL-2.0-or-later pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external override view returns (address); function WETH() external override view returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external override returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external override payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external override returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external override returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external override returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external override returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external override returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external override returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external override payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external override returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external override returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external override payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external override view returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external override view returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external override view returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external override view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external override view returns (uint[] memory amounts); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external view returns (address); function WETH() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external view returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external view returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { 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, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); 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) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div( mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000 ) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, "toUint24_overflow"); require(_bytes.length >= _start + 3, "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IYVault is IERC20 { function token() external view returns (address); function deposit() external returns (uint256); function deposit(uint256 _amount) external returns (uint256); function deposit(uint256 _amount, address recipient) external returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function withdraw( uint256 maxShares, address recipient, uint256 maxLoss ) external returns (uint256); function pricePerShare() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
Converts all assets to underlying one using uniswap V2 protocol creditAccount Credit Account address paths Exchange type data which provides paths + amountMinOut
function _convertAllAssetsToUnderlying( address creditAccount, DataTypes.Exchange[] calldata paths ) internal { uint256 tokenMask; require( paths.length == creditFilter.allowedTokensCount(), Errors.INCORRECT_PATH_LENGTH for (uint256 i = 1; i < paths.length; i++) { tokenMask = 1 << i; if (enabledTokens & tokenMask > 0) { (address tokenAddr, uint256 amount, , ) = creditFilter if (amount > 1) { _provideCreditAccountAllowance( creditAccount, defaultSwapContract, tokenAddr address[] memory currentPath = paths[i].path; currentPath[0] = tokenAddr; currentPath[paths[i].path.length - 1] = underlyingToken; bytes memory data = abi.encodeWithSelector( amount.sub(1), currentPath, creditAccount, block.timestamp ICreditAccount(creditAccount).execute( defaultSwapContract, data } } } }
13,890,574
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IERC20Permit.sol"; import "./lib/SafeERC20.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title Payments * @dev Contract for streaming token payments for set periods of time w/ optional cliffs + ability to stop payments * @dev This contract DOES NOT include support for deflationary token payments */ contract Payments is ReentrancyGuard { using SafeERC20 for IERC20; /// @notice Payment definition struct Payment { address token; address receiver; address payer; uint48 startTime; uint48 stopTime; uint16 cliffDurationInDays; uint256 paymentDurationInSecs; uint256 amount; uint256 amountClaimed; } /// @notice Payment balance definition struct PaymentBalance { uint256 id; uint256 claimableAmount; Payment payment; } /// @notice Token balance definition struct TokenBalance { uint256 totalAmount; uint256 claimableAmount; uint256 claimedAmount; } /// @dev Used to translate payment periods specified in days to seconds uint256 constant internal SECONDS_PER_DAY = 86400; /// @notice Mapping of payment id > token payments mapping (uint256 => Payment) public tokenPayments; /// @notice Mapping of address to payment id mapping (address => uint256[]) public paymentIds; /// @notice Number of payments uint256 public numPayments; /// @notice Event emitted when a new payment is created event PaymentCreated(address indexed token, address indexed payer, address indexed receiver, uint256 paymentId, uint256 amount, uint48 startTime, uint256 durationInSecs, uint16 cliffInDays); /// @notice Event emitted when tokens are claimed by a receiver from an available balance event TokensClaimed(address indexed receiver, address indexed token, uint256 indexed paymentId, uint256 amountClaimed); /// @notice Event emitted when payment stopped event PaymentStopped(uint256 indexed paymentId, uint256 indexed originalDuration, uint48 stopTime, uint48 startTime); /** * @notice Create payment * @param token Address of token for payment * @param receiver The account that will receive tokens * @param startTime The unix timestamp when the payment period will start * @param amount The amount of tokens being paid * @param paymentDurationInSecs The payment period in seconds * @param cliffDurationInDays The cliff duration in days */ function createPayment( address token, address receiver, uint48 startTime, uint256 amount, uint256 paymentDurationInSecs, uint16 cliffDurationInDays ) external nonReentrant { _validatePayment(paymentDurationInSecs, cliffDurationInDays, amount); _createPayment(token, receiver, startTime, amount, paymentDurationInSecs, cliffDurationInDays); } /** * @notice Create payment, using permit for approval * @dev It is up to the frontend developer to ensure the token implements permit - otherwise this will fail * @param token Address of token for payment * @param receiver The account that will receive tokens * @param startTime The unix timestamp when the payment period will start * @param amount The amount of tokens being paid * @param paymentDurationInSecs The payment period in seconds * @param cliffDurationInDays The payment cliff duration in days * @param deadline 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 createPaymentWithPermit( address token, address receiver, uint48 startTime, uint256 amount, uint256 paymentDurationInSecs, uint16 cliffDurationInDays, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { _validatePayment(paymentDurationInSecs, cliffDurationInDays, amount); _permit(token, amount, deadline, v, r, s); _createPayment(token, receiver, startTime, amount, paymentDurationInSecs, cliffDurationInDays); } /** * @notice Create multiple payments * @param tokens Address of tokens for payments * @param receivers The accounts that will receive tokens * @param startTimes The unix timestamp when the payment periods will start * @param amounts The amounts of tokens being paid * @param paymentDurationsInSecs The payment periods in seconds * @param cliffDurationsInDays The cliff durations in days */ function createPayments( address[] memory tokens, address[] memory receivers, uint48[] memory startTimes, uint256[] memory amounts, uint256[] memory paymentDurationsInSecs, uint16[] memory cliffDurationsInDays ) external nonReentrant { require( tokens.length == receivers.length && receivers.length == startTimes.length && startTimes.length == amounts.length && amounts.length == paymentDurationsInSecs.length && paymentDurationsInSecs.length == cliffDurationsInDays.length, "Payments::createPayments: arrays must be same length" ); for (uint256 i; i < tokens.length; i++) { _validatePayment(paymentDurationsInSecs[i], cliffDurationsInDays[i], amounts[i]); _createPayment( tokens[i], receivers[i], startTimes[i], amounts[i], paymentDurationsInSecs[i], cliffDurationsInDays[i] ); } } /** * @notice Create multiple payments, using permit for approvals * @param tokens Address of tokens for payments * @param receivers The accounts that will receive tokens * @param startTimes The unix timestamp when the payment periods will start * @param amounts The amounts of tokens being paid * @param paymentDurationsInSecs The payment periods in seconds * @param cliffDurationsInDays The cliff durations in days * @param deadlines The times at which to expire the signatures * @param vs The recovery bytes of the signatures * @param rs Half of the ECDSA signature pairs * @param ss Half of the ECDSA signature pairs */ function createPaymentsWithPermit( address[] memory tokens, address[] memory receivers, uint48[] memory startTimes, uint256[] memory amounts, uint256[] memory paymentDurationsInSecs, uint16[] memory cliffDurationsInDays, uint256[] memory deadlines, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss ) external nonReentrant { require( tokens.length == receivers.length && receivers.length == startTimes.length && startTimes.length == amounts.length && amounts.length == paymentDurationsInSecs.length && paymentDurationsInSecs.length == cliffDurationsInDays.length && cliffDurationsInDays.length == deadlines.length && deadlines.length == vs.length && vs.length == rs.length && rs.length == ss.length, "Payments::createPaymentsWithPermit: arrays must be same length" ); for (uint256 i; i < tokens.length; i++) { _validatePayment(paymentDurationsInSecs[i], cliffDurationsInDays[i], amounts[i]); _permit(tokens[i], amounts[i], deadlines[i], vs[i], rs[i], ss[i]); _createPayment( tokens[i], receivers[i], startTimes[i], amounts[i], paymentDurationsInSecs[i], cliffDurationsInDays[i] ); } } /** * @notice Get all active token payment ids * @return the payment ids */ function allActivePaymentIds() external view returns(uint256[] memory){ uint256 activeCount; // Get number of active payments for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { activeCount++; } } // Create result array of length `activeCount` uint256[] memory result = new uint256[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { result[j] = i; j++; } } return result; } /** * @notice Get all active token payments * @return the payments */ function allActivePayments() external view returns(Payment[] memory){ uint256 activeCount; // Get number of active payments for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { activeCount++; } } // Create result array of length `activeCount` Payment[] memory result = new Payment[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { result[j] = tokenPayments[i]; j++; } } return result; } /** * @notice Get all active token payment balances * @return the active payment balances */ function allActivePaymentBalances() external view returns(PaymentBalance[] memory){ uint256 activeCount; // Get number of active payments for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { activeCount++; } } // Create result array of length `activeCount` PaymentBalance[] memory result = new PaymentBalance[](activeCount); uint256 j; // Populate result array for (uint256 i; i < numPayments; i++) { if(claimableBalance(i) > 0) { result[j] = paymentBalance(i); j++; } } return result; } /** * @notice Get all active token payment ids for receiver * @param receiver The address that has paid balances * @return the active payment ids */ function activePaymentIds(address receiver) external view returns(uint256[] memory){ uint256 activeCount; uint256[] memory receiverPaymentIds = paymentIds[receiver]; // Get number of active payments for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { activeCount++; } } // Create result array of length `activeCount` uint256[] memory result = new uint256[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { result[j] = receiverPaymentIds[i]; j++; } } return result; } /** * @notice Get all token payments for receiver * @param receiver The address that has paid balances * @return the payments */ function allPayments(address receiver) external view returns(Payment[] memory){ uint256[] memory allPaymentIds = paymentIds[receiver]; Payment[] memory result = new Payment[](allPaymentIds.length); for (uint256 i; i < allPaymentIds.length; i++) { result[i] = tokenPayments[allPaymentIds[i]]; } return result; } /** * @notice Get all active token payments for receiver * @param receiver The address that has paid balances * @return the payments */ function activePayments(address receiver) external view returns(Payment[] memory){ uint256 activeCount; uint256[] memory receiverPaymentIds = paymentIds[receiver]; // Get number of active payments for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { activeCount++; } } // Create result array of length `activeCount` Payment[] memory result = new Payment[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { result[j] = tokenPayments[receiverPaymentIds[i]]; j++; } } return result; } /** * @notice Get all active token payment balances for receiver * @param receiver The address that has paid balances * @return the active payment balances */ function activePaymentBalances(address receiver) external view returns(PaymentBalance[] memory){ uint256 activeCount; uint256[] memory receiverPaymentIds = paymentIds[receiver]; // Get number of active payments for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { activeCount++; } } // Create result array of length `activeCount` PaymentBalance[] memory result = new PaymentBalance[](activeCount); uint256 j; // Populate result array for (uint256 i; i < receiverPaymentIds.length; i++) { if(claimableBalance(receiverPaymentIds[i]) > 0) { result[j] = paymentBalance(receiverPaymentIds[i]); j++; } } return result; } /** * @notice Get total token balance * @param token The token to check * @return balance the total active balance of `token` */ function totalTokenBalance(address token) external view returns(TokenBalance memory balance){ for (uint256 i; i < numPayments; i++) { Payment memory tokenPayment = tokenPayments[i]; if(tokenPayment.token == token && tokenPayment.startTime != tokenPayment.stopTime){ balance.totalAmount = balance.totalAmount + tokenPayment.amount; if(block.timestamp > tokenPayment.startTime) { balance.claimedAmount = balance.claimedAmount + tokenPayment.amountClaimed; uint256 elapsedTime = tokenPayment.stopTime > 0 && tokenPayment.stopTime < block.timestamp ? tokenPayment.stopTime - tokenPayment.startTime : block.timestamp - tokenPayment.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if ( elapsedDays >= tokenPayment.cliffDurationInDays ) { if (tokenPayment.stopTime == 0 && elapsedTime >= tokenPayment.paymentDurationInSecs) { balance.claimableAmount = balance.claimableAmount + tokenPayment.amount - tokenPayment.amountClaimed; } else { uint256 paymentAmountPerSec = tokenPayment.amount / tokenPayment.paymentDurationInSecs; uint256 amountAvailable = paymentAmountPerSec * elapsedTime; balance.claimableAmount = balance.claimableAmount + amountAvailable - tokenPayment.amountClaimed; } } } } } } /** * @notice Get token balance of receiver * @param token The token to check * @param receiver The address that has available balances * @return balance the total active balance of `token` for `receiver` */ function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance){ uint256[] memory receiverPaymentIds = paymentIds[receiver]; for (uint256 i; i < receiverPaymentIds.length; i++) { Payment memory receiverPayment = tokenPayments[receiverPaymentIds[i]]; if(receiverPayment.token == token && receiverPayment.startTime != receiverPayment.stopTime){ balance.totalAmount = balance.totalAmount + receiverPayment.amount; if(block.timestamp > receiverPayment.startTime) { balance.claimedAmount = balance.claimedAmount + receiverPayment.amountClaimed; uint256 elapsedTime = receiverPayment.stopTime > 0 && receiverPayment.stopTime < block.timestamp ? receiverPayment.stopTime - receiverPayment.startTime : block.timestamp - receiverPayment.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if ( elapsedDays >= receiverPayment.cliffDurationInDays ) { if (receiverPayment.stopTime == 0 && elapsedTime >= receiverPayment.paymentDurationInSecs) { balance.claimableAmount = balance.claimableAmount + receiverPayment.amount - receiverPayment.amountClaimed; } else { uint256 paymentAmountPerSec = receiverPayment.amount / receiverPayment.paymentDurationInSecs; uint256 amountAvailable = paymentAmountPerSec * elapsedTime; balance.claimableAmount = balance.claimableAmount + amountAvailable - receiverPayment.amountClaimed; } } } } } } /** * @notice Get payment balance for a given payment id * @param paymentId The payment ID * @return balance the payment balance */ function paymentBalance(uint256 paymentId) public view returns (PaymentBalance memory balance) { balance.id = paymentId; balance.claimableAmount = claimableBalance(paymentId); balance.payment = tokenPayments[paymentId]; } /** * @notice Get claimable balance for a given payment id * @dev Returns 0 if cliff duration has not ended, payment cancelled, or payment is in the future * @param paymentId The payment ID * @return The amount that can be claimed */ function claimableBalance(uint256 paymentId) public view returns (uint256) { Payment storage payment = tokenPayments[paymentId]; // For payments created with a future start date or payments stopped before starting, return 0 if (block.timestamp < payment.startTime || payment.startTime == payment.stopTime) { return 0; } uint256 elapsedTime = payment.stopTime > 0 && payment.stopTime < block.timestamp ? payment.stopTime - payment.startTime : block.timestamp - payment.startTime; uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY; if (elapsedDays < payment.cliffDurationInDays) { return 0; } if (payment.stopTime == 0 && elapsedTime >= payment.paymentDurationInSecs) { return payment.amount - payment.amountClaimed; } uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs; uint256 amountAvailable = paymentAmountPerSec * elapsedTime; return amountAvailable - payment.amountClaimed; } /** * @notice Allows receiver to claim all of their available tokens for a set of payments * @dev Errors if no tokens are claimable * @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this * @param payments The payment ids for available token balances */ function claimAllAvailableTokens(uint256[] memory payments) external nonReentrant { for (uint i = 0; i < payments.length; i++) { uint256 claimableAmount = claimableBalance(payments[i]); require(claimableAmount > 0, "Payments::claimAllAvailableTokens: claimableAmount is 0"); _claimTokens(payments[i], claimableAmount); } } /** * @notice Allows receiver to claim a portion of their available tokens for a given payment * @dev Errors if token amounts provided are > claimable amounts * @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this * @param payments The payment ids for available token balances * @param amounts The amount of each available token to claim */ function claimAvailableTokenAmounts(uint256[] memory payments, uint256[] memory amounts) external nonReentrant { require(payments.length == amounts.length, "Payments::claimAvailableTokenAmounts: arrays must be same length"); for (uint i = 0; i < payments.length; i++) { uint256 claimableAmount = claimableBalance(payments[i]); require(claimableAmount >= amounts[i], "Payments::claimAvailableTokenAmounts: claimableAmount < amount"); _claimTokens(payments[i], amounts[i]); } } /** * @notice Allows payer or receiver to stop existing payments for a given paymentId * @param paymentId The payment id for a payment * @param stopTime Timestamp to stop payment, if 0 use current block.timestamp */ function stopPayment(uint256 paymentId, uint48 stopTime) external nonReentrant { Payment storage payment = tokenPayments[paymentId]; require(msg.sender == payment.payer || msg.sender == payment.receiver, "Payments::stopPayment: msg.sender must be payer or receiver"); require(payment.stopTime == 0, "Payments::stopPayment: payment already stopped"); stopTime = stopTime == 0 ? uint48(block.timestamp) : stopTime; require(stopTime < payment.startTime + payment.paymentDurationInSecs, "Payments::stopPayment: stop time > payment duration"); if(stopTime > payment.startTime) { payment.stopTime = stopTime; uint256 newPaymentDuration = stopTime - payment.startTime; uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs; uint256 newPaymentAmount = paymentAmountPerSec * newPaymentDuration; IERC20(payment.token).safeTransfer(payment.payer, payment.amount - newPaymentAmount); emit PaymentStopped(paymentId, payment.paymentDurationInSecs, stopTime, payment.startTime); } else { payment.stopTime = payment.startTime; IERC20(payment.token).safeTransfer(payment.payer, payment.amount); emit PaymentStopped(paymentId, payment.paymentDurationInSecs, payment.startTime, payment.startTime); } } /** * @notice Check that payment has valid terms * @param paymentDurationInSecs The payment period in seconds * @param cliffDurationInDays The cliff duration in days * @param amount The amount of tokens being paid */ function _validatePayment(uint256 paymentDurationInSecs, uint16 cliffDurationInDays, uint256 amount) internal pure { require(paymentDurationInSecs > 0, "Payments::_validatePayment: payment duration must be > 0"); require(paymentDurationInSecs <= 25*365*SECONDS_PER_DAY, "Payments::_validatePayment: payment duration more than 25 years"); require(paymentDurationInSecs >= SECONDS_PER_DAY*cliffDurationInDays, "Payments::_validatePayment: payment duration < cliff"); require(amount > 0, "Payments::_validatePayment: amount not > 0"); } /** * @notice Internal implementation of createPayment * @param receiver The account that will receive tokens * @param startTime The unix timestamp when the payment period will start * @param amount The amount of tokens being paid * @param paymentDurationInSecs The payment period in seconds * @param cliffDurationInDays The cliff duration in days */ function _createPayment( address token, address receiver, uint48 startTime, uint256 amount, uint256 paymentDurationInSecs, uint16 cliffDurationInDays ) internal { // Transfer the tokens under the control of the payment contract IERC20(token).safeTransferFrom(msg.sender, address(this), amount); uint48 paymentStartTime = startTime == 0 ? uint48(block.timestamp) : startTime; // Create payment Payment memory payment = Payment({ token: token, receiver: receiver, payer: msg.sender, startTime: paymentStartTime, stopTime: 0, paymentDurationInSecs: paymentDurationInSecs, cliffDurationInDays: cliffDurationInDays, amount: amount, amountClaimed: 0 }); tokenPayments[numPayments] = payment; paymentIds[receiver].push(numPayments); emit PaymentCreated(token, msg.sender, receiver, numPayments, amount, paymentStartTime, paymentDurationInSecs, cliffDurationInDays); // Increment payment id numPayments++; } /** * @notice Internal implementation of token claims * @param paymentId The payment id for claim * @param claimAmount The amount to claim */ function _claimTokens(uint256 paymentId, uint256 claimAmount) internal { Payment storage payment = tokenPayments[paymentId]; require(msg.sender == payment.receiver, "Payments::_claimTokens: msg.sender != receiver"); // Update claimed amount payment.amountClaimed = payment.amountClaimed + claimAmount; // Release tokens IERC20(payment.token).safeTransfer(payment.receiver, claimAmount); emit TokensClaimed(payment.receiver, payment.token, paymentId, claimAmount); } /** * @notice Permit contract to use tokens * @param token Address of the token to permit * @param amount Amount to permit * @param deadline 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 _permit( address token, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { IERC20Permit(token).permit(msg.sender, address(this), amount, deadline, v, r, s); } } // 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 "./IERC20.sol"; interface IERC20Permit is IERC20 { function getDomainSeparator() external view returns (bytes32); function DOMAIN_TYPEHASH() external view returns (bytes32); function VERSION_HASH() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function nonces(address) external view returns (uint); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // 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); } 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); } } } } // SPDX-License-Identifier: MIT 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 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.8.0; import "../interfaces/IERC20.sol"; import "./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"); } } }
Allows payer or receiver to stop existing payments for a given paymentId paymentId The payment id for a payment stopTime Timestamp to stop payment, if 0 use current block.timestamp/
function stopPayment(uint256 paymentId, uint48 stopTime) external nonReentrant { Payment storage payment = tokenPayments[paymentId]; require(msg.sender == payment.payer || msg.sender == payment.receiver, "Payments::stopPayment: msg.sender must be payer or receiver"); require(payment.stopTime == 0, "Payments::stopPayment: payment already stopped"); stopTime = stopTime == 0 ? uint48(block.timestamp) : stopTime; require(stopTime < payment.startTime + payment.paymentDurationInSecs, "Payments::stopPayment: stop time > payment duration"); if(stopTime > payment.startTime) { payment.stopTime = stopTime; uint256 newPaymentDuration = stopTime - payment.startTime; uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs; uint256 newPaymentAmount = paymentAmountPerSec * newPaymentDuration; IERC20(payment.token).safeTransfer(payment.payer, payment.amount - newPaymentAmount); emit PaymentStopped(paymentId, payment.paymentDurationInSecs, stopTime, payment.startTime); payment.stopTime = payment.startTime; IERC20(payment.token).safeTransfer(payment.payer, payment.amount); emit PaymentStopped(paymentId, payment.paymentDurationInSecs, payment.startTime, payment.startTime); } }
10,037,534
./full_match/43114/0xC25148cB2a1CE39d121003f26422E724bD46782C/sources/contracts/Tranche.sol
View accrued yield in a tranche
function viewYield(uint256 trancheId, address currency) public view virtual override returns (uint256) { address holdingStrategy = _holdingStrategies[trancheId]; return IStrategy(holdingStrategy).viewYield(trancheId, currency); }
4,635,090
//SPDX-License-Identifier: MIT pragma solidity >=0.6; pragma experimental ABIEncoderV2; interface cERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 mintAmount) external returns (uint256); function redeem(uint256 cTokenAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function balanceOf(address addr) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function transferFrom(address from, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transferAndCall( address, uint256, bytes calldata ) external returns (bool); } interface Staking { struct Staker { // The staked DAI amount uint256 stakedDAI; // The latest block number which the // staker has staked tokens uint256 lastStake; } function stakeDAI(uint256 amount) external; function withdrawStake() external; function stakers(address staker) external view returns (Staker memory); } interface Uniswap { function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function WETH() external pure returns (address); } interface Reserve { function buy( address _buyWith, uint256 _tokenAmount, uint256 _minReturn ) external returns (uint256); function sell( address _sellWith, uint256 _tokenAmount, uint256 _minReturn ) external returns (uint256); } interface AmbBridge { function relayTokens( address token, address receiver, uint256 amount ) external; } //SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../Interfaces.sol"; contract TradeGD is OwnableUpgradeable { Uniswap public uniswap; cERC20 public GD; cERC20 public DAI; cERC20 public cDAI; Reserve public reserve; address public gdBridge; address public omniBridge; event GDTraded( string protocol, string action, address from, uint256 value, uint256[] uniswap, uint256 gd ); /** * @dev initialize the upgradable contract * @param _gd address of the GoodDollar token * @param _dai address of the DAI token * @param _cdai address of the cDAI token * @param _reserve address of the GoodDollar reserve */ function initialize( address _gd, address _dai, address _cdai, address _reserve ) public initializer { OwnableUpgradeable.__Ownable_init(); uniswap = Uniswap(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)); GD = cERC20(_gd); DAI = cERC20(_dai); cDAI = cERC20(_cdai); reserve = Reserve(_reserve); gdBridge = address(0xD5D11eE582c8931F336fbcd135e98CEE4DB8CCB0); omniBridge = address(0xf301d525da003e874DF574BCdd309a6BF0535bb6); GD.approve( address(uniswap), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); DAI.approve( address(cDAI), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); GD.approve( address(reserve), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); cDAI.approve( address(reserve), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); DAI.approve( omniBridge, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); } function setContract(string memory name, address newaddress) public onlyOwner { bytes32 nameHash = keccak256(bytes(name)); if (nameHash == keccak256(bytes("GD"))) { GD = cERC20(newaddress); GD.approve( address(uniswap), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); GD.approve( address(reserve), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); } else if (nameHash == keccak256(bytes("uniswap"))) { uniswap = Uniswap(newaddress); } else if (nameHash == "reserve") { reserve = Reserve(newaddress); GD.approve( address(reserve), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); cDAI.approve( address(reserve), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); } else if (nameHash == keccak256(bytes("gdBridge"))) { gdBridge = newaddress; } else if (nameHash == keccak256(bytes("omniBridge"))) { omniBridge = newaddress; DAI.approve( omniBridge, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); } } /** * @dev buy GD from reserve using ETH since reserve is in cDAI * we first buy DAI from uniswap -> mint cDAI -> buy GD * @param _minDAIAmount - the min amount of DAI to receive for buying with ETH * @param _minGDAmount - the min amount of GD to receive for buying with cDAI(via DAI) * @param _bridgeTo - if non 0 will bridge result tokens to _bridgeTo address on Fuse */ function buyGDFromReserve( uint256 _minDAIAmount, uint256 _minGDAmount, address _bridgeTo ) external payable returns (uint256) { uint256 gd = _buyGDFromReserve(_minDAIAmount, _minGDAmount); transferWithFee(GD, gd, _bridgeTo); return gd; } function transferWithFee( cERC20 _token, uint256 _amount, address _bridgeTo ) internal { uint256 amountAfterFee = deductFee(_amount); if (_bridgeTo == address(0)) { _token.transfer(msg.sender, amountAfterFee); } else if (_token == GD) { _token.transferAndCall( gdBridge, amountAfterFee, abi.encodePacked(_bridgeTo) ); } else { AmbBridge(omniBridge).relayTokens( address(_token), _bridgeTo, amountAfterFee ); } } function deductFee(uint256 _amount) public pure returns (uint256) { return (_amount * 998) / 1000; } /** * @dev buy GD from reserve using DAI since reserve is in cDAI * we first mint cDAI * @param _DAIAmount - the amount of DAI approved to buy G$ with * @param _minGDAmount - the min amount of GD to receive for buying with cDAI(via DAI) * @param _bridgeTo - if non 0 will bridge result tokens to _bridgeTo address on Fuse */ function buyGDFromReserveWithDAI( uint256 _DAIAmount, uint256 _minGDAmount, address _bridgeTo ) public returns (uint256) { uint256 gd = _buyGDFromReserveWithDAI(_DAIAmount, _minGDAmount); transferWithFee(GD, gd, _bridgeTo); return gd; } function _buyGDFromReserveWithDAI(uint256 _DAIAmount, uint256 _minGDAmount) internal returns (uint256) { require(_DAIAmount > 0, "DAI amount should not be 0"); require( DAI.transferFrom(msg.sender, _DAIAmount), "must approve DAI first" ); uint256 cdaiRes = cDAI.mint(_DAIAmount); require(cdaiRes == 0, "cDAI buying failed"); uint256 cdai = cDAI.balanceOf(address(this)); uint256 gd = reserve.buy(address(cDAI), cdai, _minGDAmount); require(gd > 0, "gd buying failed"); emit GDTraded( "reserve", "buy", msg.sender, _DAIAmount, new uint256[](0), gd ); return gd; } /** * @dev sell GD to reserve converting resulting cDAI to DAI * @param _GDAmount - the amount of G$ approved to sell * @param _minCDAIAmount - the min amount of cDAI to receive for selling G$ * @param _bridgeTo - if non 0 will bridge result tokens to _bridgeTo address on Fuse */ function sellGDToReserveForDAI( uint256 _GDAmount, uint256 _minCDAIAmount, address _bridgeTo ) external returns (uint256) { require(_GDAmount > 0, "G$ amount should not be 0"); require( GD.transferFrom(msg.sender, _GDAmount), "must approve G$ first" ); uint256 cdai = reserve.sell(address(cDAI), _GDAmount, _minCDAIAmount); require(cdai > 0, "G$ selling failed"); uint256 daiRedeemed = DAI.balanceOf(address(this)); require(cDAI.redeem(cdai) == 0, "cDAI redeem faiiled"); daiRedeemed = DAI.balanceOf(address(this)) - daiRedeemed; transferWithFee(DAI, daiRedeemed, _bridgeTo); emit GDTraded( "reserve", "sell", msg.sender, cdai, new uint256[](0), _GDAmount ); } function _buyGDFromReserve(uint256 _minDAIAmount, uint256 _minGDAmount) internal returns (uint256) { require(msg.value > 0, "You must send some ETH"); address[] memory path = new address[](2); path[1] = address(DAI); path[0] = uniswap.WETH(); uint256[] memory swap = uniswap.swapExactETHForTokens{value: msg.value}( _minDAIAmount, path, address(this), now ); uint256 dai = swap[1]; require(dai > 0, "DAI buying failed"); uint256 cdaiRes = cDAI.mint(dai); require(cdaiRes == 0, "cDAI buying failed"); uint256 cdai = cDAI.balanceOf(address(this)); uint256 gd = reserve.buy(address(cDAI), cdai, _minGDAmount); // uint256 gd = GD.balanceOf(address(this)); require(gd > 0, "gd buying failed"); emit GDTraded("reserve", "buy", msg.sender, msg.value, swap, gd); return gd; } /** * @dev buy GD from uniswap pool using ETH since pool is in DAI * we first buy DAI from uniswap -> buy GD * @param _minGDAmount - the min amount of GD to receive for buying with DAI(via ETH) * @param _bridgeTo - if non 0 will bridge result tokens to _bridgeTo address on Fuse */ function buyGDFromUniswap(uint256 _minGDAmount, address _bridgeTo) external payable returns (uint256) { require(msg.value > 0, "You must send some ETH"); uint256 value = msg.value; address[] memory path = new address[](3); path[2] = address(GD); path[1] = address(DAI); path[0] = uniswap.WETH(); uint256[] memory swap = uniswap.swapExactETHForTokens{value: value}( _minGDAmount, path, address(this), now ); uint256 gd = swap[2]; require(gd > 0, "gd buying failed"); emit GDTraded("uniswap", "buy", msg.sender, msg.value, swap, gd); transferWithFee(GD, gd, _bridgeTo); return gd; } /** * @dev buy G$ from reserve using ETH and sell to uniswap pool resulting in DAI * @param _minDAIAmount - the min amount of dai to receive for selling eth to uniswap * @param _minGDAmount - the min amount of G$ to receive for buying with cDAI(via ETH) from reserve * @param _minDAIAmountUniswap - the min amount of DAI to receive for selling G$ to uniswap * @param _bridgeTo - if non 0 will bridge result tokens to _bridgeTo address on Fuse */ function sellGDFromReserveToUniswap( uint256 _minDAIAmount, uint256 _minGDAmount, uint256 _minDAIAmountUniswap, address _bridgeTo ) external payable returns (uint256) { uint256 gd = _buyGDFromReserve(_minDAIAmount, _minGDAmount); address[] memory path = new address[](2); path[0] = address(GD); path[1] = address(DAI); uint256[] memory swap = uniswap.swapExactTokensForTokens( gd, _minDAIAmountUniswap, path, address(this), now ); uint256 dai = swap[1]; require(dai > 0, "gd selling failed"); emit GDTraded("uniswap", "sell", msg.sender, msg.value, swap, gd); transferWithFee(DAI, dai, _bridgeTo); return dai; } /** * @dev buy GD from reserve using DAI and sell to uniswap pool resulting in DAI * @param _DAIAmount - the amount of dai approved to buy G$ * @param _minGDAmount - the min amount of GD to receive for buying with cDAI * @param _minDAIAmount - the min amount of DAI to receive for selling G$ on uniswap * @param _bridgeTo - if non 0 will bridge result tokens to _bridgeTo address on Fuse */ function sellGDFromReserveToUniswapWithDAI( uint256 _DAIAmount, uint256 _minGDAmount, uint256 _minDAIAmount, address _bridgeTo ) external payable returns (uint256) { uint256 gd = _buyGDFromReserveWithDAI(_DAIAmount, _minGDAmount); address[] memory path = new address[](2); path[0] = address(GD); path[1] = address(DAI); uint256[] memory swap = uniswap.swapExactTokensForTokens( gd, _minDAIAmount, path, address(this), now ); uint256 dai = swap[1]; require(dai > 0, "gd selling failed"); emit GDTraded("uniswap", "sell", msg.sender, msg.value, swap, gd); transferWithFee(DAI, dai, _bridgeTo); return dai; } function withdraw(address to) public onlyOwner { GD.transfer(to, GD.balanceOf(address(this))); DAI.transfer(to, DAI.balanceOf(address(this))); payable(to).transfer(address(this).balance); } } // 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 // 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; 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; }
buy GD from uniswap pool using ETH since pool is in DAI we first buy DAI from uniswap -> buy GD _minGDAmount - the min amount of GD to receive for buying with DAI(via ETH) _bridgeTo - if non 0 will bridge result tokens to _bridgeTo address on Fuse/
function buyGDFromUniswap(uint256 _minGDAmount, address _bridgeTo) external payable returns (uint256) { require(msg.value > 0, "You must send some ETH"); uint256 value = msg.value; address[] memory path = new address[](3); path[2] = address(GD); path[1] = address(DAI); path[0] = uniswap.WETH(); uint256[] memory swap = _minGDAmount, path, address(this), now ); uint256 gd = swap[2]; require(gd > 0, "gd buying failed"); emit GDTraded("uniswap", "buy", msg.sender, msg.value, swap, gd); transferWithFee(GD, gd, _bridgeTo); return gd; }
13,556,706
./partial_match/1/0xeEFe0487f16082cABef73974aD689D3F55544240/sources/PitchHero.sol
Return the log in base 10, rounded down, of a positive value. Returns 0 if given 0./
function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; }
2,649,785
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TradingAction.sol"; import "./ActionGuards.sol"; import "./nTokenMintAction.sol"; import "./nTokenRedeemAction.sol"; import "../SettleAssetsExternal.sol"; import "../FreeCollateralExternal.sol"; import "../../math/SafeInt256.sol"; import "../../global/StorageLayoutV1.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/AccountContextHandler.sol"; import "../../../interfaces/notional/NotionalCallback.sol"; contract BatchAction is StorageLayoutV1, ActionGuards { using BalanceHandler for BalanceState; using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; using SafeInt256 for int256; /// @notice Executes a batch of balance transfers including minting and redeeming nTokens. /// @param account the account for the action /// @param actions array of balance actions to take, must be sorted by currency id /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange /// @dev auth:msg.sender auth:ERC1155 function batchBalanceAction(address account, BalanceAction[] calldata actions) external payable nonReentrant { require(account == msg.sender || msg.sender == address(this), "Unauthorized"); requireValidAccount(account); // Return any settle amounts here to reduce the number of storage writes to balances AccountContext memory accountContext = _settleAccountIfRequired(account); BalanceState memory balanceState; for (uint256 i = 0; i < actions.length; i++) { BalanceAction calldata action = actions[i]; // msg.value will only be used when currency id == 1, referencing ETH. The requirement // to sort actions by increasing id enforces that msg.value will only be used once. if (i > 0) { require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions"); } // Loads the currencyId into balance state balanceState.loadBalanceState(account, action.currencyId, accountContext); _executeDepositAction( account, balanceState, action.actionType, action.depositActionAmount ); _calculateWithdrawActionAndFinalize( account, accountContext, balanceState, action.withdrawAmountInternalPrecision, action.withdrawEntireCashBalance, action.redeemToUnderlying ); } _finalizeAccountContext(account, accountContext); } /// @notice Executes a batch of balance transfers and trading actions /// @param account the account for the action /// @param actions array of balance actions with trades to take, must be sorted by currency id /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity, /// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued /// @dev auth:msg.sender auth:ERC1155 function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions) external payable nonReentrant { require(account == msg.sender || msg.sender == address(this), "Unauthorized"); requireValidAccount(account); AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions); _finalizeAccountContext(account, accountContext); } /// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This /// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform /// other actions on behalf of the user. /// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract /// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM /// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting /// and will mainly be used for contracts that make migrating assets a better user experience. /// @param account the account that will take all the actions /// @param actions array of balance actions with trades to take, must be sorted by currency id /// @param callbackData arbitrary bytes to be passed backed to the caller in the callback /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity, /// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued /// @dev auth:authorizedCallbackContract function batchBalanceAndTradeActionWithCallback( address account, BalanceActionWithTrades[] calldata actions, bytes calldata callbackData ) external payable { // NOTE: Re-entrancy is allowed for authorized callback functions. require(authorizedCallbackContract[msg.sender], "Unauthorized"); requireValidAccount(account); AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions); accountContext.setAccountContext(account); // Be sure to set the account context before initiating the callback, all stateful updates // have been finalized at this point so we are safe to issue a callback. This callback may // re-enter Notional safely to deposit or take other actions. NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData); if (accountContext.hasDebt != 0x00) { // NOTE: this method may update the account context to turn off the hasDebt flag, this // is ok because the worst case would be causing an extra free collateral check when it // is not required. This check will be entered if the account hasDebt prior to the callback // being triggered above, so it will happen regardless of what the callback function does. FreeCollateralExternal.checkFreeCollateralAndRevert(account); } } function _batchBalanceAndTradeAction( address account, BalanceActionWithTrades[] calldata actions ) internal returns (AccountContext memory) { AccountContext memory accountContext = _settleAccountIfRequired(account); BalanceState memory balanceState; // NOTE: loading the portfolio state must happen after settle account to get the // correct portfolio, it will have changed if the account is settled. PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); for (uint256 i = 0; i < actions.length; i++) { BalanceActionWithTrades calldata action = actions[i]; // msg.value will only be used when currency id == 1, referencing ETH. The requirement // to sort actions by increasing id enforces that msg.value will only be used once. if (i > 0) { require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions"); } // Loads the currencyId into balance state balanceState.loadBalanceState(account, action.currencyId, accountContext); // Does not revert on invalid action types here, they also have no effect. _executeDepositAction( account, balanceState, action.actionType, action.depositActionAmount ); if (action.trades.length > 0) { int256 netCash; if (accountContext.isBitmapEnabled()) { require( accountContext.bitmapCurrencyId == action.currencyId, "Invalid trades for account" ); bool didIncurDebt; (netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, action.trades ); if (didIncurDebt) { accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt; } } else { // NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch // because we want to only write to storage once after all trades are completed (portfolioState, netCash) = TradingAction.executeTradesArrayBatch( account, action.currencyId, portfolioState, action.trades ); } // If the account owes cash after trading, ensure that it has enough if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg()); balanceState.netCashChange = balanceState.netCashChange.add(netCash); } _calculateWithdrawActionAndFinalize( account, accountContext, balanceState, action.withdrawAmountInternalPrecision, action.withdrawEntireCashBalance, action.redeemToUnderlying ); } // Update the portfolio state if bitmap is not enabled. If bitmap is already enabled // then all the assets have already been updated in in storage. if (!accountContext.isBitmapEnabled()) { // NOTE: account context is updated in memory inside this method call. accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } // NOTE: free collateral and account context will be set outside of this method call. return accountContext; } /// @dev Executes deposits function _executeDepositAction( address account, BalanceState memory balanceState, DepositActionType depositType, uint256 depositActionAmount_ ) private { int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_); int256 assetInternalAmount; require(depositActionAmount >= 0); if (depositType == DepositActionType.None) { return; } else if ( depositType == DepositActionType.DepositAsset || depositType == DepositActionType.DepositAssetAndMintNToken ) { // NOTE: this deposit will NOT revert on a failed transfer unless there is a // transfer fee. The actual transfer will take effect later in balanceState.finalize assetInternalAmount = balanceState.depositAssetToken( account, depositActionAmount, false // no force transfer ); } else if ( depositType == DepositActionType.DepositUnderlying || depositType == DepositActionType.DepositUnderlyingAndMintNToken ) { // NOTE: this deposit will revert on a failed transfer immediately assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount); } else if (depositType == DepositActionType.ConvertCashToNToken) { // _executeNTokenAction will check if the account has sufficient cash assetInternalAmount = depositActionAmount; } _executeNTokenAction( balanceState, depositType, depositActionAmount, assetInternalAmount ); } /// @dev Executes nToken actions function _executeNTokenAction( BalanceState memory balanceState, DepositActionType depositType, int256 depositActionAmount, int256 assetInternalAmount ) private { // After deposits have occurred, check if we are minting nTokens if ( depositType == DepositActionType.DepositAssetAndMintNToken || depositType == DepositActionType.DepositUnderlyingAndMintNToken || depositType == DepositActionType.ConvertCashToNToken ) { // Will revert if trying to mint ntokens and results in a negative cash balance _checkSufficientCash(balanceState, assetInternalAmount); balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount); // Converts a given amount of cash (denominated in internal precision) into nTokens int256 tokensMinted = nTokenMintAction.nTokenMint( balanceState.currencyId, assetInternalAmount ); balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add( tokensMinted ); } else if (depositType == DepositActionType.RedeemNToken) { require( // prettier-ignore balanceState .storedNTokenBalance .add(balanceState.netNTokenTransfer) // transfers would not occur at this point .add(balanceState.netNTokenSupplyChange) >= depositActionAmount, "Insufficient token balance" ); balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub( depositActionAmount ); int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch( balanceState.currencyId, depositActionAmount ); balanceState.netCashChange = balanceState.netCashChange.add(assetCash); } } /// @dev Calculations any withdraws and finalizes balances function _calculateWithdrawActionAndFinalize( address account, AccountContext memory accountContext, BalanceState memory balanceState, uint256 withdrawAmountInternalPrecision, bool withdrawEntireCashBalance, bool redeemToUnderlying ) private { int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision); require(withdrawAmount >= 0); // dev: withdraw action overflow // NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input if (withdrawEntireCashBalance) { // This option is here so that accounts do not end up with dust after lending since we generally // cannot calculate exact cash amounts from the liquidity curve. withdrawAmount = balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision); // If the account has a negative cash balance then cannot withdraw if (withdrawAmount < 0) withdrawAmount = 0; } // prettier-ignore balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .sub(withdrawAmount); balanceState.finalize(account, accountContext, redeemToUnderlying); } function _finalizeAccountContext(address account, AccountContext memory accountContext) private { // At this point all balances, market states and portfolio states should be finalized. Just need to check free // collateral if required. accountContext.setAccountContext(account); if (accountContext.hasDebt != 0x00) { FreeCollateralExternal.checkFreeCollateralAndRevert(account); } } /// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance /// to do so. function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision) private pure { // The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision require( amountInternalPrecision >= 0 && balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision, "Insufficient cash" ); } function _settleAccountIfRequired(address account) private returns (AccountContext memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { // Returns a new memory reference to account context return SettleAssetsExternal.settleAccount(account, accountContext); } else { return accountContext; } } /// @notice Get a list of deployed library addresses (sorted by library name) function getLibInfo() external view returns (address, address, address, address, address, address) { return ( address(FreeCollateralExternal), address(MigrateIncentives), address(SettleAssetsExternal), address(TradingAction), address(nTokenMintAction), address(nTokenRedeemAction) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../FreeCollateralExternal.sol"; import "../SettleAssetsExternal.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/portfolio/TransferAssets.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library TradingAction { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; using Market for MarketParameters; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; using SafeInt256 for int256; using SafeMath for uint256; event LendBorrowTrade( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash ); event AddRemoveLiquidity( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash, int256 netLiquidityTokens ); event SettledCashDebt( address indexed settledAccount, uint16 indexed currencyId, address indexed settler, int256 amountToSettleAsset, int256 fCashAmount ); event nTokenResidualPurchase( uint16 indexed currencyId, uint40 indexed maturity, address indexed purchaser, int256 fCashAmountToPurchase, int256 netAssetCashNToken ); /// @dev Used internally to manage stack issues struct TradeContext { int256 cash; int256 fCashAmount; int256 fee; int256 netCash; int256 totalFee; uint256 blockTime; } /// @notice Executes trades for a bitmapped portfolio, cannot be called directly /// @param account account to put fCash assets in /// @param bitmapCurrencyId currency id of the bitmap /// @param nextSettleTime used to calculate the relative positions in the bitmap /// @param trades tightly packed array of trades, schema is defined in global/Types.sol /// @return netCash generated by trading /// @return didIncurDebt if the bitmap had an fCash position go negative function executeTradesBitmapBatch( address account, uint16 bitmapCurrencyId, uint40 nextSettleTime, bytes32[] calldata trades ) external returns (int256, bool) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId); MarketParameters memory market; bool didIncurDebt; TradeContext memory c; c.blockTime = block.timestamp; for (uint256 i = 0; i < trades.length; i++) { uint256 maturity; (maturity, c.cash, c.fCashAmount) = _executeTrade( account, cashGroup, market, trades[i], c.blockTime ); c.fCashAmount = BitmapAssetsHandler.addifCashAsset( account, bitmapCurrencyId, maturity, nextSettleTime, c.fCashAmount ); didIncurDebt = didIncurDebt || (c.fCashAmount < 0); c.netCash = c.netCash.add(c.cash); } return (c.netCash, didIncurDebt); } /// @notice Executes trades for a bitmapped portfolio, cannot be called directly /// @param account account to put fCash assets in /// @param currencyId currency id to trade /// @param portfolioState used to update the positions in the portfolio /// @param trades tightly packed array of trades, schema is defined in global/Types.sol /// @return resulting portfolio state /// @return netCash generated by trading function executeTradesArrayBatch( address account, uint16 currencyId, PortfolioState memory portfolioState, bytes32[] calldata trades ) external returns (PortfolioState memory, int256) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId); MarketParameters memory market; TradeContext memory c; c.blockTime = block.timestamp; for (uint256 i = 0; i < trades.length; i++) { TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i])))); if ( tradeType == TradeActionType.AddLiquidity || tradeType == TradeActionType.RemoveLiquidity ) { revert("Disabled"); /** * Manual adding and removing of liquidity is currently disabled. * * // Liquidity tokens can only be added by array portfolio * c.cash = _executeLiquidityTrade( * account, * cashGroup, * market, * tradeType, * trades[i], * portfolioState, * c.netCash * ); */ } else { uint256 maturity; (maturity, c.cash, c.fCashAmount) = _executeTrade( account, cashGroup, market, trades[i], c.blockTime ); portfolioState.addAsset( currencyId, maturity, Constants.FCASH_ASSET_TYPE, c.fCashAmount ); } c.netCash = c.netCash.add(c.cash); } return (portfolioState, c.netCash); } /// @notice Executes a non-liquidity token trade /// @param account the initiator of the trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param trade bytes32 encoding of the particular trade /// @param blockTime the current block time /// @return maturity of the asset that was traded /// @return cashAmount - a positive or negative cash amount accrued to the account /// @return fCashAmount - a positive or negative fCash amount accrued to the account function _executeTrade( address account, CashGroupParameters memory cashGroup, MarketParameters memory market, bytes32 trade, uint256 blockTime ) private returns ( uint256 maturity, int256 cashAmount, int256 fCashAmount ) { TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade)))); if (tradeType == TradeActionType.PurchaseNTokenResidual) { (maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual( account, cashGroup, blockTime, trade ); } else if (tradeType == TradeActionType.SettleCashDebt) { (maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade); } else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) { (cashAmount, fCashAmount) = _executeLendBorrowTrade( cashGroup, market, tradeType, blockTime, trade ); // This is a little ugly but required to deal with stack issues. We know the market is loaded // with the proper maturity inside _executeLendBorrowTrade maturity = market.maturity; emit LendBorrowTrade( account, uint16(cashGroup.currencyId), uint40(maturity), cashAmount, fCashAmount ); } else { revert("Invalid trade type"); } } /// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold /// liquidity tokens. /// @param account the initiator of the trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param tradeType whether this is add or remove liquidity /// @param trade bytes32 encoding of the particular trade /// @param portfolioState the current account's portfolio state /// @param netCash the current net cash accrued in this batch of trades, can be // used for adding liquidity /// @return cashAmount: a positive or negative cash amount accrued to the account function _executeLiquidityTrade( address account, CashGroupParameters memory cashGroup, MarketParameters memory market, TradeActionType tradeType, bytes32 trade, PortfolioState memory portfolioState, int256 netCash ) private returns (int256) { uint256 marketIndex = uint8(bytes1(trade << 8)); // NOTE: this loads the market in memory cashGroup.loadMarket(market, marketIndex, true, block.timestamp); int256 cashAmount; int256 fCashAmount; int256 tokens; if (tradeType == TradeActionType.AddLiquidity) { cashAmount = int256((uint256(trade) >> 152) & type(uint88).max); // Setting cash amount to zero will deposit all net cash accumulated in this trade into // liquidity. This feature allows accounts to borrow in one maturity to provide liquidity // in another in a single transaction without dust. It also allows liquidity providers to // sell off the net cash residuals and use the cash amount in the new market without dust if (cashAmount == 0) cashAmount = netCash; // Add liquidity will check cash amount is positive (tokens, fCashAmount) = market.addLiquidity(cashAmount); cashAmount = cashAmount.neg(); // Report a negative cash amount in the event } else { tokens = int256((uint256(trade) >> 152) & type(uint88).max); (cashAmount, fCashAmount) = market.removeLiquidity(tokens); tokens = tokens.neg(); // Report a negative amount tokens in the event } { uint256 minImpliedRate = uint32(uint256(trade) >> 120); uint256 maxImpliedRate = uint32(uint256(trade) >> 88); // If minImpliedRate is not set then it will be zero require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage"); if (maxImpliedRate != 0) require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage"); } // Add the assets in this order so they are sorted portfolioState.addAsset( cashGroup.currencyId, market.maturity, Constants.FCASH_ASSET_TYPE, fCashAmount ); // Adds the liquidity token asset portfolioState.addAsset( cashGroup.currencyId, market.maturity, marketIndex + 1, tokens ); emit AddRemoveLiquidity( account, cashGroup.currencyId, // This will not overflow for a long time uint40(market.maturity), cashAmount, fCashAmount, tokens ); return cashAmount; } /// @notice Executes a lend or borrow trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param tradeType whether this is add or remove liquidity /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return cashAmount - a positive or negative cash amount accrued to the account /// @return fCashAmount - a positive or negative fCash amount accrued to the account function _executeLendBorrowTrade( CashGroupParameters memory cashGroup, MarketParameters memory market, TradeActionType tradeType, uint256 blockTime, bytes32 trade ) private returns ( int256 cashAmount, int256 fCashAmount ) { uint256 marketIndex = uint256(uint8(bytes1(trade << 8))); // NOTE: this updates the market in memory cashGroup.loadMarket(market, marketIndex, false, blockTime); fCashAmount = int256(uint88(bytes11(trade << 16))); // fCash to account will be negative here if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg(); cashAmount = market.executeTrade( cashGroup, fCashAmount, market.maturity.sub(blockTime), marketIndex ); require(cashAmount != 0, "Trade failed, liquidity"); uint256 rateLimit = uint256(uint32(bytes4(trade << 104))); if (rateLimit != 0) { if (tradeType == TradeActionType.Borrow) { // Do not allow borrows over the rate limit require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage"); } else { // Do not allow lends under the rate limit require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage"); } } } /// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty /// rate to the 3 month market. /// @param account the account initiating the trade, used to check that self settlement is not possible /// @param cashGroup parameters for the trade /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return maturity: the date of the three month maturity where fCash will be exchanged /// @return cashAmount: a negative cash amount that the account must pay to the settled account /// @return fCashAmount: a positive fCash amount that the account will receive function _settleCashDebt( address account, CashGroupParameters memory cashGroup, uint256 blockTime, bytes32 trade ) internal returns ( uint256, int256, int256 ) { address counterparty = address(uint256(trade) >> 88); // Allowing an account to settle itself would result in strange outcomes require(account != counterparty, "Cannot settle self"); int256 amountToSettleAsset = int256(uint88(uint256(trade))); AccountContext memory counterpartyContext = AccountContextHandler.getAccountContext(counterparty); if (counterpartyContext.mustSettleAssets()) { counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext); } // This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive // number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the // max amount to settle. This will update the balance storage on the counterparty. amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt( counterparty, cashGroup, amountToSettleAsset, counterpartyContext ); // Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market // is not initialized. uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; int256 fCashAmount = _getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset); // Defensive check to ensure that we can't inadvertently cause the settler to lose fCash. require(fCashAmount >= 0); // It's possible that this action will put an account into negative free collateral. In this case they // will immediately become eligible for liquidation and the account settling the debt can also liquidate // them in the same transaction. Do not run a free collateral check here to allow this to happen. { PortfolioAsset[] memory assets = new PortfolioAsset[](1); assets[0].currencyId = cashGroup.currencyId; assets[0].maturity = threeMonthMaturity; assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur assets[0].assetType = Constants.FCASH_ASSET_TYPE; // Can transfer assets, we have settled above counterpartyContext = TransferAssets.placeAssetsInAccount( counterparty, counterpartyContext, assets ); } counterpartyContext.setAccountContext(counterparty); emit SettledCashDebt( counterparty, uint16(cashGroup.currencyId), account, amountToSettleAsset, fCashAmount.neg() ); return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount); } /// @dev Helper method to calculate the fCashAmount from the penalty settlement rate function _getfCashSettleAmount( CashGroupParameters memory cashGroup, uint256 threeMonthMaturity, uint256 blockTime, int256 amountToSettleAsset ) private view returns (int256) { uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime); int256 exchangeRate = Market.getExchangeRateFromImpliedRate( oracleRate.add(cashGroup.getSettlementPenalty()), threeMonthMaturity.sub(blockTime) ); // Amount to settle is positive, this returns the fCashAmount that the settler will // receive as a positive number return cashGroup.assetRate .convertToUnderlying(amountToSettleAsset) // Exchange rate converts from cash to fCash when multiplying .mulInRatePrecision(exchangeRate); } /// @notice Allows an account to purchase ntoken residuals /// @param purchaser account that is purchasing the residuals /// @param cashGroup parameters for the trade /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged /// @return cashAmount: a positive or negative cash amount that the account will receive or pay /// @return fCashAmount: a positive or negative fCash amount that the account will receive function _purchaseNTokenResidual( address purchaser, CashGroupParameters memory cashGroup, uint256 blockTime, bytes32 trade ) internal returns ( uint256, int256, int256 ) { uint256 maturity = uint256(uint32(uint256(trade) >> 216)); int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128)); require(maturity > blockTime, "Invalid maturity"); // Require that the residual to purchase does not fall on an existing maturity (i.e. // it is an idiosyncratic maturity) require( !DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime), "Non idiosyncratic maturity" ); address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, /* assetArrayLength */, bytes5 parameters ) = nTokenHandler.getNTokenContext(nTokenAddress); // Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage // opportunities are not available (by generating residuals and then immediately purchasing them at a discount) // This is always relative to the last initialized time which is set at utc0 when initialized, not the // reference time. Therefore we will always restrict residual purchase relative to initialization, not reference. // This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization // until the residual time buffer passes. require( blockTime > lastInitializedTime.add( uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours ), "Insufficient block time" ); int256 notional = BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity); // Check if amounts are valid and set them to the max available if necessary if (notional < 0 && fCashAmountToPurchase < 0) { // Does not allow purchasing more negative notional than available if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional; } else if (notional > 0 && fCashAmountToPurchase > 0) { // Does not allow purchasing more positive notional than available if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional; } else { // Does not allow moving notional in the opposite direction revert("Invalid amount"); } // If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return // netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken. int256 netAssetCashNToken = _getResidualPriceAssetCash( cashGroup, maturity, blockTime, fCashAmountToPurchase, parameters ); _updateNTokenPortfolio( nTokenAddress, cashGroup.currencyId, maturity, lastInitializedTime, fCashAmountToPurchase, netAssetCashNToken ); emit nTokenResidualPurchase( uint16(cashGroup.currencyId), uint40(maturity), purchaser, fCashAmountToPurchase, netAssetCashNToken ); return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase); } /// @notice Returns the amount of asset cash required to purchase the nToken residual function _getResidualPriceAssetCash( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime, int256 fCashAmount, bytes6 parameters ) internal view returns (int256) { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); // Residual purchase incentive is specified in ten basis point increments uint256 purchaseIncentive = uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) * Constants.TEN_BASIS_POINTS; if (fCashAmount > 0) { // When fCash is positive then we add the purchase incentive, the purchaser // can pay less cash for the fCash relative to the oracle rate oracleRate = oracleRate.add(purchaseIncentive); } else if (oracleRate > purchaseIncentive) { // When fCash is negative, we reduce the interest rate that the purchaser will // borrow at, we do this check to ensure that we floor the oracle rate at zero. oracleRate = oracleRate.sub(purchaseIncentive); } else { // If the oracle rate is less than the purchase incentive floor the interest rate at zero oracleRate = 0; } int256 exchangeRate = Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime)); // Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount return cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate)); } function _updateNTokenPortfolio( address nTokenAddress, uint256 currencyId, uint256 maturity, uint256 lastInitializedTime, int256 fCashAmountToPurchase, int256 netAssetCashNToken ) private { int256 finalNotional = BitmapAssetsHandler.addifCashAsset( nTokenAddress, currencyId, maturity, lastInitializedTime, fCashAmountToPurchase.neg() // the nToken takes on the negative position ); // Defensive check to ensure that fCash amounts do not flip signs require( (fCashAmountToPurchase > 0 && finalNotional >= 0) || (fCashAmountToPurchase < 0 && finalNotional <= 0) ); // prettier-ignore ( int256 nTokenCashBalance, /* storedNTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId); nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken); // This will ensure that the cash balance is not negative BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/StorageLayoutV1.sol"; import "../../internal/nToken/nTokenHandler.sol"; abstract contract ActionGuards is StorageLayoutV1 { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; function initializeReentrancyGuard() internal { require(reentrancyStatus == 0); // Initialize the guard to a non-zero value, see the OZ reentrancy guard // description for why this is more gas efficient: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol reentrancyStatus = _NOT_ENTERED; } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(reentrancyStatus != _ENTERED, "Reentrant call"); // Any calls to nonReentrant after this point will fail reentrancyStatus = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) reentrancyStatus = _NOT_ENTERED; } // These accounts cannot receive deposits, transfers, fCash or any other // types of value transfers. function requireValidAccount(address account) internal view { require(account != Constants.RESERVE); // Reserve address is address(0) require(account != address(this)); ( uint256 isNToken, /* incentiveAnnualEmissionRate */, /* lastInitializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(account); require(isNToken == 0); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenMintAction { using SafeInt256 for int256; using BalanceHandler for BalanceState; using CashGroup for CashGroupParameters; using Market for MarketParameters; using nTokenHandler for nTokenPortfolio; using PortfolioHandler for PortfolioState; using AssetRate for AssetRateParameters; using SafeMath for uint256; using nTokenHandler for nTokenPortfolio; /// @notice Converts the given amount of cash to nTokens in the same currency. /// @param currencyId the currency associated the nToken /// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals /// @return nTokens minted by this action function nTokenMint(uint16 currencyId, int256 amountToDepositInternal) external returns (int256) { uint256 blockTime = block.timestamp; nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime); require(tokensToMint >= 0, "Invalid token amount"); if (nToken.portfolioState.storedAssets.length == 0) { // If the token does not have any assets, then the markets must be initialized first. nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, currencyId, nToken.cashBalance ); } else { _depositIntoPortfolio(nToken, amountToDepositInternal, blockTime); } // NOTE: token supply does not change here, it will change after incentives have been claimed // during BalanceHandler.finalize return tokensToMint; } /// @notice Calculates the tokens to mint to the account as a ratio of the nToken /// present value denominated in asset cash terms. /// @return the amount of tokens to mint, the ifCash bitmap function calculateTokensToMint( nTokenPortfolio memory nToken, int256 amountToDepositInternal, uint256 blockTime ) internal view returns (int256) { require(amountToDepositInternal >= 0); // dev: deposit amount negative if (amountToDepositInternal == 0) return 0; if (nToken.lastInitializedTime != 0) { // For the sake of simplicity, nTokens cannot be minted if they have assets // that need to be settled. This is only done during market initialization. uint256 nextSettleTime = nToken.getNextSettleTime(); // If next settle time <= blockTime then the token can be settled require(nextSettleTime > blockTime, "Requires settlement"); } int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // Defensive check to ensure PV remains positive require(assetCashPV >= 0); // Allow for the first deposit if (nToken.totalSupply == 0) { return amountToDepositInternal; } else { // assetCashPVPost = assetCashPV + amountToDeposit // (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV // (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV // (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV // tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV); } } /// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When /// entering this method we know that assetCashDeposit is positive and the nToken has been /// initialized to have liquidity tokens. function _depositIntoPortfolio( nTokenPortfolio memory nToken, int256 assetCashDeposit, uint256 blockTime ) private { (int256[] memory depositShares, int256[] memory leverageThresholds) = nTokenHandler.getDepositParameters( nToken.cashGroup.currencyId, nToken.cashGroup.maxMarketIndex ); // Loop backwards from the last market to the first market, the reasoning is a little complicated: // If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient // to calculate the cash amount to lend. We do know that longer term maturities will have more // slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get // closer to the current block time. Any residual cash from lending will be rolled into shorter // markets as this loop progresses. int256 residualCash; MarketParameters memory market; for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) { int256 fCashAmount; // Loads values into the market memory slot nToken.cashGroup.loadMarket( market, marketIndex, true, // Needs liquidity to true blockTime ); // If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex // before initializing if (market.totalLiquidity == 0) continue; // Checked that assetCashDeposit must be positive before entering int256 perMarketDeposit = assetCashDeposit .mul(depositShares[marketIndex - 1]) .div(Constants.DEPOSIT_PERCENT_BASIS) .add(residualCash); (fCashAmount, residualCash) = _lendOrAddLiquidity( nToken, market, perMarketDeposit, leverageThresholds[marketIndex - 1], marketIndex, blockTime ); if (fCashAmount != 0) { BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, nToken.cashGroup.currencyId, market.maturity, nToken.lastInitializedTime, fCashAmount ); } } // nToken is allowed to store assets directly without updating account context. nToken.portfolioState.storeAssets(nToken.tokenAddress); // Defensive check to ensure that we do not somehow accrue negative residual cash. require(residualCash >= 0, "Negative residual cash"); // This will occur if the three month market is over levered and we cannot lend into it if (residualCash > 0) { // Any remaining residual cash will be put into the nToken balance and added as liquidity on the // next market initialization nToken.cashBalance = nToken.cashBalance.add(residualCash); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } } /// @notice For a given amount of cash to deposit, decides how much to lend or provide /// given the market conditions. function _lendOrAddLiquidity( nTokenPortfolio memory nToken, MarketParameters memory market, int256 perMarketDeposit, int256 leverageThreshold, uint256 marketIndex, uint256 blockTime ) private returns (int256 fCashAmount, int256 residualCash) { // We start off with the entire per market deposit as residuals residualCash = perMarketDeposit; // If the market is over leveraged then we will lend to it instead of providing liquidity if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { (residualCash, fCashAmount) = _deleverageMarket( nToken.cashGroup, market, perMarketDeposit, blockTime, marketIndex ); // Recalculate this after lending into the market, if it is still over leveraged then // we will not add liquidity and just exit. if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { // Returns the residual cash amount return (fCashAmount, residualCash); } } // Add liquidity to the market only if we have successfully delevered. // (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored // If deleveraged, residualCash is what remains // If not deleveraged, residual cash is per market deposit fCashAmount = fCashAmount.add( _addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash) ); // No residual cash if we're adding liquidity return (fCashAmount, 0); } /// @notice Markets are over levered when their proportion is greater than a governance set /// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken /// account for the given amount of cash deposited, putting the nToken account at risk of liquidation. /// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead. function _isMarketOverLeveraged( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 leverageThreshold ) private pure returns (bool) { int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // Comparison we want to do: // (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold // However, the division will introduce rounding errors so we change this to: // totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying) // Leverage threshold is denominated in rate precision. return ( market.totalfCash.mul(Constants.RATE_PRECISION) > leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying)) ); } function _addLiquidityToMarket( nTokenPortfolio memory nToken, MarketParameters memory market, uint256 index, int256 perMarketDeposit ) private returns (int256) { // Add liquidity to the market PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index]; // We expect that all the liquidity tokens are in the portfolio in order. require( asset.maturity == market.maturity && // Ensures that the asset type references the proper liquidity token asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX && // Ensures that the storage state will not be overwritten asset.storageState == AssetStorageState.NoChange, "PT: invalid liquidity token" ); // This will update the market state as well, fCashAmount returned here is negative (int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit); asset.notional = asset.notional.add(liquidityTokens); asset.storageState = AssetStorageState.Update; return fCashAmount; } /// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due /// to slippage or result in some amount of residual cash. function _deleverageMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 perMarketDeposit, uint256 blockTime, uint256 marketIndex ) private returns (int256, int256) { uint256 timeToMaturity = market.maturity.sub(blockTime); // Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this // is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here // because it is very gas inefficient. int256 assumedExchangeRate; if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) { // Floor the exchange rate at zero interest rate assumedExchangeRate = Constants.RATE_PRECISION; } else { assumedExchangeRate = Market.getExchangeRateFromImpliedRate( market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER), timeToMaturity ); } int256 fCashAmount; { int256 perMarketDepositUnderlying = cashGroup.assetRate.convertToUnderlying(perMarketDeposit); // NOTE: cash * exchangeRate = fCash fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate); } int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex); // This means that the trade failed if (netAssetCash == 0) { return (perMarketDeposit, 0); } else { // Ensure that net the per market deposit figure does not drop below zero, this should not be possible // given how we've calculated the exchange rate but extra caution here int256 residual = perMarketDeposit.add(netAssetCash); require(residual >= 0); // dev: insufficient cash return (residual, fCashAmount); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../internal/markets/Market.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/portfolio/TransferAssets.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenRedeemAction { using SafeInt256 for int256; using SafeMath for uint256; using Bitmap for bytes32; using BalanceHandler for BalanceState; using Market for MarketParameters; using CashGroup for CashGroupParameters; using PortfolioHandler for PortfolioState; using nTokenHandler for nTokenPortfolio; /// @notice When redeeming nTokens via the batch they must all be sold to cash and this /// method will return the amount of asset cash sold. /// @param currencyId the currency associated the nToken /// @param tokensToRedeem the amount of nTokens to convert to cash /// @return amount of asset cash to return to the account, denominated in internal token decimals function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem) external returns (int256) { uint256 blockTime = block.timestamp; // prettier-ignore ( int256 totalAssetCash, bool hasResidual, /* PortfolioAssets[] memory newfCashAssets */ ) = _redeem(currencyId, tokensToRedeem, true, false, blockTime); require(!hasResidual, "Cannot redeem via batch, residual"); return totalAssetCash; } /// @notice Redeems nTokens for asset cash and fCash /// @param currencyId the currency associated the nToken /// @param tokensToRedeem the amount of nTokens to convert to cash /// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place /// back into the account's portfolio /// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will /// be no penalty assessed /// @return assetCash positive amount of asset cash to the account /// @return hasResidual true if there are fCash residuals left /// @return assets an array of fCash asset residuals to place into the account function redeem( uint16 currencyId, int256 tokensToRedeem, bool sellTokenAssets, bool acceptResidualAssets ) external returns (int256, bool, PortfolioAsset[] memory) { return _redeem( currencyId, tokensToRedeem, sellTokenAssets, acceptResidualAssets, block.timestamp ); } function _redeem( uint16 currencyId, int256 tokensToRedeem, bool sellTokenAssets, bool acceptResidualAssets, uint256 blockTime ) internal returns (int256, bool, PortfolioAsset[] memory) { require(tokensToRedeem > 0); nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); // nTokens cannot be redeemed during the period of time where they require settlement. require(nToken.getNextSettleTime() > blockTime, "Requires settlement"); require(tokensToRedeem < nToken.totalSupply, "Cannot redeem"); PortfolioAsset[] memory newifCashAssets; // Get the ifCash bits that are idiosyncratic bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits( nToken.tokenAddress, currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); if (ifCashBits != 0 && acceptResidualAssets) { // This will remove all the ifCash assets proportionally from the account newifCashAssets = _reduceifCashAssetsProportional( nToken.tokenAddress, currencyId, nToken.lastInitializedTime, tokensToRedeem, nToken.totalSupply, ifCashBits ); // Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw // simply gets the proportional amount of liquidity tokens to remove ifCashBits = 0; } // Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only // set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens (int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw( nToken, tokensToRedeem, blockTime, ifCashBits ); // Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated // in memory if required and will contain the fCash to be sold or returned to the portfolio int256 totalAssetCash = _reduceLiquidAssets( nToken, tokensToRedeem, tokensToWithdraw, netfCash, ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts blockTime ); bool netfCashRemaining = true; if (sellTokenAssets) { int256 assetCash; // NOTE: netfCash is modified in place and set to zero if the fCash is sold (assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime); totalAssetCash = totalAssetCash.add(assetCash); } if (netfCashRemaining) { // If the account is unwilling to accept residuals then will fail here. require(acceptResidualAssets, "Residuals"); newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash); } return (totalAssetCash, netfCashRemaining, newifCashAssets); } /// @notice Removes liquidity tokens and cash from the nToken /// @param nToken portfolio object /// @param nTokensToRedeem tokens to redeem /// @param tokensToWithdraw array of liquidity tokens to withdraw /// @param netfCash array of netfCash figures /// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step /// @param blockTime current block time /// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken function _reduceLiquidAssets( nTokenPortfolio memory nToken, int256 nTokensToRedeem, int256[] memory tokensToWithdraw, int256[] memory netfCash, bool mustCalculatefCash, uint256 blockTime ) private returns (int256 assetCashShare) { // Get asset cash share for the nToken, if it exists. It is required in balance handler that the // nToken can never have a negative cash asset cash balance so what we get here is always positive // or zero. assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply); if (assetCashShare > 0) { nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } // Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash // is set to true assetCashShare = assetCashShare.add( _removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash) ); nToken.portfolioState.storeAssets(nToken.tokenAddress); // NOTE: Token supply change will happen when we finalize balances and after minting of incentives return assetCashShare; } /// @notice Removes nToken liquidity tokens and updates the netfCash figures. /// @param nToken portfolio object /// @param nTokensToRedeem tokens to redeem /// @param tokensToWithdraw array of liquidity tokens to withdraw /// @param netfCash array of netfCash figures /// @param blockTime current block time /// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step /// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims function _removeLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem, int256[] memory tokensToWithdraw, int256[] memory netfCash, uint256 blockTime, bool mustCalculatefCash ) private returns (int256 totalAssetCashClaims) { MarketParameters memory market; for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i]; asset.notional = asset.notional.sub(tokensToWithdraw[i]); // Cannot redeem liquidity tokens down to zero or this will cause many issues with // market initialization. require(asset.notional > 0, "Cannot redeem to zero"); require(asset.storageState == AssetStorageState.NoChange); asset.storageState = AssetStorageState.Update; // This will load a market object in memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); int256 fCashClaim; { int256 assetCash; // Remove liquidity from the market (assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]); totalAssetCashClaims = totalAssetCashClaims.add(assetCash); } int256 fCashToNToken; if (mustCalculatefCash) { // Do this calculation if net ifCash is not set, will happen if there are no residuals int256 fCashShare = BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, asset.maturity ); fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply); // netfCash = fCashClaim + fCashShare netfCash[i] = fCashClaim.add(fCashShare); fCashToNToken = fCashShare.neg(); } else { // Account will receive netfCash amount. Deduct that from the fCash claim and add the // remaining back to the nToken to net off the nToken's position // fCashToNToken = -fCashShare // netfCash = fCashClaim + fCashShare // fCashToNToken = -(netfCash - fCashClaim) // fCashToNToken = fCashClaim - netfCash fCashToNToken = fCashClaim.sub(netfCash[i]); } // Removes the account's fCash position from the nToken BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, asset.currencyId, asset.maturity, nToken.lastInitializedTime, fCashToNToken ); } return totalAssetCashClaims; } /// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash /// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on /// fCash assets. function _sellfCashAssets( nTokenPortfolio memory nToken, int256[] memory netfCash, uint256 blockTime ) private returns (int256 totalAssetCash, bool hasResidual) { MarketParameters memory market; hasResidual = false; for (uint256 i = 0; i < netfCash.length; i++) { if (netfCash[i] == 0) continue; nToken.cashGroup.loadMarket(market, i + 1, false, blockTime); int256 netAssetCash = market.executeTrade( nToken.cashGroup, // Use the negative of fCash notional here since we want to net it out netfCash[i].neg(), nToken.portfolioState.storedAssets[i].maturity.sub(blockTime), i + 1 ); if (netAssetCash == 0) { // This means that the trade failed hasResidual = true; } else { totalAssetCash = totalAssetCash.add(netAssetCash); netfCash[i] = 0; } } } /// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array function _addResidualsToAssets( PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory newifCashAssets, int256[] memory netfCash ) internal pure returns (PortfolioAsset[] memory finalfCashAssets) { uint256 numAssetsToExtend; for (uint256 i = 0; i < netfCash.length; i++) { if (netfCash[i] != 0) numAssetsToExtend++; } uint256 newLength = newifCashAssets.length + numAssetsToExtend; finalfCashAssets = new PortfolioAsset[](newLength); uint index = 0; for (; index < newifCashAssets.length; index++) { finalfCashAssets[index] = newifCashAssets[index]; } uint netfCashIndex = 0; for (; index < finalfCashAssets.length; ) { if (netfCash[netfCashIndex] != 0) { PortfolioAsset memory asset = finalfCashAssets[index]; asset.currencyId = liquidityTokens[netfCashIndex].currencyId; asset.maturity = liquidityTokens[netfCashIndex].maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = netfCash[netfCashIndex]; index++; } netfCashIndex++; } return finalfCashAssets; } /// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming /// nTokens to its underlying assets. function _reduceifCashAssetsProportional( address account, uint256 currencyId, uint256 lastInitializedTime, int256 tokensToRedeem, int256 totalSupply, bytes32 assetsBitmap ) internal returns (PortfolioAsset[] memory) { uint256 index = assetsBitmap.totalBitsSet(); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; int256 notional = fCashSlot.notional; int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply); int256 finalNotional = notional.sub(notionalToTransfer); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notionalToTransfer; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../internal/portfolio/PortfolioHandler.sol"; import "../internal/balances/BalanceHandler.sol"; import "../internal/settlement/SettlePortfolioAssets.sol"; import "../internal/settlement/SettleBitmapAssets.sol"; import "../internal/AccountContextHandler.sol"; /// @notice External library for settling assets library SettleAssetsExternal { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; event AccountSettled(address indexed account); /// @notice Settles an account, returns the new account context object after settlement. /// @dev The memory location of the account context object is not the same as the one returned. function settleAccount( address account, AccountContext memory accountContext ) external returns (AccountContext memory) { // Defensive check to ensure that this is a valid settlement require(accountContext.mustSettleAssets()); SettleAmount[] memory settleAmounts; PortfolioState memory portfolioState; if (accountContext.isBitmapEnabled()) { (int256 settledCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, block.timestamp ); require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow accountContext.nextSettleTime = uint40(blockTimeUTC0); settleAmounts = new SettleAmount[](1); settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash); } else { portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp); accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts); emit AccountSettled(account); return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../external/SettleAssetsExternal.sol"; import "../internal/AccountContextHandler.sol"; import "../internal/valuation/FreeCollateral.sol"; /// @title Externally deployed library for free collateral calculations library FreeCollateralExternal { using AccountContextHandler for AccountContext; /// @notice Returns the ETH denominated free collateral of an account, represents the amount of /// debt that the account can incur before liquidation. If an account's assets need to be settled this /// will revert, either settle the account or use the off chain SDK to calculate free collateral. /// @dev Called via the Views.sol method to return an account's free collateral. Does not work /// for the nToken, the nToken does not have an account context. /// @param account account to calculate free collateral for /// @return total free collateral in ETH w/ 8 decimal places /// @return array of net local values in asset values ordered by currency id function getFreeCollateralView(address account) external view returns (int256, int256[] memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); // The internal free collateral function does not account for settled assets. The Notional SDK // can calculate the free collateral off chain if required at this point. require(!accountContext.mustSettleAssets(), "Assets not settled"); return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp); } /// @notice Calculates free collateral and will revert if it falls below zero. If the account context /// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets /// need to be settled first. /// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be /// called before the end of any transaction for accounts where FC can decrease. /// @param account account to calculate free collateral for function checkFreeCollateralAndRevert(address account) external { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); require(!accountContext.mustSettleAssets(), "Assets not settled"); (int256 ethDenominatedFC, bool updateContext) = FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp); if (updateContext) { accountContext.setAccountContext(account); } require(ethDenominatedFC >= 0, "Insufficient free collateral"); } /// @notice Calculates liquidation factors for an account /// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is /// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then /// liquidation actions will revert. /// @dev an ntoken account will return 0 FC and revert if called /// @param account account to liquidate /// @param localCurrencyId currency that the debts are denominated in /// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation /// @return accountContext the accountContext of the liquidated account /// @return factors struct of relevant factors for liquidation /// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array) function getLiquidationFactors( address account, uint256 localCurrencyId, uint256 collateralCurrencyId ) external returns ( AccountContext memory accountContext, LiquidationFactors memory factors, PortfolioAsset[] memory portfolio ) { accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { accountContext = SettleAssetsExternal.settleAccount(account, accountContext); } if (accountContext.isBitmapEnabled()) { // A bitmap currency can only ever hold debt in this currency require(localCurrencyId == accountContext.bitmapCurrencyId); } (factors, portfolio) = FreeCollateral.getLiquidationFactors( account, accountContext, block.timestamp, localCurrencyId, collateralCurrencyId ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @dev Returns the multiplication of two signed integers, reverting on /// overflow. /// Counterpart to Solidity's `*` operator. /// Requirements: /// - Multiplication cannot overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; /** * @notice Storage layout for the system. Do not change this file once deployed, future storage * layouts must inherit this and increment the version number. */ contract StorageLayoutV1 { // The current maximum currency id uint16 internal maxCurrencyId; // Sets the state of liquidations being enabled during a paused state. Each of the four lower // bits can be turned on to represent one of the liquidation types being enabled. bytes1 internal liquidationEnabledState; // Set to true once the system has been initialized bool internal hasInitialized; /* Authentication Mappings */ // This is set to the timelock contract to execute governance functions address public owner; // This is set to an address of a router that can only call governance actions address public pauseRouter; // This is set to an address of a router that can only call governance actions address public pauseGuardian; // On upgrades this is set in the case that the pause router is used to pass the rollback check address internal rollbackRouterImplementation; // A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user // to set an allowance on all nTokens for a particular integrating contract system. // owner => spender => transferAllowance mapping(address => mapping(address => uint256)) internal nTokenWhitelist; // Individual transfer allowances for nTokens used for ERC20 // owner => spender => currencyId => transferAllowance mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance; // Transfer operators // Mapping from a global ERC1155 transfer operator contract to an approval value for it mapping(address => bool) internal globalTransferOperator; // Mapping from an account => operator => approval status for that operator. This is a specific // approval between two addresses for ERC1155 transfers. mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator; // Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in // BatchAction.sol, can only be set by governance mapping(address => bool) internal authorizedCallbackContract; // Reverse mapping from token addresses to currency ids, only used for referencing in views // and checking for duplicate token listings. mapping(address => uint16) internal tokenAddressToCurrencyId; // Reentrancy guard uint256 internal reentrancyStatus; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Emitted when reserve balance is updated event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance); /// @notice Emitted when reserve balance is harvested event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return assetAmountInternal which is the converted asset amount accounting for transfer fees function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256 assetAmountInternal) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); if (token.tokenType == TokenType.aToken) { // Handles special accounting requirements for aTokens assetAmountExternal = AaveHandler.convertToScaledBalanceExternal( balanceState.currencyId, assetAmountExternal ); } // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { assetAmountInternal = token.convertToInternal(assetAmountExternal); // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetTokensReceivedExternalPrecision = assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // Final nToken balance is used to calculate the account incentive debt int256 finalNTokenBalance = balanceState.storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); // The toUint() call here will ensure that nToken balances never become negative Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint()); balanceState.storedNTokenBalance = finalNTokenBalance; if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. actualTransferAmountExternal = assetToken.redeem( balanceState.currencyId, account, // No overflow, checked above uint256(assetTransferAmountExternal.neg()) ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { // NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it // will be converted to balanceOf denomination inside transfer actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /** * @notice A special balance storage method for fCash liquidation to reduce the bytecode size. */ function setBalanceStorageForfCashLiquidation( address account, AccountContext memory accountContext, uint16 currencyId, int256 netCashChange ) internal { (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, currencyId); int256 newCashBalance = cashBalance.add(netCashChange); // If a cash balance is negative already we cannot put an account further into debt. In this case // the netCashChange must be positive so that it is coming out of debt. if (newCashBalance < 0) { require(netCashChange > 0, "Neg Cash"); // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check // where all balances are examined. In this case the has cash debt flag should // already be set (cash balances cannot get more negative) but we do it again // here just to be safe. accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } bool isActive = newCashBalance != 0 || nTokenBalance != 0; accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES); // Emit the event here, we do not call finalize emit CashBalanceChange(account, currencyId, netCashChange); _setBalanceStorage( account, currencyId, newCashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice harvests excess reserve balance function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal { // parameters are validated by the caller reserve = reserve.subNoNeg(assetInternalRedeemAmount); _setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0); emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount); } /// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal { require(newBalance >= 0); // dev: invalid balance _setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0); emit ReserveBalanceUpdated(currencyId, newBalance); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow if (lastClaimTime == 0) { // In this case the account has migrated and we set the accountIncentiveDebt // The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never // encounter an overflow for accountIncentiveDebt require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt); } else { // In this case the last claim time has not changed and we do not update the last integral supply // (stored in the accountIncentiveDebt position) require(lastClaimTime == balanceStorage.lastClaimTime); } balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.cashBalance = int88(cashBalance); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; if (lastClaimTime > 0) { // NOTE: this is only necessary to support the deprecated integral supply values, which are stored // in the accountIncentiveDebt slot accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt); } else { accountIncentiveDebt = balanceStorage.accountIncentiveDebt; } cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.accountIncentiveDebt = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts /// are migrated to the new incentive calculation function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256 incentivesClaimed) { incentivesClaimed = Incentives.claimIncentives( balanceState, account, balanceState.storedNTokenBalance.toUint() ); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows /// an account to hold more fCash than a normal portfolio, except only in a single currency. /// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if /// it has no assets or debt so that we ensure no assets are left stranded. /// @param accountContext refers to the account where the bitmap will be enabled /// @param currencyId the id of the currency to enable /// @param blockTime the current block time to set the next settle time function enableBitmapForAccount( AccountContext memory accountContext, uint16 currencyId, uint256 blockTime ) internal view { require(!isBitmapEnabled(accountContext), "Cannot change bitmap"); require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id"); // Account cannot have assets or debts require(accountContext.assetArrayLength == 0, "Cannot have assets"); require(accountContext.hasDebt == 0x00, "Cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface NotionalCallback { function notionalCallback(address sender, address account, bytes calldata callbackdata) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../math/SafeInt256.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // 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: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetHandler.sol"; import "./ExchangeRate.sol"; import "../markets/CashGroup.sol"; import "../AccountContextHandler.sol"; import "../balances/BalanceHandler.sol"; import "../portfolio/PortfolioHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenCalculations.sol"; import "../../math/SafeInt256.sol"; library FreeCollateral { using SafeInt256 for int256; using Bitmap for bytes; using ExchangeRate for ETHRate; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; using nTokenHandler for nTokenPortfolio; /// @dev This is only used within the library to clean up the stack struct FreeCollateralFactors { int256 netETHValue; bool updateContext; uint256 portfolioIndex; CashGroupParameters cashGroup; MarketParameters market; PortfolioAsset[] portfolio; AssetRateParameters assetRate; nTokenPortfolio nToken; } /// @notice Checks if an asset is active in the portfolio function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) { return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO; } /// @notice Checks if currency balances are active in the account returns them if true /// @return cash balance, nTokenBalance function _getCurrencyBalances(address account, bytes2 currencyBytes) private view returns (int256, int256) { if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // prettier-ignore ( int256 cashBalance, int256 nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, currencyId); return (cashBalance, nTokenBalance); } return (0, 0); } /// @notice Calculates the nToken asset value with a haircut set by governance /// @return the value of the account's nTokens after haircut, the nToken parameters function _getNTokenHaircutAssetPV( CashGroupParameters memory cashGroup, nTokenPortfolio memory nToken, int256 tokenBalance, uint256 blockTime ) internal view returns (int256, bytes6) { nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId); nToken.cashGroup = cashGroup; int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // (tokenBalance * nTokenValue * haircut) / totalSupply int256 nTokenHaircutAssetPV = tokenBalance .mul(nTokenAssetPV) .mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE])) .div(Constants.PERCENTAGE_DECIMALS) .div(nToken.totalSupply); // nToken.parameters is returned for use in liquidation return (nTokenHaircutAssetPV, nToken.parameters); } /// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and /// markets. The reason these are grouped together is because they both require storage reads of the same /// values. function _getPortfolioAndNTokenAssetValue( FreeCollateralFactors memory factors, int256 nTokenBalance, uint256 blockTime ) private view returns ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { // If the next asset matches the currency id then we need to calculate the cash group value if ( factors.portfolioIndex < factors.portfolio.length && factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId ) { // netPortfolioValue is in asset cash (netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue( factors.portfolio, factors.cashGroup, factors.market, blockTime, factors.portfolioIndex ); } else { netPortfolioValue = 0; } if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; nTokenParameters = 0; } } /// @notice Returns balance values for the bitmapped currency function _getBitmapBalanceValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns ( int256 cashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { int256 nTokenBalance; // prettier-ignore ( cashBalance, nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId); if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; } } /// @notice Returns portfolio value for the bitmapped currency function _getBitmapPortfolioValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns (int256) { (int256 netPortfolioValueUnderlying, bool bitmapHasDebt) = BitmapAssetsHandler.getifCashNetPresentValue( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, blockTime, factors.cashGroup, true // risk adjusted ); // Turns off has debt flag if it has changed bool contextHasAssetDebt = accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT; if (bitmapHasDebt && !contextHasAssetDebt) { // Turn on has debt accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; factors.updateContext = true; } else if (!bitmapHasDebt && contextHasAssetDebt) { // Turn off has debt accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; factors.updateContext = true; } // Return asset cash value return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying); } function _updateNetETHValue( uint256 currencyId, int256 netLocalAssetValue, FreeCollateralFactors memory factors ) private view returns (ETHRate memory) { ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId); // Converts to underlying first, ETH exchange rates are in underlying factors.netETHValue = factors.netETHValue.add( ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue)) ); return ethRate; } /// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account /// context needs to be updated. function getFreeCollateralStateful( address account, AccountContext memory accountContext, uint256 blockTime ) internal returns (int256, bool) { FreeCollateralFactors memory factors; bool hasCashDebt; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); if (netCashBalance < 0) hasCashDebt = true; int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(account, currencyBytes); if (netLocalAssetValue < 0) hasCashDebt = true; if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); // prettier-ignore ( int256 netPortfolioAssetValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioAssetValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { // NOTE: we must set the proper assetRate when we updateNetETHValue factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValue, factors); currencies = currencies << 16; } // Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e. // they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of // sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing // an account to do an extra free collateral check to turn off this setting. if ( accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT && !hasCashDebt ) { accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT; factors.updateContext = true; } return (factors.netETHValue, factors.updateContext); } /// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips /// all the update context logic. function getFreeCollateralView( address account, AccountContext memory accountContext, uint256 blockTime ) internal view returns (int256, int256[] memory) { FreeCollateralFactors memory factors; uint256 netLocalIndex; int256[] memory netLocalAssetValues = new int256[](10); if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); netLocalAssetValues[netLocalIndex] = netCashBalance .add(nTokenHaircutAssetValue) .add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue( accountContext.bitmapCurrencyId, netLocalAssetValues[netLocalIndex], factors ); netLocalIndex++; } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); int256 nTokenBalance; (netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances( account, currencyBytes ); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupView(currencyId); // prettier-ignore ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex] .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { factors.assetRate = AssetRate.buildAssetRateView(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors); netLocalIndex++; currencies = currencies << 16; } return (factors.netETHValue, netLocalAssetValues); } /// @notice Calculates the net value of a currency within a portfolio, this is a bit /// convoluted to fit into the stack frame function _calculateLiquidationAssetValue( FreeCollateralFactors memory factors, LiquidationFactors memory liquidationFactors, bytes2 currencyBytes, bool setLiquidationFactors, uint256 blockTime ) private returns (int256) { uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(liquidationFactors.account, currencyBytes); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); (int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; // If collateralCurrencyId is set to zero then this is a local currency liquidation if (setLiquidationFactors) { liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenParameters = nTokenParameters; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; } } else { factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } return netLocalAssetValue; } /// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information. function getLiquidationFactors( address account, AccountContext memory accountContext, uint256 blockTime, uint256 localCurrencyId, uint256 collateralCurrencyId ) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) { FreeCollateralFactors memory factors; LiquidationFactors memory liquidationFactors; // This is only set to reduce the stack size liquidationFactors.account = account; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); (int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioBalance = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance); factors.assetRate = factors.cashGroup.assetRate; ETHRate memory ethRate = _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); // If the bitmap currency id can only ever be the local currency where debt is held. // During enable bitmap we check that the account has no assets in their portfolio and // no cash debts. if (accountContext.bitmapCurrencyId == localCurrencyId) { liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // This will be the case during local currency or local fCash liquidation if (collateralCurrencyId == 0) { // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers. liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; liquidationFactors.nTokenParameters = nTokenParameters; } } } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); // This next bit of code here is annoyingly structured to get around stack size issues bool setLiquidationFactors; { uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); // Explicitly ensures that bitmap currency cannot be double counted require(tempId != accountContext.bitmapCurrencyId); setLiquidationFactors = (tempId == localCurrencyId && collateralCurrencyId == 0) || tempId == collateralCurrencyId; } int256 netLocalAssetValue = _calculateLiquidationAssetValue( factors, liquidationFactors, currencyBytes, setLiquidationFactors, blockTime ); uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors); if (currencyId == collateralCurrencyId) { // Ensure that this is set even if the cash group is not loaded, it will not be // loaded if the account only has a cash balance and no nTokens or assets liquidationFactors.collateralCashGroup.assetRate = factors.assetRate; liquidationFactors.collateralAssetAvailable = netLocalAssetValue; liquidationFactors.collateralETHRate = ethRate; } else if (currencyId == localCurrencyId) { // This branch will not be entered if bitmap is enabled liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers and it will have been set in // _calculateLiquidationAssetValue above because the account must have fCash assets, // there is no need to set cash group in this branch. } currencies = currencies << 16; } liquidationFactors.netETHValue = factors.netETHValue; require(liquidationFactors.netETHValue < 0, "Sufficient collateral"); // Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash // netting which will make further calculations incorrect. if (accountContext.assetArrayLength > 0) { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } return (liquidationFactors, factors.portfolio); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../markets/DateTime.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; import "../../interfaces/notional/IRewarder.sol"; import "../../interfaces/aave/ILendingPool.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, // WARNING: this nTokenTotalSupply storage object was used for a buggy version // of the incentives calculation. It should only be used for accounts who have // not claimed before the migration nTokenTotalSupply_deprecated, AssetRate, ExchangeRate, nTokenTotalSupply, SecondaryIncentiveRewarder, LendingPool } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } function getDeprecatedNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists function getSecondaryIncentiveRewarder() internal pure returns (mapping(address => IRewarder) storage store) { uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder); assembly { store.slot := slot } } /// @dev Returns the address of the lending pool function getLendingPool() internal pure returns (LendingPoolStorage storage store) { uint256 slot = _getStorageSlot(StorageId.LendingPool); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } function getNetPresentValueFromBitmap( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted, bytes32 assetsBitmap ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); return getNetPresentValueFromBitmap( account, currencyId, nextSettleTime, blockTime, cashGroup, riskAdjusted, assetsBitmap ); } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../interfaces/chainlink/AggregatorV2V3Interface.sol"; import "../../interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) /// - aToken: Aave interest bearing tokens enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // Accumulator for incentives that the account no longer has a claim over uint256 accountIncentiveDebt; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; // Reserved bytes for future usage bytes15 _unused; // Set to true if a secondary rewarder is set bool hasSecondaryRewarder; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // Incentives that the account no longer has a claim over uint56 accountIncentiveDebt; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. This is the deprecated version struct nTokenTotalSupplyStorage_deprecated { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // How many NOTE incentives should be issued per nToken in 1e18 precision uint128 accumulatedNOTEPerNToken; // Last timestamp when the accumulation happened uint32 lastAccumulatedTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 accountIncentiveDebt; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Each bit set in this mask marks where an active market should be in the bitmap // if the first bit refers to the reference time. Used to detect idiosyncratic // fcash in the nToken accounts bytes32 internal constant ACTIVE_MARKETS_MASK = ( MSB >> ( 90 - 1) | // 3 month MSB >> (105 - 1) | // 6 month MSB >> (135 - 1) | // 1 year MSB >> (147 - 1) | // 2 year MSB >> (183 - 1) | // 5 year MSB >> (211 - 1) | // 10 year MSB >> (251 - 1) // 20 year ); // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // 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: GPL-3.0-only pragma solidity ^0.7.0; interface IRewarder { function claimRewards( address account, uint16 currencyId, uint256 nTokenBalanceBefore, uint256 nTokenBalanceAfter, int256 netNTokenSupplyChange, uint256 NOTETokensClaimed ) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; struct LendingPoolStorage { ILendingPool lendingPool; } interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (ReserveData memory); // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenSupply.sol"; import "../../math/SafeInt256.sol"; import "../../external/MigrateIncentives.sol"; import "../../../interfaces/notional/IRewarder.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @notice Calculates the total incentives to claim including those claimed under the previous /// less accurate calculation. Once an account is migrated it will only claim incentives under /// the more accurate regime function calculateIncentivesToClaim( BalanceState memory balanceState, address tokenAddress, uint256 accumulatedNOTEPerNToken, uint256 finalNTokenBalance ) internal view returns (uint256 incentivesToClaim) { if (balanceState.lastClaimTime > 0) { // If lastClaimTime is set then the account had incentives under the // previous regime. Will calculate the final amount of incentives to claim here // under the previous regime. incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, // In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under // the old calculation balanceState.accountIncentiveDebt ); // This marks the account as migrated and lastClaimTime will no longer be used balanceState.lastClaimTime = 0; // This value will be set immediately after this, set this to zero so that the calculation // establishes a new baseline. balanceState.accountIncentiveDebt = 0; } // If an account was migrated then they have no accountIncentivesDebt and should accumulate // incentives based on their share since the new regime calculation started. // If an account is just initiating their nToken balance then storedNTokenBalance will be zero // and they will have no incentives to claim. // This calculation uses storedNTokenBalance which is the balance of the account up until this point, // this is important to ensure that the account does not claim for nTokens that they will mint or // redeem on a going forward basis. // The calculation below has the following precision: // storedNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION incentivesToClaim = incentivesToClaim.add( balanceState.storedNTokenBalance.toUint() .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION) .sub(balanceState.accountIncentiveDebt) ); // Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion // of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance // here instead of storedNTokenBalance to mark the overall incentives claim that the account // does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt // because accumulatedNOTEPerNToken is already an aggregated value. // The calculation below has the following precision: // finalNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION balanceState.accountIncentiveDebt = finalNTokenBalance .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION); } /// @notice Incentives must be claimed every time nToken balance changes. /// @dev BalanceState.accountIncentiveDebt is updated in place here function claimIncentives( BalanceState memory balanceState, address account, uint256 finalNTokenBalance ) internal returns (uint256 incentivesToClaim) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will updated the nToken storage and return what the accumulatedNOTEPerNToken // is up until this current block time in 1e18 precision uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); incentivesToClaim = calculateIncentivesToClaim( balanceState, tokenAddress, accumulatedNOTEPerNToken, finalNTokenBalance ); // If a secondary incentive rewarder is set, then call it IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress); if (address(rewarder) != address(0)) { rewarder.claimRewards( account, balanceState.currencyId, // When this method is called from finalize, the storedNTokenBalance has not // been updated to finalNTokenBalance yet so this is the balance before the change. balanceState.storedNTokenBalance.toUint(), finalNTokenBalance, // When the rewarder is called, totalSupply has been updated already so may need to // adjust its calculation using the net supply change figure here. Supply change // may be zero when nTokens are transferred. balanceState.netNTokenSupplyChange, incentivesToClaim ); } if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../global/Deployments.sol"; import "./protocols/AaveHandler.sol"; import "./protocols/CompoundHandler.sol"; import "./protocols/GenericToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) { // Set the approval for the underlying so that we can mint cTokens or aTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // cTokens call transfer from the tokenAddress, but aTokens use the LendingPool // to initiate all transfers address approvalAddress = tokenStorage.tokenType == TokenType.cToken ? tokenStorage.tokenAddress : address(LibStorage.getLendingPool().lendingPool); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( approvalAddress, type(uint256).max ); GenericToken.checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /** * @notice If a token is mintable then will mint it. At this point we expect to have the underlying * balance in the contract already. * @param assetToken the asset token to mint * @param underlyingAmountExternal the amount of underlying to transfer to the mintable token * @return the amount of asset tokens minted, will always be a positive integer */ function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) { // aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this // value in internal accounting since it will not allow individual users to accrue aToken interest. Use the // scaledBalanceOf function call instead for internal accounting. bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); if (assetToken.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); AaveHandler.mint(underlyingToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { CompoundHandler.mint(assetToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cETH) { CompoundHandler.mintCETH(assetToken); } else { revert(); // dev: non mintable token } uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /** * @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance * to the account * @param assetToken asset token to redeem * @param currencyId the currency id of the token * @param account account to transfer the underlying to * @param assetAmountExternal the amount to transfer in asset token denomination and external precision * @return the actual amount of underlying tokens transferred. this is used as a return value back to the * user, is not used for internal accounting purposes */ function redeem( Token memory assetToken, uint256 currencyId, address account, uint256 assetAmountExternal ) internal returns (int256) { uint256 transferAmount; if (assetToken.tokenType == TokenType.cETH) { transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal); } else { Token memory underlyingToken = getUnderlyingToken(currencyId); if (assetToken.tokenType == TokenType.aToken) { transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal); } else { revert(); // dev: non redeemable token } } // Use the negative value here to signify that assets have left the protocol return SafeInt256.toInt(transferAmount).neg(); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, uint256 currencyId, int256 netTransferExternal ) internal returns (int256 actualTransferExternal) { // This will be true in all cases except for deposits where the token has transfer fees. For // aTokens this value is set before convert from scaled balances to principal plus interest actualTransferExternal = netTransferExternal; if (token.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); // aTokens need to be converted when we handle the transfer since the external balance format // is not the same as the internal balance format that we use netTransferExternal = AaveHandler.convertFromScaledBalanceExternal( underlyingToken.tokenAddress, netTransferExternal ); } if (netTransferExternal > 0) { // Deposits must account for transfer fees. int256 netDeposit = _deposit(token, account, uint256(netTransferExternal)); // If an aToken has a transfer fee this will still return a balance figure // in scaledBalanceOf terms due to the selector if (token.hasTransferFee) actualTransferExternal = netDeposit; } else if (token.tokenType == TokenType.Ether) { // netTransferExternal can only be negative or zero at this point GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg())); } else { GenericToken.safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; if (token.hasTransferFee) { startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } GenericToken.safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { // If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably // the correct behavior because if collateral accrues interest over time we should not somehow go over the // maxCollateralBalance due to the passage of time. endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenSupply.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenHandler { using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning /// two constants to each other. uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different /// contract, aside from the native NOTE token incentives. function setSecondaryRewarder( uint16 currencyId, IRewarder rewarder ) internal { address tokenAddress = nTokenAddress(currencyId); // nToken must exist for a secondary rewarder require(tokenAddress != address(0)); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // Setting the rewarder to address(0) will disable it. We use a context setting here so that // we can save a storage read before getting the rewarder context.hasSecondaryRewarder = (address(rewarder) != address(0)); LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder; } /// @notice Returns the secondary rewarder if it is set function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* accumulatedNOTEPerNToken */, /* lastAccumulatedTime */ ) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenSupply { using SafeInt256 for int256; using SafeMath for uint256; /// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating /// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead. function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken // must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken; lastAccumulatedTime = nTokenStorage.lastAccumulatedTime; } /// @notice Returns the updated accumulated NOTE per nToken for calculating incentives function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { ( totalSupply, accumulatedNOTEPerNToken, lastAccumulatedTime ) = getStoredNTokenSupplyFactors(tokenAddress); // nToken totalSupply is never allowed to drop to zero but we check this here to avoid // divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not // zero to avoid a massive accumulation amount on initialization. if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) { // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE( // Emission rate is denominated in whole tokens, scale to 1e8 decimals here emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)), // Time since last accumulation (overflow checked above) blockTime - lastAccumulatedTime, totalSupply ); accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken); require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow } } /// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision function _calculateAdditionalNOTE( uint256 emissionRatePerYear, uint256 timeSinceLastAccumulation, uint256 totalSupply ) private pure returns (uint256) { // If we use 18 decimal places as the accumulation precision then we will overflow uint128 when // a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max // NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe // using 18 decimal places and uint128 storage slot // timeSinceLastAccumulation (SECONDS) // accumulatedNOTEPerSharePrecision (1e18) // emissionRatePerYear (INTERNAL_TOKEN_PRECISION) // DIVIDE BY // YEAR (SECONDS) // totalSupply (INTERNAL_TOKEN_PRECISION) return timeSinceLastAccumulation .mul(Constants.INCENTIVE_ACCUMULATION_PRECISION) .mul(emissionRatePerYear) .div(Constants.YEAR) // totalSupply > 0 is checked in the calling function .div(totalSupply); } /// @notice Updates the nToken token supply amount when minting or redeeming. /// @param tokenAddress address of the nToken /// @param netChange positive or negative change to the total nToken supply /// @param blockTime current block time /// @return accumulatedNOTEPerNToken updated to the given block time function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, /* uint256 lastAccumulatedTime */ ) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime); // Update storage variables mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; int256 newTotalSupply = int256(totalSupply).add(netChange); // We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to // exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check. require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what // the user would see if querying the view function nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken); require(blockTime < type(uint32).max); // dev: block time overflow nTokenStorage.lastAccumulatedTime = uint32(blockTime); return accumulatedNOTEPerNToken; } /// @notice Called by governance to set the new emission rate function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal { // Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the // emission rate changeNTokenSupply(tokenAddress, 0, blockTime); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "../internal/nToken/nTokenHandler.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @notice Deployed library for migration of incentives from the old (inaccurate) calculation * to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate * calculation is inside `Incentives.sol` and this library holds the legacy calculation. System * migration code can be found in `MigrateIncentivesFix.sol` */ library MigrateIncentives { using SafeMath for uint256; /// @notice Calculates the claimable incentives for a particular nToken and account in the /// previous regime. This should only ever be called ONCE for an account / currency combination /// to get the incentives accrued up until the migration date. function migrateAccountFromPreviousCalculation( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) external view returns (uint256) { ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) = _getMigratedIncentiveValues(tokenAddress); // This if statement should never be true but we return 0 just in case if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0; // No overflow here, checked above. All incentives are claimed up until finalMigrationTime // using the finalTotalIntegralSupply. Both these values are set on migration and will not // change. uint256 timeSinceMigration = finalMigrationTime - lastClaimTime; // (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR uint256 incentiveRate = timeSinceMigration .mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) // Migration emission rate is stored as is, denominated in whole tokens .mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) .div(Constants.YEAR); // Returns the average supply using the integral of the total supply. uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } function _getMigratedIncentiveValues( address tokenAddress ) private view returns ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) { mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress]; // The total supply value is overridden as emissionRatePerYear during the initialization finalEmissionRatePerYear = d_nTokenStorage.totalSupply; finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply; finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce /// gas costs for immutable addresses. They must be updated per environment that Notional /// is deployed to. library Deployments { address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../../global/Types.sol"; import "../../../global/LibStorage.sol"; import "../../../math/SafeInt256.sol"; import "../TokenHandler.sol"; import "../../../../interfaces/aave/IAToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AaveHandler { using SafeMath for uint256; using SafeInt256 for int256; int256 internal constant RAY = 1e27; int256 internal constant halfRAY = RAY / 2; bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector; /** * @notice Mints an amount of aTokens corresponding to the the underlying. * @param underlyingToken address of the underlying token to pass to Aave * @param underlyingAmountExternal amount of underlying to deposit, in external precision */ function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal { // In AaveV3 this method is renamed to supply() but deposit() is still available for // backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755 // We use deposit here so that mainnet-fork tests against Aave v2 will pass. LibStorage.getLendingPool().lendingPool.deposit( underlyingToken.tokenAddress, underlyingAmountExternal, address(this), 0 ); } /** * @notice Redeems and sends an amount of aTokens to the specified account * @param underlyingToken address of the underlying token to pass to Aave * @param account account to receive the underlying * @param assetAmountExternal amount of aTokens in scaledBalanceOf terms */ function redeem( Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { underlyingAmountExternal = convertFromScaledBalanceExternal( underlyingToken.tokenAddress, SafeInt256.toInt(assetAmountExternal) ).toUint(); LibStorage.getLendingPool().lendingPool.withdraw( underlyingToken.tokenAddress, underlyingAmountExternal, account ); } /** * @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest) * and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional * claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will * receive future Aave interest. * @dev There is no loss of precision within this function since it does the exact same calculation as Aave. * @param currencyId is the currency id * @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must * be positive in this function, this method is only called when depositing aTokens directly * @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will * be in external precision. */ function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress); // Mimic the WadRay math performed by Aave (but do it in int256 instead) int256 halfIndex = index / 2; // Overflow will occur when: (a * RAY + halfIndex) > int256.max require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY); // if index is zero then this will revert return (assetAmountExternal * RAY + halfIndex) / index; } /** * @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision) * and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest * that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions. * @dev There is no loss of precision because this does exactly what Aave's calculation would do * @param underlyingToken token address of the underlying asset * @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from * Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or * withdrawn (negative). * @return netBalanceExternal the Aave balanceOf equivalent as a signed integer */ function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) { if (netScaledBalanceExternal == 0) return 0; // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken); // Use the absolute value here so that the halfRay rounding is applied correctly for negative values int256 abs = netScaledBalanceExternal.abs(); // Mimic the WadRay math performed by Aave (but do it in int256 instead) // Overflow will occur when: (abs * index + halfRay) > int256.max // Here the first term is computed at compile time so it just does a division. If index is zero then // solidity will revert. require(abs <= (type(int256).max - halfRAY) / index); int256 absScaled = (abs * index + halfRAY) / RAY; return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg(); } /// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is /// always positive even though we are converting to a signed int function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) { return SafeInt256.toInt( LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./GenericToken.sol"; import "../../../../interfaces/compound/CErc20Interface.sol"; import "../../../../interfaces/compound/CEtherInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../global/Types.sol"; library CompoundHandler { using SafeMath for uint256; // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; function mintCETH(Token memory token) internal { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); } function redeemCETH( Token memory assetToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = address(this).balance; uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = address(this).balance; underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.transferNativeTokenOut(account, underlyingAmountExternal); } function redeem( Token memory assetToken, Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../../../../interfaces/IEIP20NonStandard.sol"; library GenericToken { bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector; /** * @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows * for overriding the balanceOf selector to use scaledBalanceOf for aTokens */ function checkBalanceViaSelector( address token, address account, bytes4 balanceOfSelector ) internal returns (uint256 balance) { (bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account)); require(success); (balance) = abi.decode(returnData, (uint256)); } function transferNativeTokenOut( address account, uint256 amount ) internal { // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. payable(account).transfer(amount); } function safeTransferOut( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() internal pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // 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: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); function UNDERLYING_ASSET_ADDRESS() external view returns (address); function symbol() external view returns (string memory); } interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } interface IATokenFull is IScaledBalanceToken, IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface IEIP20NonStandard { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved */ function approve(address spender, uint256 amount) external; /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../balances/TokenHandler.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol"; library ExchangeRate { using SafeInt256 for int256; /// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are /// always applied in this method. /// @param er exchange rate object from base to ETH /// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) { int256 multiplier = balance > 0 ? er.haircut : er.buffer; // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals) // Therefore the result is in ethDecimals int256 result = balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div( er.rateDecimals ); return result; } /// @notice Converts the balance denominated in ETH to the equivalent value in a base currency. /// Buffers and haircuts ARE NOT applied in this method. /// @param er exchange rate object from base to ETH /// @param balance amount (denominated in ETH) to convert function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) { // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals / rateDecimals int256 result = balance.mul(er.rateDecimals).div(er.rate); return result; } /// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in /// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals /// @param baseER base exchange rate struct /// @param quoteER quote exchange rate struct function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER) internal pure returns (int256) { return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate); } /// @notice Returns an ETHRate object used to calculate free collateral function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) { mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage(); ETHRateStorage storage ethStorage = store[currencyId]; int256 rateDecimals; int256 rate; if (currencyId == Constants.ETH_CURRENCY_ID) { // ETH rates will just be 1e18, but will still have buffers, haircuts, // and liquidation discounts rateDecimals = Constants.ETH_DECIMALS; rate = Constants.ETH_DECIMALS; } else { // prettier-ignore ( /* roundId */, rate, /* uint256 startedAt */, /* updatedAt */, /* answeredInRound */ ) = ethStorage.rateOracle.latestRoundData(); require(rate > 0, "Invalid rate"); // No overflow, restricted on storage rateDecimals = int256(10**ethStorage.rateDecimalPlaces); if (ethStorage.mustInvert) { rate = rateDecimals.mul(rateDecimals).div(rate); } } return ETHRate({ rateDecimals: rateDecimals, rate: rate, buffer: ethStorage.buffer, haircut: ethStorage.haircut, liquidationDiscount: ethStorage.liquidationDiscount }); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; library nTokenCalculations { using Bitmap for bytes32; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using CashGroup for CashGroupParameters; /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // This is the total value in liquid assets (int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime); // Then get the total value in any idiosyncratic fCash residuals (if they exist) bytes32 ifCashBits = getNTokenifCashBits( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); int256 ifCashResidualUnderlyingPV = 0; if (ifCashBits != 0) { // Non idiosyncratic residuals have already been accounted for (ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false, // nToken present value calculation does not use risk adjusted values ifCashBits ); } // Return the total present value denominated in asset terms return totalAssetValueInMarkets .add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV)) .add(nToken.cashBalance); } /** * @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts * in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken * portfolio. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to * the account's share of the total supply * @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually * withdrawn from markets */ function _getProportionalLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem ) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; tokensToWithdraw = new int256[](numMarkets); netfCash = new int256[](numMarkets); for (uint256 i = 0; i < numMarkets; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply); } } /** * @notice Returns the number of liquidity tokens to withdraw from each market if the nToken * has idiosyncratic residuals during nToken redeem. In this case the redeemer will take * their cash from the rest of the fCash markets, redeeming around the nToken. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param blockTime block time * @param ifCashBits the bits in the bitmap that represent ifCash assets * @return tokensToWithdraw array of tokens to withdraw from each corresponding market * @return netfCash array of netfCash amounts to go back to the account */ function getLiquidityTokenWithdraw( nTokenPortfolio memory nToken, int256 nTokensToRedeem, uint256 blockTime, bytes32 ifCashBits ) internal view returns (int256[] memory, int256[] memory) { // If there are no ifCash bits set then this will just return the proportion of all liquidity tokens if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem); ( int256 totalAssetValueInMarkets, int256[] memory netfCash ) = getNTokenMarketValue(nToken, blockTime); int256[] memory tokensToWithdraw = new int256[](netfCash.length); // NOTE: this total portfolio asset value does not include any cash balance the nToken may hold. // The redeemer will always get a proportional share of this cash balance and therefore we don't // need to account for it here when we calculate the share of liquidity tokens to withdraw. We are // only concerned with the nToken's portfolio assets in this method. int256 totalPortfolioAssetValue; { // Returns the risk adjusted net present value for the idiosyncratic residuals (int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, true, // use risk adjusted here to assess a penalty for withdrawing around the residual ifCashBits ); // NOTE: we do not include cash balance here because the account will always take their share // of the cash balance regardless of the residuals totalPortfolioAssetValue = totalAssetValueInMarkets.add( nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV) ); } // Loops through each liquidity token and calculates how much the redeemer can withdraw to get // the requisite amount of present value after adjusting for the ifCash residual value that is // not accessible via redemption. for (uint256 i = 0; i < tokensToWithdraw.length; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; // Redeemer's baseline share of the liquidity tokens based on total supply: // redeemerShare = totalTokens * nTokensToRedeem / totalSupply // Scalar factor to account for residual value (need to inflate the tokens to withdraw // proportional to the value locked up in ifCash residuals): // scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets // Final math equals: // tokensToWithdraw = redeemerShare * scalarFactor // tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue) // / (totalAssetValueInMarkets * totalSupply) tokensToWithdraw[i] = totalTokens .mul(nTokensToRedeem) .mul(totalPortfolioAssetValue); tokensToWithdraw[i] = tokensToWithdraw[i] .div(totalAssetValueInMarkets) .div(nToken.totalSupply); // This is the share of net fcash that will be credited back to the account netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens); } return (tokensToWithdraw, netfCash); } /// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by /// the liquidity tokens held in each market and their corresponding fCash positions. The formula /// can be described as: /// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash)) /// where netfCash = fCashClaim + fCash /// and fCash refers the the fCash position at the corresponding maturity function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256 totalAssetValue, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; netfCash = new int256[](numMarkets); MarketParameters memory market; for (uint256 i = 0; i < numMarkets; i++) { // Load the corresponding market into memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i]; uint256 maturity = liquidityToken.maturity; // Get the fCash claims and fCash assets. We do not use haircut versions here because // nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied // at the end of the calculation to the entire PV instead). (int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market); // fCash is denominated in underlying netfCash[i] = fCashClaim.add( BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, maturity ) ); // This calculates for a single liquidity token: // assetCashClaim + convertToAssetCash(pv(netfCash)) int256 netAssetValueInMarket = assetCashClaim.add( nToken.cashGroup.assetRate.convertFromUnderlying( AssetHandler.getPresentfCashValue( netfCash[i], maturity, blockTime, // No need to call cash group for oracle rate, it is up to date here // and we are assured to be referring to this market. market.oracleRate ) ) ); // Calculate the running total totalAssetValue = totalAssetValue.add(netAssetValueInMarket); } } /// @notice Returns just the bits in a bitmap that are idiosyncratic function getNTokenifCashBits( address tokenAddress, uint256 currencyId, uint256 lastInitializedTime, uint256 blockTime, uint256 maxMarketIndex ) internal view returns (bytes32) { // If max market index is less than or equal to 2, there are never ifCash assets by construction if (maxMarketIndex <= 2) return bytes32(0); bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId); // Handles the case when there are no assets at the first initialization if (assetsBitmap == 0) return assetsBitmap; uint256 tRef = DateTime.getReferenceTime(blockTime); if (tRef == lastInitializedTime) { // This is a more efficient way to turn off ifCash assets in the common case when the market is // initialized immediately return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK); } else { // In this branch, initialize markets has occurred past the time above. It would occur in these // two scenarios (both should be exceedingly rare): // 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef) // 2. somehow initialize markets has been delayed for more than 24 hours for (uint i = 1; i <= maxMarketIndex; i++) { // In this loop we get the maturity of each active market and turn off the corresponding bit // one by one. It is less efficient than the option above. uint256 maturity = tRef + DateTime.getTradedMarket(i); (uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity); assetsBitmap = assetsBitmap.setBit(bitNum, false); } return assetsBitmap; } } }
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.
interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); 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 ); pragma solidity >=0.6.0; }
12,606
./full_match/42/0x7D40Eb66aD44C3bF0355c9657f612f2Ca09d81a1/sources/contracts/GameReveal2.sol
call by the winner si c'est la bonne solution on lui envoie la récompense Envoie toute la balance (monaire) à celui qui à résolu le contract player.transfer(address(this).balance);
function claim(string memory _solution, string memory _salt) payable external { require(keccak256(abi.encodePacked(_solution, _salt)) == hash); address payable player = payable(msg.sender); require(address(this).balance > 0); player.transfer(getRewardAmount()); }
16,208,494
./full_match/5/0x2747A57e3070fc19bAFE8806Be5bc37eBEaf0dB6/sources/contracts/Finale.sol
Collects and distributes the primary sale value of NFTs being claimed.
function _collectPriceOnClaim( address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal virtual override { if (_pricePerToken == 0) { return; } (address platformFeeRecipient, uint16 platformFeeBps) = getPlatformFeeInfo(); uint256 totalPrice = _quantityToClaim * _pricePerToken; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { if (msg.value != totalPrice) { revert("Must send total price"); } } address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient; CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees); CurrencyTransferLib.transferCurrency(_currency, _msgSender(), saleRecipient, totalPrice - platformFees); }
1,918,998
./full_match/80001/0x37AdbCBa91AC155958F910685446f970632a60E6/sources/contracts/TMHC-Reborn-Stake.sol
Claims the rewards for all staked team leaders and their boosts for the caller./
function calimTeamAll() external nonReentrant{ _claimTeamAll(); }
840,341
pragma solidity ^0.4.24; /** * @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 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 SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } library Attribute { enum AttributeType { ROLE_MANAGER, // 0 ROLE_OPERATOR, // 1 IS_BLACKLISTED, // 2 HAS_PASSED_KYC_AML, // 3 NO_FEES, // 4 /* Additional user-defined later */ USER_DEFINED } function toUint256(AttributeType _type) internal pure returns (uint256) { return uint256(_type); } } /** * @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; } } library BitManipulation { uint256 constant internal ONE = uint256(1); function setBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num | (ONE << _pos); } function clearBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num & ~(ONE << _pos); } function toggleBit(uint256 _num, uint256 _pos) internal pure returns (uint256) { return _num ^ (ONE << _pos); } function checkBit(uint256 _num, uint256 _pos) internal pure returns (bool) { return (_num >> _pos & ONE == ONE); } } /** * @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 Claimable * @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); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Claimable Ex * @dev Extension for the Claimable contract, where the ownership transfer can be canceled. */ contract ClaimableEx is Claimable { /* * @dev Cancels the ownership transfer. */ function cancelOwnershipTransfer() onlyOwner public { pendingOwner = owner; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this Ether. * @notice Ether can still be sent to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by setting a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param _from address The address that is transferring the tokens * @param _value uint256 the amount of the specified token * @param _data Bytes The data passed from the caller. */ function tokenFallback( address _from, uint256 _value, bytes _data ) external pure { _from; _value; _data; revert(); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param _contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address _contractAddr) external onlyOwner { Ownable contractInst = Ownable(_contractAddr); contractInst.transferOwnership(owner); } } /** * @title Base contract for contracts that should not own things. * @author Remco Bloemen <remco@2π.com> * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or * Owned contracts. See respective base contracts for details. */ contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } /** * @title NoOwner Ex * @dev Extension for the NoOwner contract, to support a case where * this contract's owner can't own ether or tokens. * Note that we *do* inherit reclaimContract from NoOwner: This contract * does have to own contracts, but it also has to be able to relinquish them **/ contract NoOwnerEx is NoOwner { function reclaimEther(address _to) external onlyOwner { _to.transfer(address(this).balance); } function reclaimToken(ERC20Basic token, address _to) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(_to, balance); } } /** * @title Address Set. * @dev This contract allows to store addresses in a set and * owner can run a loop through all elements. **/ contract AddressSet is Ownable { mapping(address => bool) exist; address[] elements; /** * @dev Adds a new address to the set. * @param _addr Address to add. * @return True if succeed, otherwise false. */ function add(address _addr) onlyOwner public returns (bool) { if (contains(_addr)) { return false; } exist[_addr] = true; elements.push(_addr); return true; } /** * @dev Checks whether the set contains a specified address or not. * @param _addr Address to check. * @return True if the address exists in the set, otherwise false. */ function contains(address _addr) public view returns (bool) { return exist[_addr]; } /** * @dev Gets an element at a specified index in the set. * @param _index Index. * @return A relevant address. */ function elementAt(uint256 _index) onlyOwner public view returns (address) { require(_index < elements.length); return elements[_index]; } /** * @dev Gets the number of elements in the set. * @return The number of elements. */ function getTheNumberOfElements() onlyOwner public view returns (uint256) { return elements.length; } } // A wrapper around the balances mapping. contract BalanceSheet is ClaimableEx { using SafeMath for uint256; mapping (address => uint256) private balances; AddressSet private holderSet; constructor() public { holderSet = new AddressSet(); } /** * @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]; } function addBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = balances[_addr].add(_value); _checkHolderSet(_addr); } function subBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = balances[_addr].sub(_value); } function setBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = _value; _checkHolderSet(_addr); } function setBalanceBatch( address[] _addrs, uint256[] _values ) public onlyOwner { uint256 _count = _addrs.length; require(_count == _values.length); for(uint256 _i = 0; _i < _count; _i++) { setBalance(_addrs[_i], _values[_i]); } } function getTheNumberOfHolders() public view returns (uint256) { return holderSet.getTheNumberOfElements(); } function getHolder(uint256 _index) public view returns (address) { return holderSet.elementAt(_index); } function _checkHolderSet(address _addr) internal { if (!holderSet.contains(_addr)) { holderSet.add(_addr); } } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * A version of OpenZeppelin's StandardToken whose balances mapping has been replaced * with a separate BalanceSheet contract. Most useful in combination with e.g. * HasNoContracts because then it can relinquish its balance sheet to a new * version of the token, removing the need to copy over balances. **/ contract StandardToken is ClaimableEx, NoOwnerEx, ERC20 { using SafeMath for uint256; uint256 totalSupply_; BalanceSheet private balances; event BalanceSheetSet(address indexed sheet); mapping (address => mapping (address => uint256)) private allowed; constructor() public { totalSupply_ = 0; } /** * @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 the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances.balanceOf(_owner); } /** * @dev Claim ownership of the BalanceSheet contract * @param _sheet The address of the BalanceSheet to claim. */ function setBalanceSheet(address _sheet) public onlyOwner returns (bool) { balances = BalanceSheet(_sheet); balances.claimOwnership(); emit BalanceSheetSet(_sheet); return true; } function getTheNumberOfHolders() public view returns (uint256) { return balances.getTheNumberOfHolders(); } function getHolder(uint256 _index) public view returns (address) { return balances.getHolder(_index); } /** * @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 Transfer tokens from one address to another * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { _transferFrom(_from, _to, _value, msg.sender); 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) { _approve(_spender, _value, msg.sender); 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) * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { _increaseApproval(_spender, _addedValue, msg.sender); 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) * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { _decreaseApproval(_spender, _subtractedValue, msg.sender); return true; } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal { allowed[_tokenHolder][_spender] = _value; emit Approval(_tokenHolder, _spender, _value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _burner The account whose tokens will be burnt. * @param _value The amount that will be burnt. */ function _burn(address _burner, uint256 _value) internal { require(_burner != 0); require(_value <= balanceOf(_burner), "not enough balance to burn"); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances.subBalance(_burner, _value); totalSupply_ = totalSupply_.sub(_value); emit Transfer(_burner, address(0), _value); } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal { uint256 _oldValue = allowed[_tokenHolder][_spender]; if (_subtractedValue >= _oldValue) { allowed[_tokenHolder][_spender] = 0; } else { allowed[_tokenHolder][_spender] = _oldValue.sub(_subtractedValue); } emit Approval(_tokenHolder, _spender, allowed[_tokenHolder][_spender]); } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal { allowed[_tokenHolder][_spender] = ( allowed[_tokenHolder][_spender].add(_addedValue)); emit Approval(_tokenHolder, _spender, allowed[_tokenHolder][_spender]); } /** * @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 _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances.addBalance(_account, _amount); emit Transfer(address(0), _account, _amount); } function _transfer(address _from, address _to, uint256 _value) internal { require(_to != address(0), "to address cannot be 0x0"); require(_from != address(0),"from address cannot be 0x0"); require(_value <= balanceOf(_from), "not enough balance to transfer"); // SafeMath.sub will throw if there is not enough balance. balances.subBalance(_from, _value); balances.addBalance(_to, _value); emit Transfer(_from, _to, _value); } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { uint256 _allowed = allowed[_from][_spender]; require(_value <= _allowed, "not enough allowance to transfer"); allowed[_from][_spender] = allowed[_from][_spender].sub(_value); _transfer(_from, _to, _value); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). **/ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value, string note); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. * @param _note a note that burner can attach. */ function burn(uint256 _value, string _note) public returns (bool) { _burn(msg.sender, _value, _note); return true; } /** * @dev Burns a specific amount of tokens of an user. * @param _burner Who has tokens to be burned. * @param _value The amount of tokens to be burned. * @param _note a note that the manager can attach. */ function _burn( address _burner, uint256 _value, string _note ) internal { _burn(_burner, _value); emit Burn(_burner, _value, _note); } } // Interface for logic governing write access to a Registry. contract RegistryAccessManager { // Called when _admin attempts to write _value for _who's _attribute. // Returns true if the write is allowed to proceed. function confirmWrite( address _who, Attribute.AttributeType _attribute, address _admin ) public returns (bool); } contract DefaultRegistryAccessManager is RegistryAccessManager { function confirmWrite( address /*_who*/, Attribute.AttributeType _attribute, address _operator ) public returns (bool) { Registry _client = Registry(msg.sender); if (_operator == _client.owner()) { return true; } else if (_client.hasAttribute(_operator, Attribute.AttributeType.ROLE_MANAGER)) { return (_attribute == Attribute.AttributeType.ROLE_OPERATOR); } else if (_client.hasAttribute(_operator, Attribute.AttributeType.ROLE_OPERATOR)) { return (_attribute != Attribute.AttributeType.ROLE_OPERATOR && _attribute != Attribute.AttributeType.ROLE_MANAGER); } } } contract Registry is ClaimableEx { using BitManipulation for uint256; struct AttributeData { uint256 value; } // Stores arbitrary attributes for users. An example use case is an ERC20 // token that requires its users to go through a KYC/AML check - in this case // a validator can set an account's "hasPassedKYC/AML" attribute to 1 to indicate // that account can use the token. This mapping stores that value (1, in the // example) as well as which validator last set the value and at what time, // so that e.g. the check can be renewed at appropriate intervals. mapping(address => AttributeData) private attributes; // The logic governing who is allowed to set what attributes is abstracted as // this accessManager, so that it may be replaced by the owner as needed. RegistryAccessManager public accessManager; event SetAttribute( address indexed who, Attribute.AttributeType attribute, bool enable, string notes, address indexed adminAddr ); event SetManager( address indexed oldManager, address indexed newManager ); constructor() public { accessManager = new DefaultRegistryAccessManager(); } // Writes are allowed only if the accessManager approves function setAttribute( address _who, Attribute.AttributeType _attribute, string _notes ) public { bool _canWrite = accessManager.confirmWrite( _who, _attribute, msg.sender ); require(_canWrite); // Get value of previous attribute before setting new attribute uint256 _tempVal = attributes[_who].value; attributes[_who] = AttributeData( _tempVal.setBit(Attribute.toUint256(_attribute)) ); emit SetAttribute(_who, _attribute, true, _notes, msg.sender); } function clearAttribute( address _who, Attribute.AttributeType _attribute, string _notes ) public { bool _canWrite = accessManager.confirmWrite( _who, _attribute, msg.sender ); require(_canWrite); // Get value of previous attribute before setting new attribute uint256 _tempVal = attributes[_who].value; attributes[_who] = AttributeData( _tempVal.clearBit(Attribute.toUint256(_attribute)) ); emit SetAttribute(_who, _attribute, false, _notes, msg.sender); } // Returns true if the uint256 value stored for this attribute is non-zero function hasAttribute( address _who, Attribute.AttributeType _attribute ) public view returns (bool) { return attributes[_who].value.checkBit(Attribute.toUint256(_attribute)); } // Returns the exact value of the attribute, as well as its metadata function getAttributes( address _who ) public view returns (uint256) { AttributeData memory _data = attributes[_who]; return _data.value; } function setManager(RegistryAccessManager _accessManager) public onlyOwner { emit SetManager(accessManager, _accessManager); accessManager = _accessManager; } } // Superclass for contracts that have a registry that can be set by their owners contract HasRegistry is Ownable { Registry public registry; event SetRegistry(address indexed registry); function setRegistry(Registry _registry) public onlyOwner { registry = _registry; emit SetRegistry(registry); } } /** * @title Manageable * @dev The Manageable contract provides basic authorization control functions * for managers. This simplifies the implementation of "manager permissions". */ contract Manageable is HasRegistry { /** * @dev Throws if called by any account that is not in the managers list. */ modifier onlyManager() { require( registry.hasAttribute( msg.sender, Attribute.AttributeType.ROLE_MANAGER ) ); _; } /** * @dev Getter to determine if address is a manager */ function isManager(address _operator) public view returns (bool) { return registry.hasAttribute( _operator, Attribute.AttributeType.ROLE_MANAGER ); } } // Interface implemented by tokens that are the *target* of a BurnableToken's // delegation. That is, if we want to replace BurnableToken X by // Y but for convenience we'd like users of X // to be able to keep using it and it will just forward calls to Y, // then X should extend CanDelegate and Y should extend DelegateBurnable. // Most ERC20 calls use the value of msg.sender to figure out e.g. whose // balance to update; since X becomes the msg.sender of all such calls // that it forwards to Y, we add the origSender parameter to those calls. // Delegation is intended as a convenience for legacy users of X since // we do not expect all regular users to learn about Y and change accordingly, // but we do require the *owner* of X to now use Y instead so ownerOnly // functions are not delegated and should be disabled instead. // This delegation system is intended to work with the modified versions of // the standard ERC20 token contracts, allowing the balances // to be moved over to a new contract. // NOTE: To maintain backwards compatibility, these function signatures // cannot be changed contract DelegateBurnable { function delegateTotalSupply() public view returns (uint256); function delegateBalanceOf(address _who) public view returns (uint256); function delegateTransfer(address _to, uint256 _value, address _origSender) public returns (bool); function delegateAllowance(address _owner, address _spender) public view returns (uint256); function delegateTransferFrom( address _from, address _to, uint256 _value, address _origSender ) public returns (bool); function delegateApprove( address _spender, uint256 _value, address _origSender ) public returns (bool); function delegateIncreaseApproval( address _spender, uint256 _addedValue, address _origSender ) public returns (bool); function delegateDecreaseApproval( address _spender, uint256 _subtractedValue, address _origSender ) public returns (bool); function delegateBurn( address _origSender, uint256 _value, string _note ) public; function delegateGetTheNumberOfHolders() public view returns (uint256); function delegateGetHolder(uint256 _index) public view returns (address); } /** * @title Contactable token * @dev Basic version of a contactable contract, allowing the owner to provide a string with their * contact information. */ contract Contactable is Ownable { string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param _info The contact information to attach to the contract. */ function setContactInformation(string _info) public onlyOwner { contactInformation = _info; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function _transfer( address _from, address _to, uint256 _value ) internal whenNotPaused { super._transfer(_from, _to, _value); } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal whenNotPaused { super._transferFrom(_from, _to, _value, _spender); } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal whenNotPaused { super._approve(_spender, _value, _tokenHolder); } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal whenNotPaused { super._increaseApproval(_spender, _addedValue, _tokenHolder); } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal whenNotPaused { super._decreaseApproval(_spender, _subtractedValue, _tokenHolder); } function _burn( address _burner, uint256 _value ) internal whenNotPaused { super._burn(_burner, _value); } } // See DelegateBurnable.sol for more on the delegation system. contract CanDelegateToken is BurnableToken { // If this contract needs to be upgraded, the new contract will be stored // in 'delegate' and any BurnableToken calls to this contract will be delegated to that one. DelegateBurnable public delegate; event DelegateToNewContract(address indexed newContract); // Can undelegate by passing in _newContract = address(0) function delegateToNewContract( DelegateBurnable _newContract ) public onlyOwner { delegate = _newContract; emit DelegateToNewContract(delegate); } // If a delegate has been designated, all ERC20 calls are forwarded to it function _transfer(address _from, address _to, uint256 _value) internal { if (!_hasDelegate()) { super._transfer(_from, _to, _value); } else { require(delegate.delegateTransfer(_to, _value, _from)); } } function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { if (!_hasDelegate()) { super._transferFrom(_from, _to, _value, _spender); } else { require(delegate.delegateTransferFrom(_from, _to, _value, _spender)); } } function totalSupply() public view returns (uint256) { if (!_hasDelegate()) { return super.totalSupply(); } else { return delegate.delegateTotalSupply(); } } function balanceOf(address _who) public view returns (uint256) { if (!_hasDelegate()) { return super.balanceOf(_who); } else { return delegate.delegateBalanceOf(_who); } } function getTheNumberOfHolders() public view returns (uint256) { if (!_hasDelegate()) { return super.getTheNumberOfHolders(); } else { return delegate.delegateGetTheNumberOfHolders(); } } function getHolder(uint256 _index) public view returns (address) { if (!_hasDelegate()) { return super.getHolder(_index); } else { return delegate.delegateGetHolder(_index); } } function _approve( address _spender, uint256 _value, address _tokenHolder ) internal { if (!_hasDelegate()) { super._approve(_spender, _value, _tokenHolder); } else { require(delegate.delegateApprove(_spender, _value, _tokenHolder)); } } function allowance( address _owner, address _spender ) public view returns (uint256) { if (!_hasDelegate()) { return super.allowance(_owner, _spender); } else { return delegate.delegateAllowance(_owner, _spender); } } function _increaseApproval( address _spender, uint256 _addedValue, address _tokenHolder ) internal { if (!_hasDelegate()) { super._increaseApproval(_spender, _addedValue, _tokenHolder); } else { require( delegate.delegateIncreaseApproval(_spender, _addedValue, _tokenHolder) ); } } function _decreaseApproval( address _spender, uint256 _subtractedValue, address _tokenHolder ) internal { if (!_hasDelegate()) { super._decreaseApproval(_spender, _subtractedValue, _tokenHolder); } else { require( delegate.delegateDecreaseApproval( _spender, _subtractedValue, _tokenHolder) ); } } function _burn(address _burner, uint256 _value, string _note) internal { if (!_hasDelegate()) { super._burn(_burner, _value, _note); } else { delegate.delegateBurn(_burner, _value , _note); } } function _hasDelegate() internal view returns (bool) { return !(delegate == address(0)); } } // Treats all delegate functions exactly like the corresponding normal functions, // e.g. delegateTransfer is just like transfer. See DelegateBurnable.sol for more on // the delegation system. contract DelegateToken is DelegateBurnable, BurnableToken { address public delegatedFrom; event DelegatedFromSet(address addr); // Only calls from appointed address will be processed modifier onlyMandator() { require(msg.sender == delegatedFrom); _; } function setDelegatedFrom(address _addr) public onlyOwner { delegatedFrom = _addr; emit DelegatedFromSet(_addr); } // each function delegateX is simply forwarded to function X function delegateTotalSupply( ) public onlyMandator view returns (uint256) { return totalSupply(); } function delegateBalanceOf( address _who ) public onlyMandator view returns (uint256) { return balanceOf(_who); } function delegateTransfer( address _to, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _transfer(_origSender, _to, _value); return true; } function delegateAllowance( address _owner, address _spender ) public onlyMandator view returns (uint256) { return allowance(_owner, _spender); } function delegateTransferFrom( address _from, address _to, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _transferFrom(_from, _to, _value, _origSender); return true; } function delegateApprove( address _spender, uint256 _value, address _origSender ) public onlyMandator returns (bool) { _approve(_spender, _value, _origSender); return true; } function delegateIncreaseApproval( address _spender, uint256 _addedValue, address _origSender ) public onlyMandator returns (bool) { _increaseApproval(_spender, _addedValue, _origSender); return true; } function delegateDecreaseApproval( address _spender, uint256 _subtractedValue, address _origSender ) public onlyMandator returns (bool) { _decreaseApproval(_spender, _subtractedValue, _origSender); return true; } function delegateBurn( address _origSender, uint256 _value, string _note ) public onlyMandator { _burn(_origSender, _value , _note); } function delegateGetTheNumberOfHolders() public view returns (uint256) { return getTheNumberOfHolders(); } function delegateGetHolder(uint256 _index) public view returns (address) { return getHolder(_index); } } /** * @title Asset information. * @dev Stores information about a specified real asset. */ contract AssetInfo is Manageable { string public publicDocument; /** * Event for updated running documents logging. * @param newLink New link. */ event UpdateDocument( string newLink ); /** * @param _publicDocument A link to a zip file containing running documents of the asset. */ constructor(string _publicDocument) public { publicDocument = _publicDocument; } /** * @dev Updates information about where to find new running documents of this asset. * @param _link A link to a zip file containing running documents of the asset. */ function setPublicDocument(string _link) public onlyManager { publicDocument = _link; emit UpdateDocument(publicDocument); } } /** * @title BurnableExToken. * @dev Extension for the BurnableToken contract, to support * some manager to enforce burning all tokens of all holders. **/ contract BurnableExToken is Manageable, BurnableToken { /** * @dev Burns all remaining tokens of all holders. * @param _note a note that the manager can attach. */ function burnAll(string _note) external onlyManager { uint256 _holdersCount = getTheNumberOfHolders(); for (uint256 _i = 0; _i < _holdersCount; ++_i) { address _holder = getHolder(_i); uint256 _balance = balanceOf(_holder); if (_balance == 0) continue; _burn(_holder, _balance, _note); } } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation **/ contract MintableToken is StandardToken { event Mint(address indexed to, uint256 value); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _value ) public hasMintPermission canMint returns (bool) { _mint(_to, _value); emit Mint(_to, _value); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract CompliantToken is HasRegistry, MintableToken { // Addresses can also be blacklisted, preventing them from sending or receiving // PAT tokens. This can be used to prevent the use of PAT by bad actors in // accordance with law enforcement. modifier onlyIfNotBlacklisted(address _addr) { require( !registry.hasAttribute( _addr, Attribute.AttributeType.IS_BLACKLISTED ) ); _; } modifier onlyIfBlacklisted(address _addr) { require( registry.hasAttribute( _addr, Attribute.AttributeType.IS_BLACKLISTED ) ); _; } modifier onlyIfPassedKYC_AML(address _addr) { require( registry.hasAttribute( _addr, Attribute.AttributeType.HAS_PASSED_KYC_AML ) ); _; } function _mint( address _to, uint256 _value ) internal onlyIfPassedKYC_AML(_to) onlyIfNotBlacklisted(_to) { super._mint(_to, _value); } // transfer and transferFrom both call this function, so check blacklist here. function _transfer( address _from, address _to, uint256 _value ) internal onlyIfNotBlacklisted(_from) onlyIfNotBlacklisted(_to) onlyIfPassedKYC_AML(_to) { super._transfer(_from, _to, _value); } } /** * @title TokenWithFees. * @dev This contract allows for transaction fees to be assessed on transfer. **/ contract TokenWithFees is Manageable, StandardToken { uint8 public transferFeeNumerator = 0; uint8 public transferFeeDenominator = 100; // All transaction fees are paid to this address. address public beneficiary; event ChangeWallet(address indexed addr); event ChangeFees(uint8 transferFeeNumerator, uint8 transferFeeDenominator); constructor(address _wallet) public { beneficiary = _wallet; } // transfer and transferFrom both call this function, so pay fee here. // E.g. if A transfers 1000 tokens to B, B will receive 999 tokens, // and the system wallet will receive 1 token. function _transfer(address _from, address _to, uint256 _value) internal { uint256 _fee = _payFee(_from, _value, _to); uint256 _remaining = _value.sub(_fee); super._transfer(_from, _to, _remaining); } function _payFee( address _payer, uint256 _value, address _otherParticipant ) internal returns (uint256) { // This check allows accounts to be whitelisted and not have to pay transaction fees. bool _shouldBeFree = ( registry.hasAttribute(_payer, Attribute.AttributeType.NO_FEES) || registry.hasAttribute(_otherParticipant, Attribute.AttributeType.NO_FEES) ); if (_shouldBeFree) { return 0; } uint256 _fee = _value.mul(transferFeeNumerator).div(transferFeeDenominator); if (_fee > 0) { super._transfer(_payer, beneficiary, _fee); } return _fee; } function checkTransferFee(uint256 _value) public view returns (uint256) { return _value.mul(transferFeeNumerator).div(transferFeeDenominator); } function changeFees( uint8 _transferFeeNumerator, uint8 _transferFeeDenominator ) public onlyManager { require(_transferFeeNumerator < _transferFeeDenominator); transferFeeNumerator = _transferFeeNumerator; transferFeeDenominator = _transferFeeDenominator; emit ChangeFees(transferFeeNumerator, transferFeeDenominator); } /** * @dev Change address of the wallet where the fees will be sent to. * @param _beneficiary The new wallet address. */ function changeWallet(address _beneficiary) public onlyManager { require(_beneficiary != address(0), "new wallet cannot be 0x0"); beneficiary = _beneficiary; emit ChangeWallet(_beneficiary); } } // This allows a token to treat transfer(redeemAddress, value) as burn(value). // This is useful for users of standard wallet programs which have transfer // functionality built in but not the ability to burn. contract WithdrawalToken is BurnableToken { address public constant redeemAddress = 0xfacecafe01facecafe02facecafe03facecafe04; function _transfer(address _from, address _to, uint256 _value) internal { if (_to == redeemAddress) { burn(_value, ''); } else { super._transfer(_from, _to, _value); } } // StandardToken's transferFrom doesn't have to check for _to != redeemAddress, // but we do because we redirect redeemAddress transfers to burns, but // we do not redirect transferFrom function _transferFrom( address _from, address _to, uint256 _value, address _spender ) internal { require(_to != redeemAddress, "_to is redeem address"); super._transferFrom(_from, _to, _value, _spender); } } /** * @title PAT token. * @dev PAT is a ERC20 token that: * - has no tokens limit. * - mints new tokens for each new property (real asset). * - can pause and unpause token transfer (and authorization) actions. * - token holders can be distributed profit from asset manager. * - contains real asset information. * - can delegate to a new contract. * - can enforce burning all tokens. * - transferring tokens to 0x0 address is treated as burning. * - transferring tokens with fees are sent to the system wallet. * - attempts to check KYC/AML and Blacklist using Registry. * - attempts to reject ERC20 token transfers to itself and allows token transfer out. * - attempts to reject ether sent and allows any ether held to be transferred out. * - allows the new owner to accept the ownership transfer, the owner can cancel the transfer if needed. **/ contract PATToken is Contactable, AssetInfo, BurnableExToken, CanDelegateToken, DelegateToken, TokenWithFees, CompliantToken, WithdrawalToken, PausableToken { string public name = "RAX Mt.Fuji"; string public symbol = "FUJI"; uint8 public constant decimals = 18; event ChangeTokenName(string newName, string newSymbol); /** * @param _name Name of this token. * @param _symbol Symbol of this token. */ constructor( string _name, string _symbol, string _publicDocument, address _wallet ) public AssetInfo(_publicDocument) TokenWithFees(_wallet) { name = _name; symbol = _symbol; contactInformation = 'https://rax.exchange/'; } function changeTokenName(string _name, string _symbol) public onlyOwner { name = _name; symbol = _symbol; emit ChangeTokenName(_name, _symbol); } /** * @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) onlyOwner public { // do not allow self ownership require(_newOwner != address(this)); super.transferOwnership(_newOwner); } }
Burns all remaining tokens of all holders. _note a note that the manager can attach./
function burnAll(string _note) external onlyManager { uint256 _holdersCount = getTheNumberOfHolders(); for (uint256 _i = 0; _i < _holdersCount; ++_i) { address _holder = getHolder(_i); uint256 _balance = balanceOf(_holder); if (_balance == 0) continue; _burn(_holder, _balance, _note); } }
13,059,909
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { DSMath } from "../lib/ds-hub.sol"; import { StorageSlotOwnable } from "../lib/StorageSlotOwnable.sol"; import { OnApprove } from "../token/ERC20OnApprove.sol"; import { NonLinearTimeLockSwapperV2_0_4Storage } from "./NonLinearTimeLockSwapperV2_0_4Storage.sol"; contract NonLinearTimeLockSwapperV2_0_4 is NonLinearTimeLockSwapperV2_0_4Storage, StorageSlotOwnable, DSMath, OnApprove { using SafeERC20 for IERC20; using SafeMath for uint256; modifier onlyValidAddress(address account) { require(account != address(0), "zero-address"); _; } modifier onlyDeposit(address sourceToken, address account) { require(depositAmounts[sourceToken][account] != 0, "no-deposit"); _; } event Deposited( address indexed sourceToken, address indexed beneficiary, uint256 sourceTokenAmount, uint256 targetTokenAmount ); event Undeposited(address indexed sourceToken, address indexed beneficiary, uint256 amount, address receiver); event Claimed(address indexed sourceToken, address indexed beneficiary, uint256 targetTokenAmount); event TokenWalletChanged(address indexed previousWallet, address newWallet); ////////////////////////////////////////// // // kernel // ////////////////////////////////////////// function implementationVersion() public view virtual override returns (string memory) { return "2.0.4"; } function _initializeKernel(bytes memory data) internal override { (address owner_, address token_, address tokenWallet_) = abi.decode(data, (address, address, address)); _initializeV2(owner_, token_, tokenWallet_); } function _initializeV2( address owner_, address token_, address tokenWallet_ ) private onlyValidAddress(owner_) onlyValidAddress(token_) onlyValidAddress(tokenWallet_) { if (owner() == address(0)) _setOwner(owner_); if (address(token) == address(0)) token = IERC20(token_); if (tokenWallet == address(0)) tokenWallet = tokenWallet_; _registerInterface(OnApprove(this).onApprove.selector); } ////////////////////////////////////////// // // token wallet // ////////////////////////////////////////// function setTokenWallet(address tokenWallet_) external onlyOwner onlyValidAddress(tokenWallet_) { address previousWallet = tokenWallet; tokenWallet = tokenWallet_; emit TokenWalletChanged(previousWallet, tokenWallet_); } ////////////////////////////////////////// // // register source token // ////////////////////////////////////////// /** * @dev register source token with vesting data */ function register( address sourceToken, uint128 rate, uint128 startTime, uint256[] memory stepEndTimes, uint256[] memory stepRatio ) external onlyOwner { require(!isRegistered(sourceToken), "duplicate-register"); require(rate > 0, "invalid-rate"); require(stepEndTimes.length == stepRatio.length, "invalid-array-length"); uint256 n = stepEndTimes.length; uint256[] memory accStepRatio = new uint256[](n); uint256 accRatio; for (uint256 i = 0; i < n; i++) { accRatio = add(accRatio, stepRatio[i]); accStepRatio[i] = accRatio; } require(accRatio == WAD, "invalid-acc-ratio"); for (uint256 i = 1; i < n; i++) { require(stepEndTimes[i - 1] < stepEndTimes[i], "unsorted-times"); } sourceTokenDatas[sourceToken] = SourceTokeData({ rate: rate, startTime: startTime, stepEndTimes: stepEndTimes, accStepRatio: accStepRatio }); } function isRegistered(address sourceToken) public view returns (bool) { return sourceTokenDatas[sourceToken].startTime > 0; } function getStepEndTimes(address sourceToken) external view returns (uint256[] memory) { return sourceTokenDatas[sourceToken].stepEndTimes; } function getAccStepRatio(address sourceToken) external view returns (uint256[] memory) { return sourceTokenDatas[sourceToken].accStepRatio; } ////////////////////////////////////////// // // source token deposit // ////////////////////////////////////////// function onApprove( address owner, address spender, uint256 amount, bytes calldata data ) external override returns (bool) { require(spender == address(this), "invalid-approval"); require(isRegistered(msg.sender), "unregistered-source-token"); deposit(msg.sender, owner, amount); data; return true; } // deposit sender's token function deposit( address sourceToken, address beneficiary, uint256 sourceTokenAmount ) public onlyValidAddress(beneficiary) { require(isRegistered(sourceToken), "unregistered-source-token"); require(sourceTokenAmount > 0, "invalid-amount"); require(msg.sender == address(sourceToken) || msg.sender == beneficiary, "no-auth"); SourceTokeData storage data = sourceTokenDatas[sourceToken]; uint256 targetTokenAmount = wmul(sourceTokenAmount, data.rate); // update initial balance depositAmounts[sourceToken][beneficiary] = depositAmounts[sourceToken][beneficiary].add(sourceTokenAmount); // get source token from beneficiary IERC20(sourceToken).safeTransferFrom(beneficiary, address(this), sourceTokenAmount); emit Deposited(sourceToken, beneficiary, sourceTokenAmount, targetTokenAmount); } ////////////////////////////////////////// // // claim // ////////////////////////////////////////// function claim(address sourceToken) public onlyDeposit(sourceToken, msg.sender) { uint256 amount = claimable(sourceToken, msg.sender); require(amount > 0, "invalid-amount"); claimedAmounts[sourceToken][msg.sender] = claimedAmounts[sourceToken][msg.sender].add(amount); token.safeTransferFrom(tokenWallet, msg.sender, amount); emit Claimed(sourceToken, msg.sender, amount); } function claimTokens(address[] calldata sourceTokens) external { for (uint256 i = 0; i < sourceTokens.length; i++) { claim(sourceTokens[i]); } } /** * @dev get claimable tokens now */ function claimable(address sourceToken, address beneficiary) public view returns (uint256) { return claimableAt(sourceToken, beneficiary, block.timestamp); } /** * @dev get claimable tokens at `timestamp` */ function claimableAt( address sourceToken, address beneficiary, uint256 timestamp ) public view returns (uint256) { require(block.timestamp <= timestamp, "invalid-timestamp"); SourceTokeData storage sourceTokenData = sourceTokenDatas[sourceToken]; uint256 totalClaimable = wmul(depositAmounts[sourceToken][beneficiary], sourceTokenData.rate); uint256 claimedAmount = claimedAmounts[sourceToken][beneficiary]; if (timestamp < sourceTokenData.startTime) return 0; if (timestamp >= sourceTokenData.stepEndTimes[sourceTokenData.stepEndTimes.length - 1]) return totalClaimable.sub(claimedAmount); uint256 step = getStepAt(sourceToken, timestamp); uint256 accRatio = sourceTokenData.accStepRatio[step]; uint256 claimableAmount = wmul(totalClaimable, accRatio); return claimableAmount > claimedAmount ? claimableAmount.sub(claimedAmount) : 0; } function initialBalance(address sourceToken, address beneficiary) external view returns (uint256) { return depositAmounts[sourceToken][beneficiary]; } /** * @dev get current step */ function getStep(address sourceToken) public view returns (uint256) { return getStepAt(sourceToken, block.timestamp); } /** * @dev get step at `timestamp` */ function getStepAt(address sourceToken, uint256 timestamp) public view returns (uint256) { SourceTokeData storage sourceTokenData = sourceTokenDatas[sourceToken]; require(timestamp >= sourceTokenData.startTime, "not-started"); uint256 n = sourceTokenData.stepEndTimes.length; if (timestamp >= sourceTokenData.stepEndTimes[n - 1]) { return n - 1; } if (timestamp <= sourceTokenData.stepEndTimes[0]) { return 0; } uint256 lo = 1; uint256 hi = n - 1; uint256 md; while (lo < hi) { md = (hi + lo + 1) / 2; if (timestamp < sourceTokenData.stepEndTimes[md - 1]) { hi = md - 1; } else { lo = md; } } return lo; } } // 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. 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) { 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; /** * @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 "../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' // 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"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface DSAuthority { function canCall( address src, address dst, bytes4 sig ) external view returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(address(0))) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue() } _; emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); } } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; //rounds to zero if x*y < WAD / 2 function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSThing is DSAuth, DSNote, DSMath { function S(string memory s) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked(s))); } } contract DSValue is DSThing { bool has; bytes32 val; function peek() public view returns (bytes32, bool) { return (val, has); } function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = peek(); require(haz, "haz-not"); return wut; } function poke(bytes32 wut) public note auth { val = wut; has = true; } function void() public note auth { // unset the value has = false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/StorageSlot.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 StorageSlotOwnable is Context { bytes32 private constant _OWNER_SLOT = bytes32(uint256(keccak256("StorageSlotOwnable.owner")) - 1); /** * @dev Returns the current owner. */ function _getOwner() internal view returns (address) { return StorageSlot.getAddressSlot(_OWNER_SLOT).value; } /** * @dev Stores a new address in the owner slot. */ function _setOwner(address newOwner) internal { require(newOwner != address(0), "StorageSlotOwnable: new admin is the zero address"); StorageSlot.getAddressSlot(_OWNER_SLOT).value = newOwner; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _getOwner(); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "StorageSlotOwnable: 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(_getOwner(), address(0)); _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), "StorageSlotOwnable: new owner is the zero address"); emit OwnershipTransferred(_getOwner(), newOwner); _setOwner(newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // solhint-disable-line compiler-version import { ERC165 } from "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { ERC165Storage } from "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; abstract contract OnApprove is ERC165Storage { constructor() { _registerInterface(OnApprove(this).onApprove.selector); } function onApprove( address owner, address spender, uint256 amount, bytes calldata data ) external virtual returns (bool); } abstract contract ERC20OnApprove is ERC20 { function approveAndCall( address spender, uint256 amount, bytes calldata data ) external returns (bool) { require(approve(spender, amount), "ERC20OnApprove: fail to approve"); _callOnApprove(msg.sender, spender, amount, data); return true; } function _callOnApprove( address owner, address spender, uint256 amount, bytes memory data ) internal { bytes4 onApproveSelector = OnApprove(spender).onApprove.selector; require( ERC165Checker.supportsInterface(spender, onApproveSelector), "ERC20OnApprove: spender doesn't support onApprove" ); (bool ok, bytes memory res) = spender.call( abi.encodeWithSelector(onApproveSelector, owner, spender, amount, data) ); // check if low-level call reverted or not require(ok, string(res)); assembly { ok := mload(add(res, 0x20)) } // check if OnApprove.onApprove returns true or false require(ok, "ERC20OnApprove: failed to call onApprove"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Kernel } from "../proxy/Kernel.sol"; abstract contract NonLinearTimeLockSwapperV2_0_4Storage is Kernel { // swap data for each source token, i.e., teamCFX, ecoCFX, backCFX struct SourceTokeData { uint128 rate; // convertion rate from source token to target token uint128 startTime; uint256[] stepEndTimes; uint256[] accStepRatio; } IERC20 public token; // target token, i.e., CFX address public tokenWallet; // address who supply target token /// @dev `migrationStopped` is deprecated. this exists only to remain storage layout. bool public _____DEPRECATED_____migrationStopped; // time lock data for each source token mapping(address => SourceTokeData) public sourceTokenDatas; // source token deposit amounts // sourceToken => beneficiary => deposit amounts mapping(address => mapping(address => uint256)) public depositAmounts; // source token claimed amounts // sourceToken => beneficiary => claimed amounts mapping(address => mapping(address => uint256)) public claimedAmounts; } // 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; // 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.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) { 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.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // 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; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC165.sol"; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Storage is ERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _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.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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, 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 defaut 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: * * - `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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - 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 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= 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 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.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; import "../IERC20.sol"; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This contains proxy initialization data */ abstract contract Kernel { bytes32 private constant INITIALIZED = bytes32(uint256(keccak256("Kernel.INITIALIZED")) - 1); // initialized for the version mapping(bytes32 => bool) private _initialized; modifier onlyKernelInitialized() { require(kernelInitialized(), "Kernel: no-init"); _; } modifier onlyKernelInitializedWithVersion(string memory version) { require(kernelInitialized(getVersionHash(version)), "Kernel: no-init"); _; } /// @dev Each implementation contract must implement `implementationVersion` with unique return value for a proxy. function implementationVersion() public view virtual returns (string memory); /// @dev External function to initialize proxy, with specific `_initializeKernel` /// implemented in each implementation contract. function initializeKernel(bytes calldata data) external returns (bool) { require(!kernelInitialized(), "Kernel: already-init"); bytes32 h = getVersionHash(); _initialized[h] = true; _initializeKernel(data); return true; } /// @dev Implementation contract have to override `_initializeKernel` to initialize after proxy upgraded. function _initializeKernel(bytes memory data) internal virtual; function kernelInitialized() public view returns (bool) { bytes32 h = getVersionHash(); return _initialized[h]; } /// @dev Return whether kernel is initialized with version hash. function kernelInitialized(bytes32 h) public view returns (bool) { return _initialized[h]; } /// @dev Return hash of current implementation version. function getVersionHash() public view returns (bytes32) { return getVersionHash(implementationVersion()); } /// @dev Return hash of given implementation version. function getVersionHash(string memory version) public pure returns (bytes32) { bytes32 h = keccak256(abi.encode(INITIALIZED, version)); return h; } }
get claimable tokens now/
function claimable(address sourceToken, address beneficiary) public view returns (uint256) { return claimableAt(sourceToken, beneficiary, block.timestamp); }
299,414
./full_match/1/0xDaf6F80AD2AFdC45014c59bfE507ED728656D11B/sources/contracts/AuctionMarketplace.sol
Returns Merkle Roots For A Specific Sale SaleIndex The Sale Index To View/
function ViewRoots(uint SaleIndex) public view returns (bytes32[] memory) { return MerkleRootsEligibility[SaleIndex]; }
3,007,018
./full_match/4/0x5539c9E1d8Ac0F34839D31dCc2a6e97b332A8BeF/sources/browser/contracts/SafeEx.sol
Creates `amount` of new tokens for `to`. See {ERC20-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./
function mint(address to, uint256 amount) public virtual override { require( hasRole(MINTER_ROLE, _msgSender()), "SafeExToken: must have minter role to mint" ); _mint(to, amount); }
12,355,882
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.0; import "../CryptoChampions.sol"; import "../token/ChampzToken.sol"; /// @title Exposed version of CryptoChampions /// @author Oozyx /// @notice This contract inherits from CryptoChampions and makes its functions testable /// @dev Not to be deployed outside of a test environment contract ExposedCryptoChampions is CryptoChampions { /// Holds the requestId bytes32 public requestId; /// See CryptoChampions::CryptoChampions constructor( bytes32 keyhash, address vrfCoordinator, address linkToken, address minigameFactoryRegistry, ChampzToken champzToken ) public CryptoChampions(keyhash, vrfCoordinator, linkToken, minigameFactoryRegistry, champzToken) {} /// See CryptoChampions::_getRandomNumber function getRandomNumber(uint256 seed) public { requestId = _getRandomNumber(seed); } /// See CryptoChampions::_randomResult function getRandomResult() public view returns (uint256) { return _randomResultsVRF[requestId]; } /// See CryptoChampions::_burnElders function burnElders() public { _burnElders(); } /// See CryptoChampions::_burnElder function burnElder(uint256 elderId) public { _burnElder(elderId); } /// See CryptoChampions::_canMintHero function canMintHero(uint256 elderId) public view returns (bool) { return _canMintHero(elderId); } /// See CryptoChampions::_trainHero function trainHero(uint256 heroId, uint256 randomNumber) public { _heroRandomRequest[requestId] = heroId; _randomResultsVRF[requestId] = randomNumber; _trainHero(requestId); } /// See CryptoChampions::_startNewPriceGame function startNewPriceGame() public { _startNewPriceGame(); } /// See CryptoChampions::_transitionNextPhase function transitionNextPhase() public { _transitionNextPhase(); } /// See CryptoChampions::_heroRewardsShare function heroRewardsShare() public view returns (uint256) { return _heroRewardsShare; } }
See CryptoChampions::_startNewPriceGame
function startNewPriceGame() public { _startNewPriceGame(); }
12,873,280
pragma solidity ^0.5.4; contract HelloTON { uint32 timestamp; // Modifier that allows public function to accept all external calls. modifier alwaysAccept { tvm.accept(); _; } modifier onlyOwner { require(msg.pubkey() == tvm.pubkey(), 100); tvm.accept(); _; } constructor() public { timestamp = uint32(now); } //Function setting set value to state variable timestamp function touch() public alwaysAccept { timestamp = uint32(now); } //Function returns value of state variable timestamp function sayHello() public view returns (uint32) { return timestamp; } //Due to the modifier onlyOwner function sendAllMoney can be called only by the owner of the contract. //Function sendAllMoney send all contract's money to dest_addr. function sendAllMoney(address payable dest_addr) public onlyOwner { selfdestruct(dest_addr); } }
Function setting set value to state variable timestamp
function touch() public alwaysAccept { timestamp = uint32(now); }
12,959,688
pragma solidity >=0.4.22 <0.6.0; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } library DateTime { /* * Date and Time utilities for ethereum contracts * */ struct MyDateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) public pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (MyDateTime memory dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = 0;//getHour(timestamp); // Minute dt.minute = 0;//getMinute(timestamp); // Second dt.second = 0;//getSecond(timestamp); // Day of week. dt.weekday = 0;//getWeekday(timestamp); } function getYear(uint timestamp) public pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) public pure returns (uint8) { return uint8(timestamp % 60); } function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toDay(uint256 timestamp) internal pure returns (uint256) { MyDateTime memory d = parseTimestamp(timestamp); return uint256(d.year) * 10000 + uint256(d.month) * 100 + uint256(d.day); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public pure returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); // Hour timestamp += HOUR_IN_SECONDS * (hour); // Minute timestamp += MINUTE_IN_SECONDS * (minute); // Second timestamp += second; return timestamp; } } contract Controlled{ address public owner; address public operator; mapping (address => bool) public blackList; constructor() public { owner = msg.sender; operator = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyOperator() { require(msg.sender == operator || msg.sender == owner); _; } modifier isNotBlack(address _addr) { require(blackList[_addr] == false); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); owner = _newOwner; } function transferOperator(address _newOperator) public onlyOwner { require(_newOperator != address(0)); operator = _newOperator; } function addBlackList(address _blackAddr) public onlyOperator { blackList[_blackAddr] = true; } function removeBlackList(address _blackAddr) public onlyOperator { delete blackList[_blackAddr]; } } contract TokenERC20 is Controlled{ using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed _from, address indexed _to, uint256 _value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This generates a public event on the blockchain that will notify clients event Burn(address indexed burner, uint256 value); /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0x0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public isNotBlack(msg.sender) returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public isNotBlack(msg.sender) returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public isNotBlack(msg.sender) returns (bool success) { require(_value <= balanceOf[msg.sender]); // Check balance allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public returns (bool) { require(_value > 0); require(_value <= balanceOf[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balanceOf[burner] = balanceOf[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); return true; } } contract FrozenableToken is TokenERC20{ using SafeMath for uint; using DateTime for uint256; uint256 public totalFrozen; struct UnfreezeRecord { address to; uint256 amount; // release amount uint256 unfreezeTime; } mapping (uint256 => UnfreezeRecord) public unfreezeRecords; event Unfreeze(address indexed receiver, uint256 value, uint256 unfreezeTime); function unfreeze(address _receiver, uint256 _value) public onlyOwner returns (bool) { require(_value > 0); require(_value <= totalFrozen); balanceOf[owner] = balanceOf[owner].add(_value); totalFrozen = totalFrozen.sub(_value); totalSupply = totalSupply.add(_value); uint256 timestamp = block.timestamp; uint256 releasedDay = timestamp.toDay(); _transfer(owner,_receiver,_value); unfreezeRecords[releasedDay] = UnfreezeRecord(_receiver, _value, timestamp); emit Unfreeze(_receiver, _value, timestamp); return true; } } contract CasinoTkoen is FrozenableToken{ /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = 'CasinoToken'; // Set the name for display purposes symbol = 'CT'; // Set the symbol for display purposes decimals = 18; totalFrozen = 100000000 * 10 ** uint256(decimals); totalSupply = 0; balanceOf[msg.sender] = 0; } }
Internal transfer, only can be called by this contract/ Prevent transfer to 0x0 address. Use burn() instead Check if the sender has enough Check for overflows Save this for an assertion in the future Subtract from the sender Add the same to the recipient Asserts are used to use static analysis to find bugs in your code. They should never fail
function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0x0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
5,367,646
./full_match/1/0xa943F863fA69ff4F6D9022843Fb861BBEe45B2ce/sources/TangleBundle0.sol
Gets all available rewards from all farms address_ The address whose rewards info will be returned return Each individual farm's rewards and the combined total rewards
function availableRewards( address address_ ) external view returns (string[] memory, uint[] memory) { SLib.S storage s = SLib.getS(); uint[] memory rewards = new uint[](s.names.length + 1); uint totalRewards = 0; for (uint i = 0; i < s.names.length; i++) { rewards[i] = piecesToUnits(_availableRewards(address_, s.names[i])); totalRewards += rewards[i]; } rewards[s.names.length] = totalRewards; return (s.names, rewards); }
17,007,035
pragma solidity >=0.4.21 < 0.6.0; library BloomFilter { struct Filter { uint256 bitmap; uint8 hashCount; } /** * @dev It returns how many times it should be hashed, when the expected * number of input items is _itenNum. * @param _itemNum Expected number of input items */ function getHashCount(uint _itemNum) public pure returns(uint8) { uint numOfHash = (256 * 144) / (_itemNum * 100) + 1; if(numOfHash < 256) return uint8(numOfHash); else return 255; } /** * @dev It returns updated bitmap when a new item is added into the bitmap * @param _bitmap Original bitmap * @param _hashCount How many times to hash. You should use the same value with the one which is used for the original bitmap. * @param _item Hash value of an item */ function addToBitmap(uint256 _bitmap, uint8 _hashCount, bytes32 _item) public pure returns(uint256 _newBitmap) { _newBitmap = _bitmap; require(_hashCount > 0, "Hash count can not be zero"); for(uint i = 0; i < _hashCount; i++) { uint256 position = uint256(keccak256(abi.encodePacked(_item, i))) % 256; require(position < 256, "Overflow error"); uint256 digest = 1 << position; _newBitmap = _newBitmap | digest; } return _newBitmap; } /** * @dev It returns it may exist or definitely not exist. * @param _bitmap Original bitmap * @param _hashCount How many times to hash. You should use the same value with the one which is used for the original bitmap. * @param _item Hash value of an item */ function falsePositive(uint256 _bitmap, uint8 _hashCount, bytes32 _item) public pure returns(bool _probablyPresent){ require(_hashCount > 0, "Hash count can not be zero"); for(uint i = 0; i < _hashCount; i++) { uint256 position = uint256(keccak256(abi.encodePacked(_item, i))) % 256; require(position < 256, "Overflow error"); uint256 digest = 1 << position; if(_bitmap != _bitmap | digest) return false; } return true; } // Please see the test/TestBloomFilter.sol to know how to use this library in another contract. /** * @dev It initialize the Filter struct. It sets the appropriate hash count for the expected number of item * @param _itemNum Expected number of items to be added */ function init(Filter storage _filter, uint _itemNum) internal { _filter.hashCount = getHashCount(_itemNum); } /** * @dev It updates the bitmap of the filter using the given item value * @param _item Hash value of an item */ function add(Filter storage _filter, bytes32 _item) internal { _filter.bitmap = addToBitmap(_filter.bitmap, _filter.hashCount, _item); } /** * @dev It returns the filter may include the item or definitely now include it. * @param _item Hash value of an item */ function check(Filter storage _filter, bytes32 _item) internal view returns(bool) { return falsePositive(_filter.bitmap, _filter.hashCount, _item); } }
It initialize the Filter struct. It sets the appropriate hash count for the expected number of item _itemNum Expected number of items to be added/
function init(Filter storage _filter, uint _itemNum) internal { _filter.hashCount = getHashCount(_itemNum); }
15,873,430
pragma solidity ^0.4.20; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant 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 constant 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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { 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; } 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 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; /** * @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) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { address public saleAgent; address public partner; modifier onlyAdmin() { require(msg.sender == owner || msg.sender == saleAgent || msg.sender == partner); _; } function setSaleAgent(address newSaleAgent) onlyOwner public { require(newSaleAgent != address(0)); saleAgent = newSaleAgent; } function setPartner(address newPartner) onlyOwner public { require(newPartner != address(0)); partner = newPartner; } event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Pausable { using SafeMath for uint256; mapping(address => uint256) balances; uint256 public storageTime = 1522749600; // 04/03/2018 @ 10:00am (UTC) modifier checkStorageTime() { require(now >= storageTime); _; } modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length >= numwords * 32 + 4); _; } function setStorageTime(uint256 _time) public onlyOwner { storageTime = _time; } /** * @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 onlyPayloadSize(2) whenNotPaused checkStorageTime returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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 constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev 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)) 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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) whenNotPaused checkStorageTime returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @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 onlyPayloadSize(2) whenNotPaused returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; 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 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { 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, uint _addedValue) public onlyPayloadSize(2) returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); 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, uint _subtractedValue) public onlyPayloadSize(2) returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken{ event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve 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 onlyAdmin whenNotPaused canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(this), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is MintableToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyPayloadSize(1) { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } function burnFrom(address _from, uint256 _value) public onlyPayloadSize(2) returns (bool success) { require(balances[_from] >= _value);// Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]);// Check allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); Burn(_from, _value); return true; } } contract AlttexToken is BurnableToken { string public constant name = "Alttex"; string public constant symbol = "ALTX"; uint8 public constant decimals = 8; } contract Crowdsale is Ownable { using SafeMath for uint; uint256 public startTimeRound1; uint256 public endTimeRound1; uint256 public startTimeRound2; uint256 public endTimeRound2; // one token per one rate uint256 public rateRound1 = 1200; uint256 public rateRound2; uint256 constant dec = 10 ** 8; uint256 public supply = 50000000 * 10 ** 8; uint256 public percentTokensToSale = 60; uint256 public tokensToSale = supply.mul(percentTokensToSale).div(100); // address where funds are collected address public wallet; AlttexToken public token; // Amount of raised money in wei uint256 public weiRaised = 17472 * 10 ** 16; // 174.72 ETH uint256 public minTokensToSale = 45 * dec; // Company addresses address public TeamAndAdvisors; address public Investors; uint256 timeBonus1 = 20; uint256 timeBonus2 = 10; // Round bonuses uint256 bonus1 = 10; uint256 bonus2 = 15; uint256 bonus3 = 20; uint256 bonus4 = 30; // Amount bonuses uint256 amount1 = 500 * dec; uint256 amount2 = 1000 * dec; uint256 amount3 = 5000 * dec; uint256 amount4 = 10000 * dec; bool initalMinted = false; bool checkBonus = false; function Crowdsale( address _token, uint256 _startTimeRound1, // 1520121600 - 03/04/2018 @ 12:00am (UTC) uint256 _startTimeRound2, // 1521417600 - 03/19/2018 @ 12:00am (UTC) uint256 _endTimeRound1, // 1521417600 - 03/19/2018 @ 12:00am (UTC) uint256 _endTimeRound2, // 1525305600 - 05/03/2018 @ 12:00am (UTC) address _wallet, address _TeamAndAdvisors, address _Investors) public { require(_token != address(0)); require(_endTimeRound1 > _startTimeRound1); require(_endTimeRound2 > _startTimeRound2); require(_wallet != address(0)); require(_TeamAndAdvisors != address(0)); require(_Investors != address(0)); token = AlttexToken(_token); startTimeRound1 = _startTimeRound1; startTimeRound2 = _startTimeRound2; endTimeRound1 = _endTimeRound1; endTimeRound2 = _endTimeRound2; wallet = _wallet; TeamAndAdvisors = _TeamAndAdvisors; Investors = _Investors; } function initialMint() onlyOwner public { require(!initalMinted); uint256 _initialRaised = 17472 * 10 ** 16; uint256 _tokens = _initialRaised.mul(1500).div(10 ** 10); token.mint(Investors, _tokens.add(_tokens.mul(40).div(100))); initalMinted = true; } modifier saleIsOn() { uint tokenSupply = token.totalSupply(); require(now > startTimeRound1 && now < endTimeRound2); require(tokenSupply <= tokensToSale); _; } function setPercentTokensToSale( uint256 _newPercentTokensToSale) onlyOwner public { percentTokensToSale = _newPercentTokensToSale; } function setMinTokensToSale( uint256 _newMinTokensToSale) onlyOwner public { minTokensToSale = _newMinTokensToSale; } function setCheckBonus( bool _newCheckBonus) onlyOwner public { checkBonus = _newCheckBonus; } function setAmount( uint256 _newAmount1, uint256 _newAmount2, uint256 _newAmount3, uint256 _newAmount4) onlyOwner public { amount1 = _newAmount1; amount2 = _newAmount2; amount3 = _newAmount3; amount4 = _newAmount4; } function setBonuses( uint256 _newBonus1, uint256 _newBonus2, uint256 _newBonus3, uint256 _newBonus4) onlyOwner public { bonus1 = _newBonus1; bonus2 = _newBonus2; bonus3 = _newBonus3; bonus4 = _newBonus4; } function setRoundTime( uint256 _newStartTimeRound2, uint256 _newEndTimeRound2) onlyOwner public { require(_newEndTimeRound2 > _newStartTimeRound2); startTimeRound2 = _newStartTimeRound2; endTimeRound2 = _newEndTimeRound2; } function setRate(uint256 _newRateRound2) public onlyOwner { rateRound2 = _newRateRound2; } function setTimeBonus(uint256 _newTimeBonus) public onlyOwner { timeBonus2 = _newTimeBonus; } function setTeamAddress( address _newTeamAndAdvisors, address _newInvestors, address _newWallet) onlyOwner public { require(_newTeamAndAdvisors != address(0)); require(_newInvestors != address(0)); require(_newWallet != address(0)); TeamAndAdvisors = _newTeamAndAdvisors; Investors = _newInvestors; wallet = _newWallet; } function getAmount(uint256 _value) internal view returns (uint256) { uint256 amount = 0; uint256 all = 100; uint256 tokenSupply = token.totalSupply(); if(now >= startTimeRound1 && now < endTimeRound1) { // Round 1 amount = _value.mul(rateRound1); amount = amount.add(amount.mul(timeBonus1).div(all)); } else if(now >= startTimeRound2 && now < endTimeRound2) { // Round 2 amount = _value.mul(rateRound2); amount = amount.add(amount.mul(timeBonus2).div(all)); } require(amount >= minTokensToSale); require(amount != 0 && amount.add(tokenSupply) < tokensToSale); return amount; } function getBonus(uint256 _value) internal view returns (uint256) { if(_value >= amount1 && _value < amount2) { return bonus1; } else if(_value >= amount2 && _value < amount3) { return bonus2; } else if(_value >= amount3 && _value < amount4) { return bonus3; } else if(_value >= amount4) { return bonus4; } } /** * events 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); event TokenPartners(address indexed purchaser, address indexed beneficiary, uint256 amount); function buyTokens(address beneficiary) saleIsOn public payable { require(beneficiary != address(0)); uint256 weiAmount = (msg.value).div(10 ** 10); // calculate token amount to be created uint256 tokens = getAmount(weiAmount); if(checkBonus) { uint256 bonusNow = getBonus(tokens); tokens = tokens.add(tokens.mul(bonusNow).div(100)); } weiRaised = weiRaised.add(msg.value); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); wallet.transfer(msg.value); uint256 taaTokens = tokens.mul(20).div(100); token.mint(TeamAndAdvisors, taaTokens); TokenPartners(msg.sender, TeamAndAdvisors, taaTokens); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // @return true if tokensale event has ended function hasEnded() public view returns (bool) { return now > endTimeRound2; } function kill() onlyOwner public { selfdestruct(owner); } }
return true if tokensale event has ended
function hasEnded() public view returns (bool) { return now > endTimeRound2; }
897,287
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol
remove an address' access to this role/
function remove(Role storage _role, address _addr) internal { require(has(_role, _addr), "Roles: addr do not have role"); _role.bearer[_addr] = false; }
8,114,037
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.15; /** * @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; // assert(a == b * c + a % b); // There is no case in which this doesn'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 Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) 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) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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. */ function Ownable() { 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) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title UintUtil /// @author Daniel Wang - <daniel@loopring.org> /// @dev uint utility functions library UintLib { using SafeMath for uint; function tolerantSub(uint x, uint y) constant returns (uint z) { if (x >= y) z = x - y; else z = 0; } function next(uint i, uint size) internal constant returns (uint) { return (i + 1) % size; } function prev(uint i, uint size) internal constant returns (uint) { return (i + size - 1) % size; } /// @dev calculate the square of Coefficient of Variation (CV) /// https://en.wikipedia.org/wiki/Coefficient_of_variation function cvsquare( uint[] arr, uint scale ) internal constant returns (uint) { uint len = arr.length; require(len > 1); require(scale > 0); uint avg = 0; for (uint i = 0; i < len; i++) { avg += arr[i]; } avg = avg.div(len); if (avg == 0) { return 0; } uint cvs = 0; for (i = 0; i < len; i++) { uint sub = 0; if (arr[i] > avg) { sub = arr[i] - avg; } else { sub = avg - arr[i]; } cvs += sub.mul(sub); } return cvs .mul(scale) .div(avg) .mul(scale) .div(avg) .div(len - 1); } } /// @title Token Register Contract /// @author Kongliang Zhong - <kongliang@loopring.org>, /// @author Daniel Wang - <daniel@loopring.org>. library Uint8Lib { function xorReduce( uint8[] arr, uint len ) public constant returns (uint8 res) { res = arr[0]; for (uint i = 1; i < len; i++) { res ^= arr[i]; } } } /// @title Token Register Contract /// @author Daniel Wang - <daniel@loopring.org>. library ErrorLib { event Error(string message); /// @dev Check if condition hold, if not, log an exception and revert. function orThrow(bool condition, string message) public constant { if (!condition) { error(message); } } function error(string message) public constant { Error(message); revert(); } } /// @title Token Register Contract /// @author Kongliang Zhong - <kongliang@loopring.org>, /// @author Daniel Wang - <daniel@loopring.org>. library Bytes32Lib { function xorReduce( bytes32[] arr, uint len ) public constant returns (bytes32 res) { res = arr[0]; for (uint i = 1; i < len; i++) { res = _xor(res, arr[i]); } } function _xor( bytes32 bs1, bytes32 bs2 ) public constant returns (bytes32 res) { bytes memory temp = new bytes(32); for (uint i = 0; i < 32; i++) { temp[i] = bs1[i] ^ bs2[i]; } string memory str = string(temp); assembly { res := mload(add(str, 32)) } } } /// @title Token Register Contract /// @author Kongliang Zhong - <kongliang@loopring.org>, /// @author Daniel Wang - <daniel@loopring.org>. contract TokenRegistry is Ownable { address[] public tokens; mapping (string => address) tokenSymbolMap; function registerToken(address _token, string _symbol) public onlyOwner { require(_token != address(0)); require(!isTokenRegisteredBySymbol(_symbol)); require(!isTokenRegistered(_token)); tokens.push(_token); tokenSymbolMap[_symbol] = _token; } function unregisterToken(address _token, string _symbol) public onlyOwner { require(tokenSymbolMap[_symbol] == _token); delete tokenSymbolMap[_symbol]; for (uint i = 0; i < tokens.length; i++) { if (tokens[i] == _token) { tokens[i] == tokens[tokens.length - 1]; tokens.length --; break; } } } function isTokenRegisteredBySymbol(string symbol) public constant returns (bool) { return tokenSymbolMap[symbol] != address(0); } function isTokenRegistered(address _token) public constant returns (bool) { for (uint i = 0; i < tokens.length; i++) { if (tokens[i] == _token) { return true; } } return false; } function getAddressBySymbol(string symbol) public constant returns (address) { return tokenSymbolMap[symbol]; } } /// @title TokenTransferDelegate - Acts as a middle man to transfer ERC20 tokens /// on behalf of different versioned of Loopring protocol to avoid ERC20 /// re-authorization. /// @author Daniel Wang - <daniel@loopring.org>. contract TokenTransferDelegate is Ownable { using Math for uint; //////////////////////////////////////////////////////////////////////////// /// Variables /// //////////////////////////////////////////////////////////////////////////// uint lastVersion = 0; address[] public versions; mapping (address => uint) public versioned; //////////////////////////////////////////////////////////////////////////// /// Modifiers /// //////////////////////////////////////////////////////////////////////////// modifier isVersioned(address addr) { if (versioned[addr] == 0) { revert(); } _; } modifier notVersioned(address addr) { if (versioned[addr] > 0) { revert(); } _; } //////////////////////////////////////////////////////////////////////////// /// Events /// //////////////////////////////////////////////////////////////////////////// event VersionAdded(address indexed addr, uint version); event VersionRemoved(address indexed addr, uint version); //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Add a Loopring protocol address. /// @param addr A loopring protocol address. function addVersion(address addr) onlyOwner notVersioned(addr) { versioned[addr] = ++lastVersion; versions.push(addr); VersionAdded(addr, lastVersion); } /// @dev Remove a Loopring protocol address. /// @param addr A loopring protocol address. function removeVersion(address addr) onlyOwner isVersioned(addr) { uint version = versioned[addr]; delete versioned[addr]; uint length = versions.length; for (uint i = 0; i < length; i++) { if (versions[i] == addr) { versions[i] = versions[length - 1]; versions.length -= 1; break; } } VersionRemoved(addr, version); } /// @return Amount of ERC20 token that can be spent by this contract. /// @param tokenAddress Address of token to transfer. /// @param _owner Address of the token owner. function getSpendable( address tokenAddress, address _owner ) isVersioned(msg.sender) constant returns (uint) { var token = ERC20(tokenAddress); return token .allowance(_owner, address(this)) .min256(token.balanceOf(_owner)); } /// @dev Invoke ERC20 transferFrom method. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. /// @return Tansfer result. function transferToken( address token, address from, address to, uint value) isVersioned(msg.sender) returns (bool) { return ERC20(token).transferFrom(from, to, value); } /// @dev Gets all versioned addresses. /// @return Array of versioned addresses. function getVersions() constant returns (address[]) { return versions; } } contract RinghashRegistry { using Bytes32Lib for bytes32[]; using ErrorLib for bool; using Uint8Lib for uint8[]; uint public blocksToLive; struct Submission { address feeRecepient; uint block; } mapping (bytes32 => Submission) submissions; function RinghashRegistry(uint _blocksToLive) public { require(_blocksToLive > 0); blocksToLive = _blocksToLive; } function submitRinghash( uint ringSize, address feeRecepient, // bool throwIfLRCIsInsuffcient, uint8[] vList, bytes32[] rList, bytes32[] sList) public { bytes32 ringhash = calculateRinghash( ringSize, // feeRecepient, // throwIfLRCIsInsuffcient, vList, rList, sList); canSubmit(ringhash, feeRecepient) .orThrow("Ringhash submitted"); submissions[ringhash] = Submission(feeRecepient, block.number); } function canSubmit( bytes32 ringhash, address feeRecepient ) public constant returns (bool) { var submission = submissions[ringhash]; return (submission.feeRecepient == address(0) || submission.block + blocksToLive < block.number || submission.feeRecepient == feeRecepient); } /// @return True if a ring's hash has ever been submitted; false otherwise. function ringhashFound(bytes32 ringhash) public constant returns (bool) { return submissions[ringhash].feeRecepient != address(0); } /// @dev Calculate the hash of a ring. function calculateRinghash( uint ringSize, // address feeRecepient, // bool throwIfLRCIsInsuffcient, uint8[] vList, bytes32[] rList, bytes32[] sList ) public constant returns (bytes32) { (ringSize == vList.length - 1 && ringSize == rList.length - 1 && ringSize == sList.length - 1) .orThrow("invalid ring data"); return keccak256( // feeRecepient, // throwIfLRCIsInsuffcient, vList.xorReduce(ringSize), rList.xorReduce(ringSize), sList.xorReduce(ringSize)); } } /// @title Loopring Token Exchange Protocol Contract Interface /// @author Daniel Wang - <daniel@loopring.org> /// @author Kongliang Zhong - <kongliang@loopring.org> contract LoopringProtocol { //////////////////////////////////////////////////////////////////////////// /// Constants /// //////////////////////////////////////////////////////////////////////////// uint public constant FEE_SELECT_LRC = 0; uint public constant FEE_SELECT_MARGIN_SPLIT = 1; uint public constant FEE_SELECT_MAX_VALUE = 1; uint public constant MARGIN_SPLIT_PERCENTAGE_BASE = 10000; //////////////////////////////////////////////////////////////////////////// /// Structs /// //////////////////////////////////////////////////////////////////////////// /// @param tokenS Token to sell. /// @param tokenB Token to buy. /// @param amountS Maximum amount of tokenS to sell. /// @param amountB Minimum amount of tokenB to buy if all amountS sold. /// @param timestamp Indicating whtn this order is created/signed. /// @param ttl Indicating after how many seconds from `timestamp` /// this order will expire. /// @param salt A random number to make this order's hash unique. /// @param lrcFee Max amount of LRC to pay for miner. The real amount /// to pay is proportional to fill amount. /// @param buyNoMoreThanAmountB - /// If true, this order does not accept buying more /// than `amountB`. /// @param marginSplitPercentage - /// The percentage of margin paid to miner. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. struct Order { address owner; address tokenS; address tokenB; uint amountS; uint amountB; uint timestamp; uint ttl; uint salt; uint lrcFee; bool buyNoMoreThanAmountB; uint8 marginSplitPercentage; uint8 v; bytes32 r; bytes32 s; } //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Submit a order-ring for validation and settlement. /// @param addressList List of each order's owner and tokenS. Note that next /// order's `tokenS` equals this order's `tokenB`. /// @param uintArgsList List of uint-type arguments in this order: /// amountS, AmountB, rateAmountS, timestamp, ttl, salt, /// and lrcFee. /// @param uint8ArgsList - /// List of unit8-type arguments, in this order: /// marginSplitPercentageList, feeSelectionList. /// @param vList List of v for each order. This list is 1-larger than /// the previous lists, with the last element being the /// v value of the ring signature. /// @param rList List of r for each order. This list is 1-larger than /// the previous lists, with the last element being the /// r value of the ring signature. /// @param sList List of s for each order. This list is 1-larger than /// the previous lists, with the last element being the /// s value of the ring signature. /// @param ringminer The address that signed this tx. /// @param feeRecepient The recepient address for fee collection. If this is /// '0x0', all fees will be paid to the address who had /// signed this transaction, not `msg.sender`. Noted if /// LRC need to be paid back to order owner as the result /// of fee selection model, LRC will also be sent from /// this address. /// @param throwIfLRCIsInsuffcient - /// If true, throw exception if any order's spendable /// LRC amount is smaller than requried; if false, ring- /// minor will give up collection the LRC fee. function submitRing( address[2][] addressList, uint[7][] uintArgsList, uint8[2][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, address ringminer, address feeRecepient, bool throwIfLRCIsInsuffcient ) public; /// @dev Cancel a order. cancel amount(amountS or amountB) can be specified /// in orderValues. /// @param addresses owner, tokenS, tokenB /// @param orderValues amountS, amountB, timestamp, ttl, salt, lrcFee, /// cancelAmountS, and cancelAmountB. /// @param marginSplitPercentage - /// @param buyNoMoreThanAmountB - /// @param v Order ECDSA signature parameter v. /// @param r Order ECDSA signature parameters r. /// @param s Order ECDSA signature parameters s. function cancelOrder( address[3] addresses, uint[7] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) public; /// @dev Set a cutoff timestamp to invalidate all orders whose timestamp /// is smaller than or equal to the new value of the address's cutoff /// timestamp. /// @param cutoff The cutoff timestamp, will default to `block.timestamp` /// if it is 0. function setCutoff(uint cutoff) public; } /// @title Loopring Token Exchange Protocol Implementation Contract v1 /// @author Daniel Wang - <daniel@loopring.org>, /// @author Kongliang Zhong - <kongliang@loopring.org> contract LoopringProtocolImpl is LoopringProtocol { using ErrorLib for bool; using Math for uint; using SafeMath for uint; using UintLib for uint; //////////////////////////////////////////////////////////////////////////// /// Variables /// //////////////////////////////////////////////////////////////////////////// address public lrcTokenAddress = address(0); address public tokenRegistryAddress = address(0); address public ringhashRegistryAddress = address(0); address public delegateAddress = address(0); uint public maxRingSize = 0; uint public ringIndex = 0; bool private entered = false; // Exchange rate (rate) is the amount to sell or sold divided by the amount // to buy or bought. // // Rate ratio is the ratio between executed rate and an order's original // rate. // // To require all orders' rate ratios to have coefficient ofvariation (CV) // smaller than 2.5%, for an example , rateRatioCVSThreshold should be: // `(0.025 * RATE_RATIO_SCALE)^2` or 62500. uint public rateRatioCVSThreshold = 0; uint public constant RATE_RATIO_SCALE = 10000; // The following two maps are used to keep trace of order fill and // cancellation history. mapping (bytes32 => uint) public filled; mapping (bytes32 => uint) public cancelled; // A map from address to its cutoff timestamp. mapping (address => uint) public cutoffs; //////////////////////////////////////////////////////////////////////////// /// Structs /// //////////////////////////////////////////////////////////////////////////// /// @param order The original order /// @param feeSelection - /// A miner-supplied value indicating if LRC (value = 0) /// or margin split is choosen by the miner (value = 1). /// We may support more fee model in the future. /// @param fillAmountS Amount of tokenS to sell, calculated by protocol. /// @param rateAmountS This value is initially provided by miner and is /// calculated by based on the original information of /// all orders of the order-ring, in other orders, this /// value is independent of the order's current state. /// This value and `rateAmountB` can be used to calculate /// the proposed exchange rate calculated by miner. /// @param lrcReward The amount of LRC paid by miner to order owner in /// exchange for margin split. /// @param lrcFee The amount of LR paid by order owner to miner. /// @param splitS TokenS paid to miner. /// @param splitB TokenB paid to miner. struct OrderState { Order order; bytes32 orderHash; uint8 feeSelection; uint rateAmountS; uint availableAmountS; uint fillAmountS; uint lrcReward; uint lrcFee; uint splitS; uint splitB; } struct Ring { bytes32 ringhash; OrderState[] orders; address miner; address feeRecepient; bool throwIfLRCIsInsuffcient; } //////////////////////////////////////////////////////////////////////////// /// Events /// //////////////////////////////////////////////////////////////////////////// event RingMined( uint _ringIndex, uint _time, uint _blocknumber, bytes32 indexed _ringhash, address indexed _miner, address indexed _feeRecepient, bool _ringhashFound); event OrderFilled( uint _ringIndex, uint _time, uint _blocknumber, bytes32 indexed _ringhash, bytes32 _prevOrderHash, bytes32 indexed _orderHash, bytes32 _nextOrderHash, uint _amountS, uint _amountB, uint _lrcReward, uint _lrcFee); event OrderCancelled( uint _time, uint _blocknumber, bytes32 indexed _orderHash, uint _amountCancelled); event CutoffTimestampChanged( uint _time, uint _blocknumber, address indexed _address, uint _cutoff); //////////////////////////////////////////////////////////////////////////// /// Constructor /// //////////////////////////////////////////////////////////////////////////// function LoopringProtocolImpl( address _lrcTokenAddress, address _tokenRegistryAddress, address _ringhashRegistryAddress, address _delegateAddress, uint _maxRingSize, uint _rateRatioCVSThreshold ) public { require(address(0) != _lrcTokenAddress); require(address(0) != _tokenRegistryAddress); require(address(0) != _delegateAddress); require(_maxRingSize > 1); require(_rateRatioCVSThreshold > 0); lrcTokenAddress = _lrcTokenAddress; tokenRegistryAddress = _tokenRegistryAddress; ringhashRegistryAddress = _ringhashRegistryAddress; delegateAddress = _delegateAddress; maxRingSize = _maxRingSize; rateRatioCVSThreshold = _rateRatioCVSThreshold; } //////////////////////////////////////////////////////////////////////////// /// Public Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Disable default function. function () payable { revert(); } /// @dev Submit a order-ring for validation and settlement. /// @param addressList List of each order's tokenS. Note that next order's /// `tokenS` equals this order's `tokenB`. /// @param uintArgsList List of uint-type arguments in this order: /// amountS, amountB, timestamp, ttl, salt, lrcFee, /// rateAmountS. /// @param uint8ArgsList - /// List of unit8-type arguments, in this order: /// marginSplitPercentageList,feeSelectionList. /// @param vList List of v for each order. This list is 1-larger than /// the previous lists, with the last element being the /// v value of the ring signature. /// @param rList List of r for each order. This list is 1-larger than /// the previous lists, with the last element being the /// r value of the ring signature. /// @param sList List of s for each order. This list is 1-larger than /// the previous lists, with the last element being the /// s value of the ring signature. /// @param ringminer The address that signed this tx. /// @param feeRecepient The recepient address for fee collection. If this is /// '0x0', all fees will be paid to the address who had /// signed this transaction, not `msg.sender`. Noted if /// LRC need to be paid back to order owner as the result /// of fee selection model, LRC will also be sent from /// this address. /// @param throwIfLRCIsInsuffcient - /// If true, throw exception if any order's spendable /// LRC amount is smaller than requried; if false, ring- /// minor will give up collection the LRC fee. function submitRing( address[2][] addressList, uint[7][] uintArgsList, uint8[2][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, address ringminer, address feeRecepient, bool throwIfLRCIsInsuffcient ) public { (!entered).orThrow("attepted to re-ent submitRing function"); entered = true; //Check ring size uint ringSize = addressList.length; (ringSize > 1 && ringSize <= maxRingSize) .orThrow("invalid ring size"); verifyInputDataIntegrity( ringSize, addressList, uintArgsList, uint8ArgsList, buyNoMoreThanAmountBList, vList, rList, sList); verifyTokensRegistered(addressList); var ringhashRegistry = RinghashRegistry(ringhashRegistryAddress); bytes32 ringhash = ringhashRegistry.calculateRinghash( ringSize, // feeRecepient, // throwIfLRCIsInsuffcient, vList, rList, sList ); ringhashRegistry.canSubmit(ringhash, feeRecepient) .orThrow("Ring claimed by others"); verifySignature( ringminer, ringhash, vList[ringSize], rList[ringSize], sList[ringSize] ); // Assemble input data into a struct so we can pass it to functions. var orders = assembleOrders( ringSize, addressList, uintArgsList, uint8ArgsList, buyNoMoreThanAmountBList, vList, rList, sList); if (feeRecepient == address(0)) { feeRecepient = ringminer; } handleRing( ringhash, orders, ringminer, feeRecepient, throwIfLRCIsInsuffcient ); entered = true; } /// @dev Cancel a order. Amount (amountS or amountB) to cancel can be /// specified using orderValues. /// @param addresses owner, tokenS, tokenB /// @param orderValues amountS, amountB, timestamp, ttl, salt, /// lrcFee, and cancelAmount /// @param buyNoMoreThanAmountB - /// If true, this order does not accept buying /// more than `amountB`. /// @param marginSplitPercentage - /// The percentage of margin paid to miner. /// @param v Order ECDSA signature parameter v. /// @param r Order ECDSA signature parameters r. /// @param s Order ECDSA signature parameters s. function cancelOrder( address[3] addresses, uint[7] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) public { uint cancelAmount = orderValues[6]; (cancelAmount > 0).orThrow("amount to cancel is zero"); var order = Order( addresses[0], addresses[1], addresses[2], orderValues[0], orderValues[1], orderValues[2], orderValues[3], orderValues[4], orderValues[5], buyNoMoreThanAmountB, marginSplitPercentage, v, r, s ); bytes32 orderHash = calculateOrderHash(order); cancelled[orderHash] = cancelled[orderHash].add(cancelAmount); OrderCancelled( block.timestamp, block.number, orderHash, cancelAmount ); } /// @dev Set a cutoff timestamp to invalidate all orders whose timestamp /// is smaller than or equal to the new value of the address's cutoff /// timestamp. /// @param cutoff The cutoff timestamp, will default to `block.timestamp` /// if it is 0. function setCutoff(uint cutoff) public { uint t = cutoff; if (t == 0) { t = block.timestamp; } (cutoffs[msg.sender] < t) .orThrow("attempted to set cutoff to a smaller value"); cutoffs[msg.sender] = t; CutoffTimestampChanged( block.timestamp, block.number, msg.sender, t ); } //////////////////////////////////////////////////////////////////////////// /// Internal & Private Functions /// //////////////////////////////////////////////////////////////////////////// /// @dev Validate a ring. function verifyRingHasNoSubRing(Ring ring) internal constant { uint ringSize = ring.orders.length; // Check the ring has no sub-ring. for (uint i = 0; i < ringSize -1; i++) { address tokenS = ring.orders[i].order.tokenS; for (uint j = i + 1; j < ringSize; j++){ (tokenS != ring.orders[j].order.tokenS) .orThrow("found sub-ring"); } } } function verifyTokensRegistered(address[2][] addressList) internal constant { var registryContract = TokenRegistry(tokenRegistryAddress); for (uint i = 0; i < addressList.length; i++) { registryContract.isTokenRegistered(addressList[i][1]) .orThrow("token not registered"); } } function handleRing( bytes32 ringhash, OrderState[] orders, address miner, address feeRecepient, bool throwIfLRCIsInsuffcient ) internal { var ring = Ring( ringhash, orders, miner, feeRecepient, throwIfLRCIsInsuffcient); // Do the hard work. verifyRingHasNoSubRing(ring); // Exchange rates calculation are performed by ring-miners as solidity // cannot get power-of-1/n operation, therefore we have to verify // these rates are correct. verifyMinerSuppliedFillRates(ring); // Scale down each order independently by substracting amount-filled and // amount-cancelled. Order owner's current balance and allowance are // not taken into consideration in these operations. scaleRingBasedOnHistoricalRecords(ring); // Based on the already verified exchange rate provided by ring-miners, // we can furthur scale down orders based on token balance and allowance, // then find the smallest order of the ring, then calculate each order's // `fillAmountS`. calculateRingFillAmount(ring); // Calculate each order's `lrcFee` and `lrcRewrard` and splict how much // of `fillAmountS` shall be paid to matching order or miner as margin // split. calculateRingFees(ring); /// Make payments. settleRing(ring); RingMined( ringIndex++, block.timestamp, block.number, ring.ringhash, ring.miner, ring.feeRecepient, RinghashRegistry(ringhashRegistryAddress).ringhashFound(ring.ringhash) ); } function settleRing(Ring ring) internal { uint ringSize = ring.orders.length; var delegate = TokenTransferDelegate(delegateAddress); for (uint i = 0; i < ringSize; i++) { var state = ring.orders[i]; var prev = ring.orders[i.prev(ringSize)]; var next = ring.orders[i.next(ringSize)]; // Pay tokenS to previous order, or to miner as previous order's // margin split or/and this order's margin split. delegate.transferToken( state.order.tokenS, state.order.owner, prev.order.owner, state.fillAmountS - prev.splitB); if (prev.splitB + state.splitS > 0) { delegate.transferToken( state.order.tokenS, state.order.owner, ring.feeRecepient, prev.splitB + state.splitS); } // Pay LRC if (state.lrcReward > 0) { delegate.transferToken( lrcTokenAddress, ring.feeRecepient, state.order.owner, state.lrcReward); } if (state.lrcFee > 0) { delegate.transferToken( lrcTokenAddress, state.order.owner, ring.feeRecepient, state.lrcFee); } // Update fill records if (state.order.buyNoMoreThanAmountB) { filled[state.orderHash] += next.fillAmountS; } else { filled[state.orderHash] += state.fillAmountS; } OrderFilled( ringIndex, block.timestamp, block.number, ring.ringhash, prev.orderHash, state.orderHash, next.orderHash, state.fillAmountS + state.splitS, next.fillAmountS - state.splitB, state.lrcReward, state.lrcFee ); } } function verifyMinerSuppliedFillRates(Ring ring) internal constant { var orders = ring.orders; uint ringSize = orders.length; uint[] memory rateRatios = new uint[](ringSize); for (uint i = 0; i < ringSize; i++) { uint rateAmountB = orders[i.next(ringSize)].rateAmountS; uint s1b0 = orders[i].rateAmountS.mul(orders[i].order.amountB); uint s0b1 = orders[i].order.amountS.mul(rateAmountB); (s1b0 <= s0b1) .orThrow("miner supplied exchange rate provides invalid discount"); rateRatios[i] = RATE_RATIO_SCALE.mul(s1b0).div(s0b1); } uint cvs = UintLib.cvsquare(rateRatios, RATE_RATIO_SCALE); (cvs <= rateRatioCVSThreshold) .orThrow("miner supplied exchange rate is not evenly discounted"); } function calculateRingFees(Ring ring) internal constant { uint minerLrcSpendable = getLRCSpendable(ring.feeRecepient); uint ringSize = ring.orders.length; for (uint i = 0; i < ringSize; i++) { var state = ring.orders[i]; var next = ring.orders[i.next(ringSize)]; if (state.feeSelection == FEE_SELECT_LRC) { uint lrcSpendable = getLRCSpendable(state.order.owner); if (lrcSpendable < state.lrcFee) { (!ring.throwIfLRCIsInsuffcient) .orThrow("order LRC balance insuffcient"); state.lrcFee = lrcSpendable; minerLrcSpendable += lrcSpendable; } } else if (state.feeSelection == FEE_SELECT_MARGIN_SPLIT) { if (minerLrcSpendable >= state.lrcFee) { if (state.order.buyNoMoreThanAmountB) { uint splitS = next.fillAmountS .mul(state.order.amountS) .div(state.order.amountB) .sub(state.fillAmountS); state.splitS = splitS .mul(state.order.marginSplitPercentage) .div(MARGIN_SPLIT_PERCENTAGE_BASE); } else { uint splitB = next.fillAmountS.sub( state.fillAmountS .mul(state.order.amountB) .div(state.order.amountS)); state.splitB = splitB .mul(state.order.marginSplitPercentage) .div(MARGIN_SPLIT_PERCENTAGE_BASE); } // This implicits order with smaller index in the ring will // be paid LRC reward first, so the orders in the ring does // mater. if (state.splitS > 0 || state.splitB > 0) { minerLrcSpendable = minerLrcSpendable.sub(state.lrcFee); state.lrcReward = state.lrcFee; } state.lrcFee = 0; } } else { ErrorLib.error("unsupported fee selection value"); } } } function calculateRingFillAmount(Ring ring) internal constant { uint ringSize = ring.orders.length; uint smallestIdx = 0; uint i; uint j; for (i = 0; i < ringSize; i++) { j = i.next(ring.orders.length); uint res = calculateOrderFillAmount( ring.orders[i], ring.orders[j]); if (res == 1) smallestIdx = i; else if (res == 2) smallestIdx = j; } for (i = 0; i < smallestIdx; i++) { j = i.next(ring.orders.length); (calculateOrderFillAmount(ring.orders[i], ring.orders[j]) == 0) .orThrow("unexpected exception in calculateRingFillAmount"); } } /// @return 0 if neither order is the smallest one; /// 1 if 'state' is the smallest order; /// 2 if 'next' is the smallest order. function calculateOrderFillAmount( OrderState state, OrderState next ) internal constant returns (uint state2IsSmaller) { // Update the amount of tokenB this order can buy, whose logic could be // a brain-burner: // We have `fillAmountB / state.fillAmountS = state.rateAmountB / state.rateAmountS`, // therefore, `fillAmountB = state.rateAmountB * state.fillAmountS / state.rateAmountS`, // therefore `fillAmountB = next.rateAmountS * state.fillAmountS / state.rateAmountS`, uint fillAmountB = next.rateAmountS .mul(state.fillAmountS) .div(state.rateAmountS); if (state.order.buyNoMoreThanAmountB) { if (fillAmountB > state.order.amountB) { fillAmountB = state.order.amountB; state.fillAmountS = state.rateAmountS .mul(fillAmountB) .div(next.rateAmountS); state2IsSmaller = 1; } state.lrcFee = state.order.lrcFee .mul(fillAmountB) .div(next.order.amountS); } else { state.lrcFee = state.order.lrcFee .mul(state.fillAmountS) .div(state.order.amountS); } if (fillAmountB <= next.fillAmountS) { next.fillAmountS = fillAmountB; } else { state2IsSmaller = 2; } } /// @dev Scale down all orders based on historical fill or cancellation /// stats but key the order's original exchange rate. function scaleRingBasedOnHistoricalRecords(Ring ring) internal constant { uint ringSize = ring.orders.length; for (uint i = 0; i < ringSize; i++) { var state = ring.orders[i]; var order = state.order; if (order.buyNoMoreThanAmountB) { uint amountB = order.amountB .sub(filled[state.orderHash]) .tolerantSub(cancelled[state.orderHash]); order.amountS = amountB.mul(order.amountS).div(order.amountB); order.lrcFee = amountB.mul(order.lrcFee).div(order.amountB); order.amountB = amountB; } else { uint amountS = order.amountS .sub(filled[state.orderHash]) .tolerantSub(cancelled[state.orderHash]); order.amountB = amountS.mul(order.amountB).div(order.amountS); order.lrcFee = amountS.mul(order.lrcFee).div(order.amountS); order.amountS = amountS; } (order.amountS > 0).orThrow("amountS is zero"); (order.amountB > 0).orThrow("amountB is zero"); state.fillAmountS = order.amountS.min256(state.availableAmountS); } } /// @return Amount of ERC20 token that can be spent by this contract. function getSpendable( address tokenAddress, address tokenOwner ) internal constant returns (uint) { return TokenTransferDelegate(delegateAddress) .getSpendable(tokenAddress, tokenOwner); } /// @return Amount of LRC token that can be spent by this contract. function getLRCSpendable(address tokenOwner) internal constant returns (uint) { return getSpendable(lrcTokenAddress, tokenOwner); } /// @dev verify input data's basic integrity. function verifyInputDataIntegrity( uint ringSize, address[2][] addressList, uint[7][] uintArgsList, uint8[2][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList ) internal constant { (ringSize == addressList.length) .orThrow("ring data is inconsistent - addressList"); (ringSize == uintArgsList.length) .orThrow("ring data is inconsistent - uintArgsList"); (ringSize == uint8ArgsList.length) .orThrow("ring data is inconsistent - uint8ArgsList"); (ringSize == buyNoMoreThanAmountBList.length) .orThrow("ring data is inconsistent - buyNoMoreThanAmountBList"); (ringSize + 1 == vList.length) .orThrow("ring data is inconsistent - vList"); (ringSize + 1 == rList.length) .orThrow("ring data is inconsistent - rList"); (ringSize + 1 == sList.length) .orThrow("ring data is inconsistent - sList"); // Validate ring-mining related arguments. for (uint i = 0; i < ringSize; i++) { (uintArgsList[i][5] > 0).orThrow("order rateAmountS is zero"); (uint8ArgsList[i][1] <= FEE_SELECT_MAX_VALUE).orThrow("invalid order fee selection "); } } /// @dev assmble order parameters into Order struct. /// @return A list of orders. function assembleOrders( uint ringSize, address[2][] addressList, uint[7][] uintArgsList, uint8[2][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList ) internal constant returns (OrderState[]) { var orders = new OrderState[](ringSize); for (uint i = 0; i < ringSize; i++) { uint j = i.prev(ringSize); var order = Order( addressList[i][0], addressList[i][1], addressList[j][1], uintArgsList[i][0], uintArgsList[i][1], uintArgsList[i][2], uintArgsList[i][3], uintArgsList[i][4], uintArgsList[i][5], buyNoMoreThanAmountBList[i], uint8ArgsList[i][0], vList[i], rList[i], sList[i]); bytes32 orderHash = calculateOrderHash(order); verifySignature( order.owner, orderHash, order.v, order.r, order.s); validateOrder(order); orders[i] = OrderState( order, orderHash, uint8ArgsList[i][1], // feeSelection uintArgsList[i][6], // rateAmountS getSpendable(order.tokenS, order.owner), 0, // fillAmountS 0, // lrcReward 0, // lrcFee 0, // splitS 0 // splitB ); /* (orders[i].availableAmountS > 0) */ /* .orThrow("order balance is zero"); */ } return orders; } /// @dev validate order's parameters are OK. function validateOrder(Order order) internal constant { (order.owner != address(0)) .orThrow("invalid order owner"); (order.tokenS != address(0)) .orThrow("invalid order tokenS"); (order.tokenB != address(0)) .orThrow("invalid order tokenB"); (order.amountS > 0) .orThrow("invalid order amountS"); (order.amountB > 0) .orThrow("invalid order amountB"); (order.timestamp > cutoffs[order.owner]) .orThrow("order is cut off"); (order.ttl > 0) .orThrow("order ttl is 0"); (order.timestamp + order.ttl > block.timestamp) .orThrow("order is expired"); (order.salt > 0) .orThrow("invalid order salt"); (order.marginSplitPercentage <= MARGIN_SPLIT_PERCENTAGE_BASE) .orThrow("invalid order marginSplitPercentage"); } /// @dev Get the Keccak-256 hash of order with specified parameters. function calculateOrderHash(Order order) internal constant returns (bytes32) { return keccak256( address(this), order.tokenS, order.tokenB, order.amountS, order.amountB, order.timestamp, order.ttl, order.salt, order.lrcFee, order.buyNoMoreThanAmountB, order.marginSplitPercentage); } /// @return The signer's address. function verifySignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public constant { address addr = ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s); (signer == addr).orThrow("invalid signature"); } function getOrderFilled(bytes32 orderHash) public constant returns (uint) { return filled[orderHash]; } function getOrderCancelled(bytes32 orderHash) public constant returns (uint) { return cancelled[orderHash]; } }
/ Structs / order The original order feeSelection - A miner-supplied value indicating if LRC (value = 0) or margin split is choosen by the miner (value = 1). We may support more fee model in the future. fillAmountS Amount of tokenS to sell, calculated by protocol. rateAmountS This value is initially provided by miner and is calculated by based on the original information of all orders of the order-ring, in other orders, this value is independent of the order's current state. This value and `rateAmountB` can be used to calculate the proposed exchange rate calculated by miner. lrcReward The amount of LRC paid by miner to order owner in exchange for margin split. lrcFee The amount of LR paid by order owner to miner. splitS TokenS paid to miner. splitB TokenB paid to miner.
function submitRing( address[2][] addressList, uint[7][] uintArgsList, uint8[2][] uint8ArgsList, bool[] buyNoMoreThanAmountBList, uint8[] vList, bytes32[] rList, bytes32[] sList, address ringminer, address feeRecepient, bool throwIfLRCIsInsuffcient ) public; function cancelOrder( address[3] addresses, uint[7] orderValues, bool buyNoMoreThanAmountB, uint8 marginSplitPercentage, uint8 v, bytes32 r, bytes32 s ) public; function setCutoff(uint cutoff) public; } struct OrderState { Order order; bytes32 orderHash; uint8 feeSelection; uint rateAmountS; uint availableAmountS; uint fillAmountS; uint lrcReward; uint lrcFee; uint splitS; uint splitB; }
891,403
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './interfaces/IAtlantisV1Pool.sol'; import './interfaces/IAtlantisV1Factory.sol'; import './interfaces/IAtlantisV1PoolDeployer.sol'; import './interfaces/IERC20Minimal.sol'; import './interfaces/callback/IAtlantisV1MintCallback.sol'; import './interfaces/callback/IAtlantisV1SwapCallback.sol'; import './interfaces/callback/IAtlantisV1FlashCallback.sol'; import './NoDelegateCall.sol'; import './libraries/Tick.sol'; import './libraries/TickMath.sol'; import './libraries/Oracle.sol'; import './libraries/Position.sol'; import './libraries/SqrtPriceMath.sol'; import './libraries/TransferHelper.sol'; import './libraries/TickBitmap.sol'; contract AtlantisV1Pool is IAtlantisV1Pool, NoDelegateCall { using LowGasSafeMath for uint256; using LowGasSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; using Tick for mapping(int24 => Tick.Info); using TickBitmap for mapping(int16 => uint256); using Position for mapping(bytes32 => Position.Info); using Position for Position.Info; using Oracle for Oracle.Observation[65535]; /// @inheritdoc IAtlantisV1PoolImmutables address public immutable override factory; /// @inheritdoc IAtlantisV1PoolImmutables address public immutable override token0; /// @inheritdoc IAtlantisV1PoolImmutables address public immutable override token1; /// @inheritdoc IAtlantisV1PoolImmutables uint24 public immutable override fee; /// @inheritdoc IAtlantisV1PoolImmutables int24 public immutable override tickSpacing; /// @inheritdoc IAtlantisV1PoolImmutables uint128 public immutable override maxLiquidityPerTick; struct Slot0 { // the current price uint160 sqrtPriceX96; // the current tick int24 tick; // the most-recently updated index of the observations array uint16 observationIndex; // the current maximum number of observations that are being stored uint16 observationCardinality; // the next maximum number of observations to store, triggered in observations.write uint16 observationCardinalityNext; // the current protocol fee as a percentage of the swap fee taken on withdrawal // represented as an integer denominator (1/x)% uint8 feeProtocol; // whether the pool is locked bool unlocked; } /// @inheritdoc IAtlantisV1PoolState Slot0 public override slot0; /// @inheritdoc IAtlantisV1PoolState uint256 public override feeGrowthGlobal0X128; /// @inheritdoc IAtlantisV1PoolState uint256 public override feeGrowthGlobal1X128; // accumulated protocol fees in token0/token1 units struct ProtocolFees { uint128 token0; uint128 token1; } /// @inheritdoc IAtlantisV1PoolState ProtocolFees public override protocolFees; /// @inheritdoc IAtlantisV1PoolState uint128 public override liquidity; /// @inheritdoc IAtlantisV1PoolState mapping(int24 => Tick.Info) public override ticks; /// @inheritdoc IAtlantisV1PoolState mapping(int16 => uint256) public override tickBitmap; /// @inheritdoc IAtlantisV1PoolState mapping(bytes32 => Position.Info) public override positions; /// @inheritdoc IAtlantisV1PoolState Oracle.Observation[65535] public override observations; /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because /// we use balance checks to determine the payment status of interactions such as mint, swap and flash. modifier lock() { require(slot0.unlocked, 'LOK'); slot0.unlocked = false; _; slot0.unlocked = true; } modifier onlyFactoryOwner() { require(msg.sender == IAtlantisV1Factory(factory).owner()); _; } constructor() { int24 _tickSpacing; (factory, token0, token1, fee, _tickSpacing) = IAtlantisV1PoolDeployer(msg.sender).parameters(); tickSpacing = _tickSpacing; maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing); } /// @dev Common checks for valid tick inputs. function checkTicks(int24 tickLower, int24 tickUpper) private pure { require(tickLower < tickUpper, 'TLU'); require(tickLower >= TickMath.MIN_TICK, 'TLM'); require(tickUpper <= TickMath.MAX_TICK, 'TUM'); } /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. function _blockTimestamp() internal view virtual returns (uint32) { return uint32(block.timestamp); // truncation is desired } /// @dev Get the pool's balance of token0 /// @dev This function is gas optimized to avoid a redundant extcodesize check /// in addition to the returndatasize check function balance0() private view returns (uint256) { (bool success, bytes memory data) = token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))); require(success && data.length >= 32); return abi.decode(data, (uint256)); } /// @dev Get the pool's balance of token1 /// @dev This function is gas optimized to avoid a redundant extcodesize check /// in addition to the returndatasize check function balance1() private view returns (uint256) { (bool success, bytes memory data) = token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))); require(success && data.length >= 32); return abi.decode(data, (uint256)); } /// @inheritdoc IAtlantisV1PoolDerivedState function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view override noDelegateCall returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) { checkTicks(tickLower, tickUpper); int56 tickCumulativeLower; int56 tickCumulativeUpper; uint160 secondsPerLiquidityOutsideLowerX128; uint160 secondsPerLiquidityOutsideUpperX128; uint32 secondsOutsideLower; uint32 secondsOutsideUpper; { Tick.Info storage lower = ticks[tickLower]; Tick.Info storage upper = ticks[tickUpper]; bool initializedLower; (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = ( lower.tickCumulativeOutside, lower.secondsPerLiquidityOutsideX128, lower.secondsOutside, lower.initialized ); require(initializedLower); bool initializedUpper; (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = ( upper.tickCumulativeOutside, upper.secondsPerLiquidityOutsideX128, upper.secondsOutside, upper.initialized ); require(initializedUpper); } Slot0 memory _slot0 = slot0; if (_slot0.tick < tickLower) { return ( tickCumulativeLower - tickCumulativeUpper, secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128, secondsOutsideLower - secondsOutsideUpper ); } else if (_slot0.tick < tickUpper) { uint32 time = _blockTimestamp(); (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = observations.observeSingle( time, 0, _slot0.tick, _slot0.observationIndex, liquidity, _slot0.observationCardinality ); return ( tickCumulative - tickCumulativeLower - tickCumulativeUpper, secondsPerLiquidityCumulativeX128 - secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128, time - secondsOutsideLower - secondsOutsideUpper ); } else { return ( tickCumulativeUpper - tickCumulativeLower, secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128, secondsOutsideUpper - secondsOutsideLower ); } } /// @inheritdoc IAtlantisV1PoolDerivedState function observe(uint32[] calldata secondsAgos) external view override noDelegateCall returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) { return observations.observe( _blockTimestamp(), secondsAgos, slot0.tick, slot0.observationIndex, liquidity, slot0.observationCardinality ); } /// @inheritdoc IAtlantisV1PoolActions function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external override lock noDelegateCall { uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event uint16 observationCardinalityNextNew = observations.grow(observationCardinalityNextOld, observationCardinalityNext); slot0.observationCardinalityNext = observationCardinalityNextNew; if (observationCardinalityNextOld != observationCardinalityNextNew) emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew); } /// @inheritdoc IAtlantisV1PoolActions /// @dev not locked because it initializes unlocked function initialize(uint160 sqrtPriceX96) external override { require(slot0.sqrtPriceX96 == 0, 'AI'); int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp()); slot0 = Slot0({ sqrtPriceX96: sqrtPriceX96, tick: tick, observationIndex: 0, observationCardinality: cardinality, observationCardinalityNext: cardinalityNext, feeProtocol: 0, unlocked: true }); emit Initialize(sqrtPriceX96, tick); } struct ModifyPositionParams { // the address that owns the position address owner; // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // any change in liquidity int128 liquidityDelta; } /// @dev Effect some changes to a position /// @param params the position details and the change to the position's liquidity to effect /// @return position a storage pointer referencing the position with the given owner and tick range /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient function _modifyPosition(ModifyPositionParams memory params) private noDelegateCall returns ( Position.Info storage position, int256 amount0, int256 amount1 ) { checkTicks(params.tickLower, params.tickUpper); Slot0 memory _slot0 = slot0; // SLOAD for gas optimization position = _updatePosition( params.owner, params.tickLower, params.tickUpper, params.liquidityDelta, _slot0.tick ); if (params.liquidityDelta != 0) { if (_slot0.tick < params.tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it amount0 = SqrtPriceMath.getAmount0Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); } else if (_slot0.tick < params.tickUpper) { // current tick is inside the passed range uint128 liquidityBefore = liquidity; // SLOAD for gas optimization // write an oracle entry (slot0.observationIndex, slot0.observationCardinality) = observations.write( _slot0.observationIndex, _blockTimestamp(), _slot0.tick, liquidityBefore, _slot0.observationCardinality, _slot0.observationCardinalityNext ); amount0 = SqrtPriceMath.getAmount0Delta( _slot0.sqrtPriceX96, TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); amount1 = SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), _slot0.sqrtPriceX96, params.liquidityDelta ); liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it amount1 = SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); } } } /// @dev Gets and updates a position with the given liquidity delta /// @param owner the owner of the position /// @param tickLower the lower tick of the position's tick range /// @param tickUpper the upper tick of the position's tick range /// @param tick the current tick, passed to avoid sloads function _updatePosition( address owner, int24 tickLower, int24 tickUpper, int128 liquidityDelta, int24 tick ) private returns (Position.Info storage position) { position = positions.get(owner, tickLower, tickUpper); uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization // if we need to update the ticks, do it bool flippedLower; bool flippedUpper; if (liquidityDelta != 0) { uint32 time = _blockTimestamp(); (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = observations.observeSingle( time, 0, slot0.tick, slot0.observationIndex, liquidity, slot0.observationCardinality ); flippedLower = ticks.update( tickLower, tick, liquidityDelta, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128, secondsPerLiquidityCumulativeX128, tickCumulative, time, false, maxLiquidityPerTick ); flippedUpper = ticks.update( tickUpper, tick, liquidityDelta, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128, secondsPerLiquidityCumulativeX128, tickCumulative, time, true, maxLiquidityPerTick ); if (flippedLower) { tickBitmap.flipTick(tickLower, tickSpacing); } if (flippedUpper) { tickBitmap.flipTick(tickUpper, tickSpacing); } } (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128); position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128); // clear any tick data that is no longer needed if (liquidityDelta < 0) { if (flippedLower) { ticks.clear(tickLower); } if (flippedUpper) { ticks.clear(tickUpper); } } } /// @inheritdoc IAtlantisV1PoolActions /// @dev noDelegateCall is applied indirectly via _modifyPosition function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external override lock returns (uint256 amount0, uint256 amount1) { require(amount > 0); (, int256 amount0Int, int256 amount1Int) = _modifyPosition( ModifyPositionParams({ owner: recipient, tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: int128(amount) }) ); amount0 = uint256(amount0Int); amount1 = uint256(amount1Int); uint256 balance0Before; uint256 balance1Before; if (amount0 > 0) balance0Before = balance0(); if (amount1 > 0) balance1Before = balance1(); IAtlantisV1MintCallback(msg.sender).AtlantisV1MintCallback(amount0, amount1, data); if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0'); if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1'); emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1); } /// @inheritdoc IAtlantisV1PoolActions function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external override lock returns (uint128 amount0, uint128 amount1) { // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1} Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper); amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested; amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested; if (amount0 > 0) { position.tokensOwed0 -= amount0; TransferHelper.safeTransfer(token0, recipient, amount0); } if (amount1 > 0) { position.tokensOwed1 -= amount1; TransferHelper.safeTransfer(token1, recipient, amount1); } emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1); } /// @inheritdoc IAtlantisV1PoolActions /// @dev noDelegateCall is applied indirectly via _modifyPosition function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external override lock returns (uint256 amount0, uint256 amount1) { (Position.Info storage position, int256 amount0Int, int256 amount1Int) = _modifyPosition( ModifyPositionParams({ owner: msg.sender, tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: -int128(amount) }) ); amount0 = uint256(-amount0Int); amount1 = uint256(-amount1Int); if (amount0 > 0 || amount1 > 0) { (position.tokensOwed0, position.tokensOwed1) = ( position.tokensOwed0 + uint128(amount0), position.tokensOwed1 + uint128(amount1) ); } emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1); } /// @inheritdoc IAtlantisV1PoolActions function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external override noDelegateCall returns (int256 amount0, int256 amount1) {} /// @inheritdoc IAtlantisV1PoolActions function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external override lock noDelegateCall {} }
@inheritdoc IAtlantisV1PoolActions not locked because it initializes unlocked
function initialize(uint160 sqrtPriceX96) external override { require(slot0.sqrtPriceX96 == 0, 'AI'); int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp()); slot0 = Slot0({ sqrtPriceX96: sqrtPriceX96, tick: tick, observationIndex: 0, observationCardinality: cardinality, observationCardinalityNext: cardinalityNext, feeProtocol: 0, unlocked: true }); emit Initialize(sqrtPriceX96, tick); }
2,542,115
./full_match/43114/0x2115f83922Ad1D732bbd3b3A255f861d6B95079F/sources/project_/contracts/HimalayaToken.sol
overrides transfer function to meet tokenomics of LAYA swap and liquify compute the amounts default tax is 5% of every transfer default 95% of transfer sent to recipient Send all the taxes to different addresses (default 5%)
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(himalayaSwapRouter) != address(0) && himalayaSwapPair != address(0) && sender != himalayaSwapPair && sender != owner() ) { swapAndLiquify(); } if (recipient == BURN_ADDRESS || transferTaxRate == 0) { super._transfer(sender, recipient, amount); uint256 burnAmount = amount.mul(burnRate).div(10000); uint256 liquidityAmount = amount.mul(liquidityRate).div(10000); uint256 marketingAmount = amount.mul(marketingRate).div(10000); uint256 taxAmount = amount.mul(transferTaxRate).div(10000); require(taxAmount == (burnAmount.add(liquidityAmount).add(marketingAmount)), "LAYA::transfer: Burn value invalid"); uint256 sendAmount = amount.sub(taxAmount); require(amount == sendAmount.add(taxAmount), "LAYA::transfer: Tax value invalid"); if (burnAmount != 0) { super._transfer(sender, BURN_ADDRESS, burnAmount); } if (liquidityAmount != 0) { super._transfer(sender, address(this), liquidityAmount); } if (marketingAmount != 0) { super._transfer(sender, marketingAddress, marketingAmount); } amount = sendAmount; } }
4,600,284
/* Copyright (C) 2017 ethbets * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ pragma solidity ^0.4.11; import './ERC20.sol'; import './governanceInterface.sol'; contract Bet is ProposalInterface { modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyArbiter() { require(msg.sender == address(arbiter)); _; } modifier beforeTimestamp(uint timestamp) { require(block.timestamp < timestamp); _; } modifier afterTimestamp(uint timestamp) { require(block.timestamp >= timestamp); _; } modifier matchIsOpenOrUndecided() { require(betState == BET_STATES.OPEN || betState == BET_STATES.UNDECIDED); _; } modifier matchIsDecided() { require(betState == BET_STATES.TEAM_ZERO_WON || betState == BET_STATES.TEAM_ONE_WON || betState == BET_STATES.DRAW); _; } enum BET_STATES { OPEN, TEAM_ZERO_WON, TEAM_ONE_WON, DRAW, UNDECIDED, CALLED_RESOLVER } address public owner; // Can be a parent contract GovernanceInterface public arbiter; // Governance account // Bet data BET_STATES public betState = BET_STATES.OPEN; bool public isFeatured; string public team0Name; string public team1Name; uint public team0BetSum; uint public team1BetSum; mapping (address => uint) public betsToTeam0; mapping (address => uint) public betsToTeam1; // ERC20 support mapping (address => mapping (address => uint)) public ERC20BetsToTeam0; mapping (address => mapping (address => uint)) public ERC20BetsToTeam1; mapping (address => uint) public ERC20Team0BetSum; mapping (address => uint) public ERC20Team1BetSum; address[] public validERC20; // Chronology data uint public timestampMatchBegin; uint public timestampMatchEnd; uint public timestampArbiterDeadline; // Self-destruct is possible if time > timestampSelfDestructDeadline uint public timestampSelfDestructDeadline; uint8 public TAX; uint constant TIMESTAMP_MARGIN = 1000; event NewBet(bool forTeam, address indexed from, uint amount); event NewBetERC20(bool forTeam, address indexed from, uint amount, address erc20); event StateChanged(BET_STATES state); function Bet(GovernanceInterface _arbiter, string _team0Name, string _team1Name, uint[] _timestamps, uint8 _tax ) { require(block.timestamp < _timestamps[0]); require(_timestamps[0] < _timestamps[1]); require(_timestamps[1] < _timestamps[2]); require(_timestamps[2] < _timestamps[3]); isFeatured = false; owner = msg.sender; arbiter = _arbiter; team0Name = _team0Name; team1Name = _team1Name; // TODO: PUT BACK TIMESTAMP_MARGIN SUMS, PUT REQUIRES! timestampMatchBegin = _timestamps[0];// - TIMESTAMP_MARGIN; timestampMatchEnd = _timestamps[1];// + TIMESTAMP_MARGIN; timestampArbiterDeadline = _timestamps[2];// + TIMESTAMP_MARGIN; timestampSelfDestructDeadline = _timestamps[3];// + TIMESTAMP_MARGIN; TAX = _tax; } function __resolve(uint outcome) onlyArbiter() afterTimestamp(timestampMatchEnd) beforeTimestamp(timestampArbiterDeadline) { require(betState == BET_STATES.CALLED_RESOLVER); if (outcome == 1) betState = BET_STATES.TEAM_ZERO_WON; else if (outcome == 2) betState = BET_STATES.TEAM_ONE_WON; else if (outcome == 3) betState = BET_STATES.DRAW; else betState = BET_STATES.UNDECIDED; StateChanged(betState); } // Will create a Proposal on the arbiter function updateResult() payable matchIsOpenOrUndecided() afterTimestamp(timestampMatchEnd) { require(betState != BET_STATES.CALLED_RESOLVER); betState = BET_STATES.CALLED_RESOLVER; StateChanged(betState); arbiter.addProposal(this, timestampArbiterDeadline); } function toggleFeatured() onlyOwner() { isFeatured = !isFeatured; } function bet(bool forTeam) payable beforeTimestamp(timestampMatchBegin) { require(!arbiter.isMember(msg.sender)); require(msg.value > 0); uint prevSum; if (forTeam == false) { // Cannot bet in two teams require(betsToTeam1[msg.sender] == 0); prevSum = team0BetSum; require((prevSum + msg.value) >= prevSum); // Overflow team0BetSum += msg.value; assert(team0BetSum >= prevSum); betsToTeam0[msg.sender] += msg.value; } else { // Cannot bet in two teams require(betsToTeam0[msg.sender] == 0); prevSum = team1BetSum; require((prevSum + msg.value) >= prevSum); // Overflow team1BetSum += msg.value; assert(team1BetSum >= prevSum); betsToTeam1[msg.sender] += msg.value; } NewBet(forTeam, msg.sender, msg.value); } function checkAddERC20(address erc20) internal { if (ERC20Team0BetSum[erc20] == 0 && ERC20Team1BetSum[erc20] == 0) { validERC20.push(erc20); } } function betERC20(address erc20, bool forTeam, uint amount) beforeTimestamp(timestampMatchBegin) { require(!arbiter.isMember(msg.sender)); require(amount > 0); uint prevSum; ERC20 erc20Contract = ERC20(erc20); require(erc20Contract.transferFrom(msg.sender, this, amount)); checkAddERC20(erc20); if (forTeam == false) { // Cannot bet in two teams require(ERC20BetsToTeam1[erc20][msg.sender] == 0); prevSum = ERC20Team0BetSum[erc20]; require((prevSum + amount) >= prevSum); // Overflow ERC20Team0BetSum[erc20] += amount; assert(ERC20Team0BetSum[erc20] >= prevSum); ERC20BetsToTeam0[erc20][msg.sender] += amount; } else { // Cannot bet in two teams require(ERC20BetsToTeam0[erc20][msg.sender] == 0); prevSum = ERC20Team1BetSum[erc20]; require((prevSum + amount) >= prevSum); // Overflow ERC20Team1BetSum[erc20] += amount; assert(ERC20Team1BetSum[erc20] >= prevSum); ERC20BetsToTeam1[erc20][msg.sender] += amount; } NewBetERC20(forTeam, msg.sender, amount, erc20); } function withdraw(address[] tokens) afterTimestamp(timestampMatchEnd) matchIsDecided() { uint idx; if (betState == BET_STATES.DRAW) { msg.sender.transfer(collectOriginalBet()); for (idx = 0; idx < validERC20.length; ++idx) { uint amount = collectOriginalBetERC20(validERC20[idx]); if (amount > 0) { ERC20 erc20Contract = ERC20(validERC20[idx]); require(erc20Contract.transfer(msg.sender, amount)); } } } else { collectProfit(); for (idx = 0; idx < tokens.length; ++idx) { collectProfitERC20(tokens[idx]); } } } // Transfers the user's initial bet back function collectOriginalBet() internal returns(uint) { uint amount; if (betsToTeam0[msg.sender] > 0) { amount = betsToTeam0[msg.sender]; betsToTeam0[msg.sender] = 0; return amount; } else if (betsToTeam1[msg.sender] > 0) { amount = betsToTeam1[msg.sender]; betsToTeam1[msg.sender] = 0; return amount; } else { return 0; } } // Transfers the user's initial bet back function collectOriginalBetERC20(address erc20) internal returns(uint) { uint amount; if (ERC20BetsToTeam0[erc20][msg.sender] > 0) { amount = ERC20BetsToTeam0[erc20][msg.sender]; ERC20BetsToTeam0[erc20][msg.sender] = 0; return amount; } else if (ERC20BetsToTeam1[erc20][msg.sender] > 0) { amount = ERC20BetsToTeam1[erc20][msg.sender]; ERC20BetsToTeam1[erc20][msg.sender] = 0; return amount; } else { return 0; } } function collectProfit() internal { uint betAmount = 0; uint sum = 0; uint profit = 0; if (betState == BET_STATES.TEAM_ZERO_WON) { if (betsToTeam0[msg.sender] > 0) { betAmount = betsToTeam0[msg.sender]; sum = team0BetSum; profit = team1BetSum; } else if (betsToTeam1[msg.sender] > 0 && team0BetSum == 0) { msg.sender.transfer(collectOriginalBet()); return; } } else if (betState == BET_STATES.TEAM_ONE_WON) { if (betsToTeam1[msg.sender] > 0) { betAmount = betsToTeam1[msg.sender]; sum = team1BetSum; profit = team0BetSum; } else if (betsToTeam0[msg.sender] > 0 && team1BetSum == 0) { msg.sender.transfer(collectOriginalBet()); return; } } else { return; } assert(betAmount <= sum); profit = computeProfit(betAmount, sum, profit); msg.sender.transfer(profit + collectOriginalBet()); } function collectProfitERC20(address erc20) internal { uint betAmount = 0; uint sum = 0; uint profit = 0; if (betState == BET_STATES.TEAM_ZERO_WON) { if (ERC20BetsToTeam0[erc20][msg.sender] > 0) { betAmount = ERC20BetsToTeam0[erc20][msg.sender]; sum = ERC20Team0BetSum[erc20]; profit = ERC20Team1BetSum[erc20]; } else if (ERC20BetsToTeam1[erc20][msg.sender] > 0 && ERC20Team0BetSum[erc20] == 0) { require(erc20Contract.transfer(msg.sender, collectOriginalBetERC20(erc20))); return; } } else if (betState == BET_STATES.TEAM_ONE_WON) { if (ERC20BetsToTeam1[erc20][msg.sender] > 0) { betAmount = ERC20BetsToTeam1[erc20][msg.sender]; sum = ERC20Team1BetSum[erc20]; profit = ERC20Team0BetSum[erc20]; } else if (ERC20BetsToTeam0[erc20][msg.sender] > 0 && ERC20Team1BetSum[erc20] == 0) { require(erc20Contract.transfer(msg.sender, collectOriginalBetERC20(erc20))); return; } } else { return; } assert(betAmount <= sum); profit = computeProfit(betAmount, sum, profit); ERC20 erc20Contract = ERC20(erc20); require(erc20Contract.transfer(msg.sender, profit + collectOriginalBetERC20(erc20))); } // Compute the user's profit function computeProfit(uint betAmount, uint sum, uint profit) internal returns(uint) { // Approach one: // We might lose precision, but no overflow var senderPc = betAmount / sum; assert(senderPc >= 0 && senderPc <= 1); var senderProfit = senderPc * profit; assert(senderProfit <= profit); // Approach two: // Better precision, since multiplication is done first, but may overflow //uint sender_profit = (bet * profit) / sum; var mulTax = (senderProfit * TAX); require(mulTax >= senderProfit); // Overflow var tax = mulTax / 100; assert(tax <= senderProfit); var notaxProfit = senderProfit; senderProfit -= tax; assert(senderProfit <= notaxProfit); return senderProfit; // We can collect the bet tax by ourselves when the bet self-destructs // owner.transfer(tax); //msg.sender.transfer(senderProfit + collectOriginalBet()); } /* After the arbiter deadline and before the self-destruct * deadline, anyone can set the bet state to DRAW. * this is in the unlikely event if the arbiter don't * decide in time, every one can collect the funds. */ function close() afterTimestamp(timestampArbiterDeadline) beforeTimestamp(timestampSelfDestructDeadline) { betState = BET_STATES.DRAW; StateChanged(betState); } /* Selfdestructs the bet and return what it has in the account * as a fee to the bet's owner. */ function terminate() afterTimestamp(timestampSelfDestructDeadline) { selfdestruct(owner); } /* Fallback just throws now * Can do something, maybe increase the value of both pools */ function () { require(false); } }
Cannot bet in two teams Cannot bet in two teams
function betERC20(address erc20, bool forTeam, uint amount) beforeTimestamp(timestampMatchBegin) { require(!arbiter.isMember(msg.sender)); require(amount > 0); uint prevSum; ERC20 erc20Contract = ERC20(erc20); require(erc20Contract.transferFrom(msg.sender, this, amount)); checkAddERC20(erc20); if (forTeam == false) { require(ERC20BetsToTeam1[erc20][msg.sender] == 0); prevSum = ERC20Team0BetSum[erc20]; ERC20Team0BetSum[erc20] += amount; assert(ERC20Team0BetSum[erc20] >= prevSum); ERC20BetsToTeam0[erc20][msg.sender] += amount; } else { require(ERC20BetsToTeam0[erc20][msg.sender] == 0); prevSum = ERC20Team1BetSum[erc20]; ERC20Team1BetSum[erc20] += amount; assert(ERC20Team1BetSum[erc20] >= prevSum); ERC20BetsToTeam1[erc20][msg.sender] += amount; } NewBetERC20(forTeam, msg.sender, amount, erc20); }
1,076,350
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract CombMasterV2 is Initializable, OwnableUpgradeable { 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. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COMBs to distribute per block. uint256 lastRewardBlock; // Last block number that COMBs distribution occurs. uint256 accCombPerShare; // Accumulated COMBs per share, times 1e12. See below. } // The COMB TOKEN! IERC20 public comb; // COMB tokens created on first block. uint256 public rewardPerBlock; // ~10 tokens/daily // Info of each pool. PoolInfo[] public poolInfo; mapping(address => bool) public lpTokenExistsInPool; // Info of each user that stakes LP 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; // The block number when COMB mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Harvest(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 ); function initialize(IERC20 _comb) public initializer { OwnableUpgradeable.__Ownable_init(); comb = _comb; startBlock = block.number; rewardPerBlock = 100; add(1500, IERC20(0x6e168d4fD7569EA1C56d985256cd2E93ee12490e), false); // COMB-ETH add(7000, IERC20(0xe6D2A02de381f21318b95e2af65067dc23ca8Fd4), false); // xCOMB add(1000, IERC20(0xB2D0cad27830D78e95313EF6b3A5383406AE77dA), false); // xDEF-ETH add(500, IERC20(0xaaD34b03d34Fe3dC17bE58fB9Bbb388739B234c2), false); // NFTS massUpdatePools(); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { require( !lpTokenExistsInPool[address(_lpToken)], "MasterCheif: LP Token Address already exists in pool" ); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint += _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCombPerShare: 0 }) ); lpTokenExistsInPool[address(_lpToken)] = true; } // Update the given pool's COMB allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // View function to see pending COMBs on frontend. function pendingComb(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCombPerShare = pool.accCombPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 combReward = ((block.number - pool.lastRewardBlock) * rewardPerBlock * pool.allocPoint) / totalAllocPoint; accCombPerShare += ((combReward * 1e12) / lpSupply); } return (user.amount * accCombPerShare) / 1e12 - 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. 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 combReward = ((block.number - pool.lastRewardBlock) * rewardPerBlock * pool.allocPoint) / totalAllocPoint; pool.accCombPerShare += ((combReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for COMB 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.accCombPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeCombTransfer(msg.sender, pending); } emit Harvest(msg.sender, _pid, user.amount); } if (_amount > 0) { pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount += _amount; } user.rewardDebt = (user.amount * pool.accCombPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } function harvest(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accCombPerShare) / 1e12) * user.rewardDebt; if (pending > 0) { safeCombTransfer(msg.sender, pending); } } user.rewardDebt = (user.amount * pool.accCombPerShare) / 1e12; emit Harvest(msg.sender, _pid, user.amount); } function harvestAll() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { harvest(pid); } } // Withdraw LP tokens from MasterChef. 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.accCombPerShare) / 1e12 - user.rewardDebt; if (pending > 0) { safeCombTransfer(msg.sender, pending); } if (_amount > 0) { user.amount -= _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = (user.amount * pool.accCombPerShare) / 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]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe comb transfer function, just in case if rounding error causes pool to not have enough COMBs. function safeCombTransfer(address _to, uint256 _amount) internal { uint256 combBal = comb.balanceOf(address(this)); if (_amount > combBal) { comb.transfer(_to, combBal); } else { comb.transfer(_to, _amount); } } } // 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 "../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' // 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"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal 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 // solhint-disable-next-line compiler-version pragma solidity ^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 || !_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 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.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } // 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); } } } }
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 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 combReward = ((block.number - pool.lastRewardBlock) * rewardPerBlock * pool.allocPoint) / totalAllocPoint; pool.accCombPerShare += ((combReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; }
533,005
./full_match/5/0xFf3820bd8196C6Fdb5568d7CB1814ecC305787a5/sources/src/AmphorSyntheticVault.sol
The `claimToken` function is used to claim other tokens that have been sent to the vault. The `claimToken` function is used to claim other tokens that have been sent to the vault. It can only be called by the owner of the contract (`onlyOwner` modifier). token The IERC20 token to be claimed./
function claimToken(IERC20 token) external onlyOwner { if (token == _asset) revert CannotClaimAsset(); token.safeTransfer(_msgSender(), token.balanceOf(address(this))); }
1,860,089
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; // Imports symbols from other files into the current contract. // In this case, a series of helper contracts from OpenZeppelin. // Learn more: https://solidity.readthedocs.io/en/v0.6.2/layout-of-source-files.html#importing-other-source-files // IERC721 is the ERC721 interface that we'll use to make Avatheeer ERC721 compliant // More about ERC721: https://eips.ethereum.org/EIPS/eip-721 import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // IERC721Receiver must be implemented to accept safe transfers. // It is included on the ERC721 standard import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; // ERC165 is used to declare interface support for IERC721 // More about ERC165: https://eips.ethereum.org/EIPS/eip-165 import "@openzeppelin/contracts/introspection/ERC165.sol"; // SafeMath will be used for every math operation import "@openzeppelin/contracts/math/SafeMath.sol"; // Address will provide functions such as .isContract verification import "@openzeppelin/contracts/utils/Address.sol"; // Chainlink oracle smart contract for vrf import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; // The `is` keyword is used to inherit functions and keywords from external contracts. // In this case, `Avatheeer` inherits from the `IERC721` and `ERC165` contracts. // Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#inheritance contract Avatheeers is IERC721, ERC165, VRFConsumerBase { // Uses OpenZeppelin's SafeMath library to perform arithmetic operations safely. // Learn more: https://docs.openzeppelin.com/contracts/3.x/api/math#SafeMath using SafeMath for uint256; // Use OpenZeppelin's Address library to validate whether an address is // is a contract or not. // Learn more: https://docs.openzeppelin.com/contracts/3.x/api/utils#Address using Address for address; // Required variables for chainlink operation bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; bytes32 internal currReqId; // Constant state variables in Solidity are similar to other languages // but you must assign from an expression which is constant at compile time. // Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#constant-state-variables uint256 constant dnaDigits = 26; uint256 constant dnaModulus = 26**dnaDigits; // ERC165 identifier for the ERC721 interface got from // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Struct types let you define your own type // Learn more: https://solidity.readthedocs.io/en/v0.6.2/types.html#structs struct Avatheeer { string name; uint256 dna; } // Creates an empty array of Avatheeer structs Avatheeer[] public avatheeers; // Mapping from id of Avatheeer to its owner's address mapping(uint256 => address) public avatheeerToOwner; // Mapping from owner's address to number of owned token mapping(address => uint256) public ownerAvatheeerCount; // Mapping to validate that dna is not already taken mapping(uint256 => bool) public dnaAvatheeerExists; // Mapping from token ID to approved address mapping(uint256 => address) avatheeerApprovals; // You can nest mappings, this example maps owner to operator approvals mapping(address => mapping(address => bool)) private operatorApprovals; // Check if Avatheeer is unique and doesn't exist yet modifier isUnique(uint256 _dna) { require( !dnaAvatheeerExists[_dna], "Avatheeer with such dna already exists." ); _; } /** * Constructor inherits VRFConsumerBase * * Network: Rinkeby * Chainlink VRF Coordinator address: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B * LINK token address: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 * Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311 */ constructor() public VRFConsumerBase( 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, // VRF Coordinator 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 // LINK Token ) { keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311; fee = 0.1 * 10**18; // 0.1 LINK } function refreshRandom(string memory _name) internal returns (bytes32 requestId) { require( LINK.balanceOf(address(this)) > fee, "Not enough LINK - fill contract with faucet" ); uint256 seed = uint256(keccak256(abi.encodePacked(_name))); return requestRandomness(keyHash, fee, seed); } // Callback function used by VRF Coordinator // Creates a random Avatheeer from string (name) function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { currReqId = requestId; randomResult = randomness; } // Creates a random Avatheeer from string (name) function createRandomAvatheeer(string memory _name) public { uint256 randDna = generateRandomDna(_name, msg.sender); _createAvatheeer(_name, randDna); refreshRandom(_name); } // Generates random DNA from string (name) and address of the owner (creator) function generateRandomDna(string memory _str, address _owner) public view returns ( // Functions marked as `pure` promise not to read from or modify the state // Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#pure-functions uint256 ) { // Generates random uint from string (name) + random chainlink oracle result + address (owner) uint256 rand = uint256(keccak256(abi.encodePacked(_str))) + randomResult + uint256(_owner); rand = SafeMath.mod(rand, dnaModulus); return rand; } // Internal function to create a random Avatheeer from string (name) and DNA function _createAvatheeer(string memory _name, uint256 _dna) internal // The `internal` keyword means this function is only visible // within this contract and contracts that derive this contract // Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#visibility-and-getters // `isUnique` is a function modifier that checks if the avatheeer already exists // Learn more: https://solidity.readthedocs.io/en/v0.6.2/structure-of-a-contract.html#function-modifiers isUnique(_dna) { // Adds Avatheeer to array of Avatheeers and get id avatheeers.push(Avatheeer(_name, _dna)); uint256 id = SafeMath.sub(avatheeers.length, 1); // Mark as existent avatheeer name and dna dnaAvatheeerExists[_dna] = true; // Checks that Avatheeer owner is the same as current user // Learn more: https://solidity.readthedocs.io/en/v0.6.2/control-structures.html#error-handling-assert-require-revert-and-exceptions assert(avatheeerToOwner[id] == address(0)); // Maps the Avatheeer to the owner avatheeerToOwner[id] = msg.sender; ownerAvatheeerCount[msg.sender] = SafeMath.add( ownerAvatheeerCount[msg.sender], 1 ); } // Returns array of Avatheeers found by owner function getAvatheeersByOwner(address _owner) public view returns ( // Functions marked as `view` promise not to modify state // Learn more: https://solidity.readthedocs.io/en/v0.6.2/contracts.html#view-functions uint256[] memory ) { // Uses the `memory` storage location to store values only for the // lifecycle of this function call. // Learn more: https://solidity.readthedocs.io/en/v0.6.2/introduction-to-smart-contracts.html#storage-memory-and-the-stack uint256[] memory result = new uint256[](ownerAvatheeerCount[_owner]); uint256 counter = 0; for (uint256 i = 0; i < avatheeers.length; i++) { if (avatheeerToOwner[i] == _owner) { result[counter] = i; counter++; } } return result; } // Returns count of Avatheeers by address function balanceOf(address _owner) public override view returns (uint256 _balance) { return ownerAvatheeerCount[_owner]; } // Returns owner of the Avatheeer found by id function ownerOf(uint256 _avatheeerId) public override view returns (address _owner) { address owner = avatheeerToOwner[_avatheeerId]; require(owner != address(0), "Invalid Avatheeer ID."); return owner; } /** * Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * otherwise, the transfer is reverted. */ function safeTransferFrom( address from, address to, uint256 avatheeerId ) public override { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, avatheeerId, ""); } // Transfers Avatheeer and ownership to other address function transferFrom( address _from, address _to, uint256 _avatheeerId ) public override { require(_from != address(0) && _to != address(0), "Invalid address."); require(_exists(_avatheeerId), "Avatheeer does not exist."); require(_from != _to, "Cannot transfer to the same address."); require( _isApprovedOrOwner(msg.sender, _avatheeerId), "Address is not approved." ); ownerAvatheeerCount[_to] = SafeMath.add(ownerAvatheeerCount[_to], 1); ownerAvatheeerCount[_from] = SafeMath.sub(ownerAvatheeerCount[_from], 1); avatheeerToOwner[_avatheeerId] = _to; // Emits event defined in the imported IERC721 contract emit Transfer(_from, _to, _avatheeerId); _clearApproval(_to, _avatheeerId); } // Checks if Avatheeer exists function _exists(uint256 avatheeerId) internal view returns (bool) { address owner = avatheeerToOwner[avatheeerId]; return owner != address(0); } // Checks if address is owner or is approved to transfer Avatheeer function _isApprovedOrOwner(address spender, uint256 avatheeerId) internal view returns (bool) { address owner = avatheeerToOwner[avatheeerId]; // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(avatheeerId) == spender || isApprovedForAll(owner, spender)); } /** * Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token */ function _clearApproval(address owner, uint256 _avatheeerId) private { require( avatheeerToOwner[_avatheeerId] == owner, "Must be avatheeer owner." ); require(_exists(_avatheeerId), "Avatheeer does not exist."); if (avatheeerApprovals[_avatheeerId] != address(0)) { avatheeerApprovals[_avatheeerId] = address(0); } } // Approves other address to transfer ownership of Avatheeer function approve(address _to, uint256 _avatheeerId) public override { require( msg.sender == avatheeerToOwner[_avatheeerId], "Must be the Avatheeer owner." ); avatheeerApprovals[_avatheeerId] = _to; emit Approval(msg.sender, _to, _avatheeerId); } // Returns approved address for specific Avatheeer function getApproved(uint256 _avatheeerId) public override view returns (address operator) { require(_exists(_avatheeerId), "Avatheeer does not exist."); return avatheeerApprovals[_avatheeerId]; } /* * Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf */ function setApprovalForAll(address to, bool approved) public override { require(to != msg.sender, "Cannot approve own address"); operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } // Tells whether an operator is approved by a given owner function isApprovedForAll(address owner, address operator) public override view returns (bool) { return operatorApprovals[owner][operator]; } /** * Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * otherwise, the transfer is reverted. */ function safeTransferFrom( address from, address to, uint256 avatheeerId, bytes memory _data ) public override { transferFrom(from, to, avatheeerId); require( _checkOnERC721Received(from, to, avatheeerId, _data), "Must implmement onERC721Received." ); } /** * Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract */ function _checkOnERC721Received( address from, address to, uint256 avatheeerId, bytes memory _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, avatheeerId, _data ); return (retval == _ERC721_RECEIVED); } // Burns a Avatheeer - destroys Token completely // The `external` function modifier means this function is // part of the contract interface and other contracts can call it function burn(uint256 _avatheeerId) external { require(msg.sender != address(0), "Invalid address."); require(_exists(_avatheeerId), "Avatheeer does not exist."); require( _isApprovedOrOwner(msg.sender, _avatheeerId), "Address is not approved." ); ownerAvatheeerCount[msg.sender] = SafeMath.sub( ownerAvatheeerCount[msg.sender], 1 ); avatheeerToOwner[_avatheeerId] = address(0); } // Takes ownership of Avatheeer - only for approved users function takeOwnership(uint256 _avatheeerId) public { require( _isApprovedOrOwner(msg.sender, _avatheeerId), "Address is not approved." ); address owner = ownerOf(_avatheeerId); transferFrom(owner, msg.sender, _avatheeerId); } }
Takes ownership of Avatheeer - only for approved users
function takeOwnership(uint256 _avatheeerId) public { require( _isApprovedOrOwner(msg.sender, _avatheeerId), "Address is not approved." ); address owner = ownerOf(_avatheeerId); transferFrom(owner, msg.sender, _avatheeerId); }
6,463,378
./partial_match/1/0x895893a26C09352a3D1Ca292D172b3dE30438c2F/sources/src/mixin/HookInstrumentERC721.sol
See {IERC721-tokenURI}. currently nothing in the contract depends on the actual underlying metadata uri IERC721 underlyingContract = IERC721(underlyingAddress);
function tokenURI(uint256 tokenId) public view override returns (string memory) { bytes4 class = _underlyingClass(tokenId); if (class == ERC_721) { IHookERC721Vault vault = IHookERC721Vault(getVaultAddress(tokenId)); uint32 assetId = getAssetId(tokenId); address underlyingAddress = vault.assetAddress(assetId); uint256 underlyingTokenId = vault.assetTokenId(assetId); uint256 instrumentStrikePrice = this.getStrikePrice(tokenId); uint256 instrumentExpiration = this.getExpiration(tokenId); uint256 transfers = _transfers[tokenId].current(); return TokenURI.tokenURIERC721( tokenId, underlyingAddress, underlyingTokenId, instrumentExpiration, instrumentStrikePrice, transfers ); } return "Invalid underlying asset"; }
4,148,607
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; 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"); } } library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } 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; } } contract Decryption { function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } library ECDSA { /** * @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) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * 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)); } } 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]; } // 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(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(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(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(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)); } } library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - (subtracted.a), p); } else { difference.a = p - (addmod(subtracted.a, p - (diminished.a), p)); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - (subtracted.b), p); } else { difference.b = p - (addmod(subtracted.b, p - (diminished.b), p)); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = p - addmod(t2, p - t0, p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = p - mulmod(value.b, t3, p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG1() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = p - sum.y.a; sum.y.b = p - sum.y.b; } function toUS(G2Point memory value) internal pure returns (G2Point memory) { return G2Point({ x: value.x.mulFp2(Fp2Operations.Fp2Point({ a: 1, b: 0 }).squaredFp2()), y: value.y.mulFp2( Fp2Operations.Fp2Point({ a: 1, b: 0 }).mulFp2(Fp2Operations.Fp2Point({ a: 1, b: 0 }).squaredFp2()) ) }); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = p - result.y.a; result.y.b = p - result.y.b; } } function mulG2( G2Point memory value, uint scalar ) internal view returns (G2Point memory result) { uint step = scalar; result = G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); G2Point memory tmp = value; uint gs = gasleft(); while (step > 0) { if (step % 2 == 1) { result = addG2(result, tmp); } gs = gasleft(); tmp = doubleG2(tmp); step >>= 1; } } } library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } interface IDelegatableToken { /** * @dev Updates and returns the amount of locked tokens of a given account (`wallet`). */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Updates and returns the amount of delegated tokens of a given account (`wallet`). */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Updates and returns the amount of slashed tokens of a given account (`wallet`). */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } 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); } interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } interface ILocker { /** * @dev Returns the locked amount of untransferable tokens of a given `wallet` */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns the locked amount of untransferable and un-delegatable tokens of a given `wallet`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } interface ISkaleDKG { function openChannel(bytes32 schainId) external; function deleteChannel(bytes32 schainId) external; function isLastDKGSuccesful(bytes32 groupIndex) external view returns (bool); function isChannelOpened(bytes32 schainId) external view returns (bool); } 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; } library MathUtils { event UnderflowError( uint a, uint b ); uint constant private _EPS = 1e6; function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) external restricted { last_completed_migration = completed; } function upgrade(address new_address) external restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Can't reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint newValue = sequence.value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value != newValue) { sequence.value = newValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } 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; } } 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 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); } } 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) { // Solidity only automatically asserts when dividing by 0 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; } } library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } function uint2str(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint _i = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len.sub(1); while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 tokenId) internal virtual { } } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 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; } abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @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 Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @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 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 { require(hasRole(_roles[role].adminRole, _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 { require(hasRole(_roles[role].adminRole, _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 { 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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * Adds actual contract to mapping of actual contract addresses * @param contractsName - contracts name in skale manager system * @param newContractsAddress - contracts address in skale manager system */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract * @param contractName - human readable name of contract */ modifier allow(string memory contractName) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName3))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } contract Pricing is Permissions { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } function adjustPrice() external { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price"); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity); uint loadDiff; if (networkIsOverloaded) { loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity)); } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100)); } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price); uint timeSkipped = now.sub(lastUpdated); uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice .mul(timeSkipped) .div(constantsHolder.COOLDOWN_TIME()) .div(capacity) .div(constantsHolder.MIN_PRICE()); if (networkIsOverloaded) { assert(priceChange > 0); price = price.add(priceChange); } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price.sub(priceChange); if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = now; } function getTotalLoadPercentage() external view returns (uint) { return _getTotalLoad().mul(100).div(_getTotalCapacity()); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = INITIAL_PRICE; } function checkAllNodes() public { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No any changes on nodes"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load.add( numberOfNodesInSchain.mul(part) ); } return load; } function _getTotalCapacity() private view returns (uint) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE()); } } contract Punisher is Permissions, ILocker { /** * @dev Emitted when a slashing condition occurs. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted when a forgive condition occurs. */ event Forgive( address wallet, uint amount ); // holder => tokens mapping (address => uint) private _locked; /** * @dev Executes slashing on a validator and its delegations by an `amount` * of tokens. Currently, SkaleDKG is the only service allowed to execute * slashing. * * Emits a Slash event. * * @param validatorId uint validator to be slashed * @param amount uint slashed amount */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Owner to forgive a slashing condition. * * Emits a Forgive event. * * @param holder address of the slashed * @param amount uint amount to be forgiven */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See ILocker-getAndUpdateLockedAmount */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker-getAndUpdateForbiddenForDelegationAmount */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } // informs that Schain is created event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); event SchainDeleted( address owner, string name, bytes32 indexed schainId ); event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); event NodeAdded( bytes32 schainId, uint newNode ); // informs that Schain based on some Nodes event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev addSchain - create Schain in the system * function could be run only by executor * @param from - owner of Schain * @param deposit - received amoung of SKL * @param data - Schain's data */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schian"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev deleteSchain - removes Schain from the system * function could be run only by executor * @param from - owner of Schain * @param name - Schain name */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not an owner of Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccesful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No any free Nodes for rotation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev verifySignature - verify signature which create Group by Groups BLS master public key * @param signatureA - first part of BLS signature * @param signatureB - second part of BLS signature * @param hash - hashed message * @param counter - smallest sub from square * @param hashA - first part of hashed message * @param hashB - second part of hashed message * @param schainName - name of the Schain * @return true - if correct, false - if not */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev getSchainPrice - returns current price for given Schain * @param typeOfSchain - type of Schain * @param lifetime - lifetime of Schain * @return current price for given Schain */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev getNodesDataFromTypeOfSchain - returns number if Nodes * and part of Node which needed to this Schain * @param typeOfSchain - type of Schain * @return numberOfNodes - number of Nodes needed to this Schain * @return partOfNode - divisor of given type of Schain */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { revert("Bad schain type"); } } function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev fallbackSchainParameterDataConverter - converts data from bytes to normal parameters * @param data - concatenated parameters * @return schainParameters Parsed lifetime, typeOfSchain, nonce and name */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev _createGroupForSchain - creates Group for Schain * @param schainName - name of Schain * @param schainId - hash by name of Schain * @param numberOfNodes - number of Nodes needed for this Schain * @param partOfNode - divisor of given type of Schain */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev _addSchain - create Schain in the system * function could be run only by executor * @param from - owner of Schain * @param deposit - received amoung of SKL * @param schainParameters - Schain's data */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; require(schainParameters.typeOfSchain <= 5, "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; /** * @dev initializeSchain - initializes Schain * function could be run only by executor * @param name - SChain name * @param from - Schain owner * @param lifetime - initial lifetime of Schain * @param deposit - given amount of SKL */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev setSchainIndex - adds Schain's hash to owner * function could be run only by executor * @param schainId - hash by Schain name * @param from - Schain owner */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev changeLifetime - changes Lifetime for Schain * function could be run only by executor * @param schainId - hash by Schain name * @param lifetime - time which would be added to lifetime of Schain * @param deposit - amount of SKL which payed for this time */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev removeSchain - removes Schain from the system * function could be run only by executor * @param schainId - hash by Schain name * @param from - owner of Schain */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainId = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainId); } function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev deleteGroup - delete Group from Data contract * function could be run only by executor * @param schainId - Groups identifier */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; if (skaleDKG.isChannelOpened(schainId)) { skaleDKG.deleteChannel(schainId); } } /** * @dev setException - sets a Node like exception * function could be run only by executor * @param schainId - Groups identifier * @param nodeIndex - index of Node which would be notes like exception */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev setNodeInGroup - adds Node to Group * function could be run only by executor * @param schainId - Groups * @param nodeIndex - index of Node which would be added to the Group */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev getSchains - gets all Schains at the system * @return array of hashes by Schain names */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev getSchainsPartOfNode - gets occupied space for given Schain * @param schainId - hash by Schain name * @return occupied space */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev getSchainListSize - gets number of created Schains at the system by owner * @param from - owner of Schain * return number of Schains */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev getSchainIdsByAddress - gets array of hashes by Schain names which owned by `from` * @param from - owner of some Schains * @return array of hashes by Schain names */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev getSchainIdsForNode - returns array of hashes by Schain names, * which given Node composed * @param nodeIndex - index of Node * @return array of hashes by Schain names */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev isSchainNameAvailable - checks is given name available * Need to delete - copy of web3.utils.soliditySha3 * @param name - possible new name of Schain * @return if available - true, else - false */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId]; } /** * @dev isTimeExpired - checks is Schain lifetime expired * @param schainId - hash by Schain name * @return if expired - true, else - false */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev isOwnerAddress - checks is `from` - owner of `schainId` Schain * @param from - owner of Schain * @param schainId - hash by Schain name * @return if owner - true, else - false */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev getNumberOfNodesInGroup - shows number of Nodes in Group * @param schainId - Groups identifier * @return number of Nodes in Group */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev getNodesInGroup - shows Nodes in Group * @param schainId - Groups identifier * @return array of indexes of Nodes in Group */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev getNodeIndexInGroup - looks for Node in Group * @param schainId - Groups identifier * @param nodeId - Nodes identifier * @return index of Node in Group */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; } /** * @dev addSchainForNode - adds Schain hash to Node * function could be run only by executor * @param nodeIndex - index of Node * @param schainId - hash by Schain name */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); } else { schainsForNodes[nodeIndex][holesForNodes[nodeIndex][0]] = schainId; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForNodes[nodeIndex].length; i++) { if (min > holesForNodes[nodeIndex][i]) { min = holesForNodes[nodeIndex][i]; index = i; } } if (min == uint(-1)) { delete holesForNodes[nodeIndex]; } else { holesForNodes[nodeIndex][0] = min; holesForNodes[nodeIndex][index] = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; holesForNodes[nodeIndex].pop(); } } } /** * @dev removesSchainForNode - clean given Node of Schain * function could be run only by executor * @param nodeIndex - index of Node * @param schainIndex - index of Schain in schainsForNodes array by this Node */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev getLengthOfSchainsForNode - returns number of Schains which contain given Node * @param nodeIndex - index of Node * @return number of Schains */ function getLengthOfSchainsForNode(uint nodeIndex) public view returns (uint) { return schainsForNodes[nodeIndex].length; } /** * @dev findSchainAtSchainsForNode - finds index of Schain at schainsForNode array * @param nodeIndex - index of Node at common array of Nodes * @param schainId - hash of name of Schain * @return index of Schain at schainsForNode array */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { uint length = getLengthOfSchainsForNode(nodeIndex); for (uint i = 0; i < length; i++) { if (schainsForNodes[nodeIndex][i] == schainId) { return i; } } return length; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev _generateGroup - generates Group for Schain * @param schainId - index of Group */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev findNode - find local index of Node in Schain * @param schainId - Groups identifier * @param nodeIndex - global index of Node * @return local index of Node in Schain */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } contract SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } uint public constant COMPLAINT_TIMELIMIT = 1800; mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccesfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; event ChannelOpened(bytes32 groupIndex); event ChannelClosed(bytes32 groupIndex); event BroadcastAndKeyShare( bytes32 indexed groupIndex, uint indexed fromNode, G2Operations.G2Point[] verificationVector, KeyShare[] secretKeyContribution ); event AllDataReceived(bytes32 indexed groupIndex, uint nodeIndex); event SuccessfulDKG(bytes32 indexed groupIndex); event BadGuy(uint nodeIndex); event FailedDKG(bytes32 indexed groupIndex); event ComplaintSent(bytes32 indexed groupIndex, uint indexed fromNodeIndex, uint indexed toNodeIndex); event NewGuy(uint nodeIndex); event ComplaintError(string error); modifier correctGroup(bytes32 groupIndex) { require(channels[groupIndex].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 groupIndex) { if (!channels[groupIndex].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 groupIndex, uint nodeIndex) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); require( index < channels[groupIndex].n, "Node is not in this group"); _; } modifier correctNodeWithoutRevert(bytes32 groupIndex, uint nodeIndex) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); if (index >= channels[groupIndex].n) { emit ComplaintError("Node is not in this group"); } else { _; } } function openChannel(bytes32 groupIndex) external override allowTwo("Schains","NodeRotation") { _openChannel(groupIndex); } function deleteChannel(bytes32 groupIndex) external override allow("SchainsInternal") { require(channels[groupIndex].active, "Channel is not created"); delete channels[groupIndex]; delete dkgProcess[groupIndex]; delete complaints[groupIndex]; KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(groupIndex); } function broadcast( bytes32 groupIndex, uint nodeIndex, G2Operations.G2Point[] calldata verificationVector, KeyShare[] calldata secretKeyContribution ) external correctGroup(groupIndex) { require(_isNodeByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); uint n = channels[groupIndex].n; require(verificationVector.length == getT(n), "Incorrect number of verification vectors"); require( secretKeyContribution.length == n, "Incorrect number of secret key shares" ); uint index = _nodeIndexInSchain(groupIndex, nodeIndex); require(index < channels[groupIndex].n, "Node is not in this group"); require(!dkgProcess[groupIndex].broadcasted[index], "This node has already broadcasted"); dkgProcess[groupIndex].broadcasted[index] = true; dkgProcess[groupIndex].numberOfBroadcasted++; if (dkgProcess[groupIndex].numberOfBroadcasted == channels[groupIndex].n) { startAlrightTimestamp[groupIndex] = now; } hashedData[groupIndex][index] = _hashData(secretKeyContribution, verificationVector); KeyStorage keyStorage = KeyStorage(contractManager.getContract("KeyStorage")); keyStorage.adding(groupIndex, verificationVector[0]); emit BroadcastAndKeyShare( groupIndex, nodeIndex, verificationVector, secretKeyContribution ); } function complaint(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) external correctGroupWithoutRevert(groupIndex) correctNode(groupIndex, fromNodeIndex) correctNodeWithoutRevert(groupIndex, toNodeIndex) { require(_isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); require(isNodeBroadcasted(groupIndex, fromNodeIndex), "Node has not broadcasted"); bool broadcasted = isNodeBroadcasted(groupIndex, toNodeIndex); if (broadcasted) { _handleComplaintWhenBroadcasted(groupIndex, fromNodeIndex, toNodeIndex); return; } else { // not broadcasted in 30 min if (channels[groupIndex].startedBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp) { _finalizeSlashing(groupIndex, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); return; } } function response( bytes32 groupIndex, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point calldata multipliedShare, G2Operations.G2Point[] calldata verificationVector, KeyShare[] calldata secretKeyContribution ) external correctGroup(groupIndex) { uint indexOnSchain = _nodeIndexInSchain(groupIndex, fromNodeIndex); require(indexOnSchain < channels[groupIndex].n, "Node is not in this group"); require(complaints[groupIndex].nodeToComplaint == fromNodeIndex, "Not this Node"); require(_isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); require( hashedData[groupIndex][indexOnSchain] == _hashData(secretKeyContribution, verificationVector), "Broadcasted Data is not correct" ); uint index = _nodeIndexInSchain(groupIndex, complaints[groupIndex].fromNodeToComplaint); _verifyDataAndSlash( groupIndex, indexOnSchain, secretNumber, multipliedShare, verificationVector, secretKeyContribution[index].share ); } function alright(bytes32 groupIndex, uint fromNodeIndex) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) { require(_isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); uint index = _nodeIndexInSchain(groupIndex, fromNodeIndex); uint numberOfParticipant = channels[groupIndex].n; require(numberOfParticipant == dkgProcess[groupIndex].numberOfBroadcasted, "Still Broadcasting phase"); require( complaints[groupIndex].fromNodeToComplaint != fromNodeIndex || (fromNodeIndex == 0 && complaints[groupIndex].startComplaintBlockTimestamp == 0), "Node has already sent complaint" ); require(!dkgProcess[groupIndex].completed[index], "Node is already alright"); dkgProcess[groupIndex].completed[index] = true; dkgProcess[groupIndex].numberOfCompleted++; emit AllDataReceived(groupIndex, fromNodeIndex); if (dkgProcess[groupIndex].numberOfCompleted == numberOfParticipant) { _setSuccesfulDKG(groupIndex); } } function getChannelStartedTime(bytes32 groupIndex) external view returns (uint) { return channels[groupIndex].startedBlockTimestamp; } function getChannelStartedBlock(bytes32 groupIndex) external view returns (uint) { return channels[groupIndex].startedBlock; } function getNumberOfBroadcasted(bytes32 groupIndex) external view returns (uint) { return dkgProcess[groupIndex].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 groupIndex) external view returns (uint) { return dkgProcess[groupIndex].numberOfCompleted; } function getTimeOfLastSuccesfulDKG(bytes32 groupIndex) external view returns (uint) { return lastSuccesfulDKG[groupIndex]; } function getComplaintData(bytes32 groupIndex) external view returns (uint, uint) { return (complaints[groupIndex].fromNodeToComplaint, complaints[groupIndex].nodeToComplaint); } function getComplaintStartedTime(bytes32 groupIndex) external view returns (uint) { return complaints[groupIndex].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 groupIndex) external view returns (uint) { return startAlrightTimestamp[groupIndex]; } function isChannelOpened(bytes32 groupIndex) external override view returns (bool) { return channels[groupIndex].active; } function isLastDKGSuccesful(bytes32 groupIndex) external override view returns (bool) { return channels[groupIndex].startedBlockTimestamp <= lastSuccesfulDKG[groupIndex]; } function isBroadcastPossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return channels[groupIndex].active && index < channels[groupIndex].n && _isNodeByMessageSender(nodeIndex, msg.sender) && !dkgProcess[groupIndex].broadcasted[index]; } function isComplaintPossible( bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { uint indexFrom = _nodeIndexInSchain(groupIndex, fromNodeIndex); uint indexTo = _nodeIndexInSchain(groupIndex, toNodeIndex); bool complaintSending = ( complaints[groupIndex].nodeToComplaint == uint(-1) && dkgProcess[groupIndex].broadcasted[indexTo] && !dkgProcess[groupIndex].completed[indexFrom] ) || ( dkgProcess[groupIndex].broadcasted[indexTo] && complaints[groupIndex].startComplaintBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp && complaints[groupIndex].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[groupIndex].broadcasted[indexTo] && complaints[groupIndex].nodeToComplaint == uint(-1) && channels[groupIndex].startedBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp ) || ( complaints[groupIndex].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(groupIndex) && dkgProcess[groupIndex].completed[indexFrom] && !dkgProcess[groupIndex].completed[indexTo] && startAlrightTimestamp[groupIndex].add(COMPLAINT_TIMELIMIT) <= block.timestamp ); return channels[groupIndex].active && indexFrom < channels[groupIndex].n && indexTo < channels[groupIndex].n && dkgProcess[groupIndex].broadcasted[indexFrom] && _isNodeByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } function isAlrightPossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return channels[groupIndex].active && index < channels[groupIndex].n && _isNodeByMessageSender(nodeIndex, msg.sender) && channels[groupIndex].n == dkgProcess[groupIndex].numberOfBroadcasted && (complaints[groupIndex].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[groupIndex].startComplaintBlockTimestamp == 0)) && !dkgProcess[groupIndex].completed[index]; } function isResponsePossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return channels[groupIndex].active && index < channels[groupIndex].n && _isNodeByMessageSender(nodeIndex, msg.sender) && complaints[groupIndex].nodeToComplaint == nodeIndex; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function isNodeBroadcasted(bytes32 groupIndex, uint nodeIndex) public view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return index < channels[groupIndex].n && dkgProcess[groupIndex].broadcasted[index]; } function isEveryoneBroadcasted(bytes32 groupIndex) public view returns (bool) { return channels[groupIndex].n == dkgProcess[groupIndex].numberOfBroadcasted; } function isAllDataReceived(bytes32 groupIndex, uint nodeIndex) public view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return dkgProcess[groupIndex].completed[index]; } function getT(uint n) public pure returns (uint) { return n.mul(2).add(1).div(3); } function _setSuccesfulDKG(bytes32 groupIndex) internal { lastSuccesfulDKG[groupIndex] = now; channels[groupIndex].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(groupIndex); emit SuccessfulDKG(groupIndex); } function _verifyDataAndSlash( bytes32 groupIndex, uint indexOnSchain, uint secretNumber, G2Operations.G2Point calldata multipliedShare, G2Operations.G2Point[] calldata verificationVector, bytes32 share ) internal { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey( complaints[groupIndex].fromNodeToComplaint ); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); bytes32 key = bytes32(pkX); // Decrypt secret key contribution uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( share, key ); uint badNode = (_checkCorrectMultipliedShare(multipliedShare, indexOnSchain, secret, verificationVector) ? complaints[groupIndex].fromNodeToComplaint : complaints[groupIndex].nodeToComplaint); _finalizeSlashing(groupIndex, badNode); } function _checkCorrectMultipliedShare( G2Operations.G2Point memory multipliedShare, uint indexOnSchain, uint secret, G2Operations.G2Point[] calldata verificationVector ) private view returns (bool) { if (!multipliedShare.isG2()) { return false; } G2Operations.G2Point memory value = G2Operations.getG2Zero(); G2Operations.G2Point memory tmp = G2Operations.getG2Zero(); for (uint i = 0; i < verificationVector.length; i++) { tmp = verificationVector[i].mulG2(indexOnSchain.add(1) ** i); value = tmp.addG2(value); } tmp = multipliedShare; Fp2Operations.Fp2Point memory g1 = G2Operations.getG1(); Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({ a: 0, b: 0 }); (share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret); if (!(share.a == 0 && share.b == 0)) { share.b = Fp2Operations.P.sub((share.b % Fp2Operations.P)); } require(G2Operations.isG1(share), "mulShare not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2(); require(G2Operations.isG2(tmp), "tmp not in g2"); return value.isEqual(multipliedShare) && Precompiled.bn256Pairing( share.a, share.b, g2.x.b, g2.x.a, g2.y.b, g2.y.a, g1.a, g1.b, tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a); } function _openChannel(bytes32 groupIndex) private { SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(groupIndex); channels[groupIndex].active = true; channels[groupIndex].n = len; delete dkgProcess[groupIndex].completed; delete dkgProcess[groupIndex].broadcasted; dkgProcess[groupIndex].broadcasted = new bool[](len); dkgProcess[groupIndex].completed = new bool[](len); complaints[groupIndex].fromNodeToComplaint = uint(-1); complaints[groupIndex].nodeToComplaint = uint(-1); delete complaints[groupIndex].startComplaintBlockTimestamp; delete dkgProcess[groupIndex].numberOfBroadcasted; delete dkgProcess[groupIndex].numberOfCompleted; channels[groupIndex].startedBlockTimestamp = now; channels[groupIndex].startedBlock = block.number; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(groupIndex); emit ChannelOpened(groupIndex); } function _handleComplaintWhenBroadcasted(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) private { // incorrect data or missing alright if (complaints[groupIndex].nodeToComplaint == uint(-1)) { if ( isEveryoneBroadcasted(groupIndex) && !isAllDataReceived(groupIndex, toNodeIndex) && startAlrightTimestamp[groupIndex].add(COMPLAINT_TIMELIMIT) <= block.timestamp ) { // missing alright _finalizeSlashing(groupIndex, toNodeIndex); return; } else if (!isAllDataReceived(groupIndex, fromNodeIndex)) { // incorrect data complaints[groupIndex].nodeToComplaint = toNodeIndex; complaints[groupIndex].fromNodeToComplaint = fromNodeIndex; complaints[groupIndex].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(groupIndex, fromNodeIndex, toNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; } else if (complaints[groupIndex].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[groupIndex].startComplaintBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp) { _finalizeSlashing(groupIndex, complaints[groupIndex].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _finalizeSlashing(bytes32 groupIndex, uint badNode) private { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(groupIndex); if (schainsInternal.isAnyFreeNode(groupIndex)) { uint newNode = nodeRotation.rotateNode( badNode, groupIndex, false ); emit NewGuy(newNode); } else { _openChannel(groupIndex); schainsInternal.removeNodeFromSchain( badNode, groupIndex ); channels[groupIndex].active = false; } Punisher(contractManager.getContract("Punisher")).slash( Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode), SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function _nodeIndexInSchain(bytes32 schainId, uint nodeIndex) private view returns (uint) { return SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, nodeIndex); } function _isNodeByMessageSender(uint nodeIndex, address from) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return nodes.isNodeExist(from, nodeIndex); } function _hashData( KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) private pure returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } } contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); event BountyGot( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce}); nodes.createNode(msg.sender, params); // uint nodeIndex = nodes.createNode(msg.sender, params); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // monitors.addMonitor(nodeIndex); } function nodeExit(uint nodeIndex) external { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } bool completed; bool isSchains = false; if (schainsInternal.getActiveSchain(nodeIndex) != bytes32(0)) { completed = nodeRotation.exitFromSchain(nodeIndex); isSchains = true; } else { completed = true; } if (completed) { require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime(nodeIndex, now.add(isSchains ? constants.rotationDelay() : 0)); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // monitors.removeCheckedNodes(nodeIndex); // monitors.deleteMonitor(nodeIndex); nodes.deleteNodeForValidator(validatorId, nodeIndex); } } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } // function sendVerdict(uint fromMonitorIndex, Monitors.Verdict calldata verdict) external { // Nodes nodes = Nodes(contractManager.getContract("Nodes")); // require(nodes.isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // // additional checks for monitoring inside sendVerdict // monitors.sendVerdict(fromMonitorIndex, verdict); // } // function sendVerdicts(uint fromMonitorIndex, Monitors.Verdict[] calldata verdicts) external { // Nodes nodes = Nodes(contractManager.getContract("Nodes")); // require(nodes.isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // for (uint i = 0; i < verdicts.length; i++) { // // additional checks for monitoring inside sendVerdict // monitors.sendVerdict(fromMonitorIndex, verdicts[i]); // } // } function getBounty(uint nodeIndex) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require( nodes.isNodeActive(nodeIndex) || nodes.isNodeLeaving(nodeIndex), "Node is not Active and is not Leaving" ); Bounty bountyContract = Bounty(contractManager.getContract("Bounty")); uint averageDowntime; uint averageLatency; Monitors monitors = Monitors(contractManager.getContract("Monitors")); (averageDowntime, averageLatency) = monitors.calculateMetrics(nodeIndex); uint bounty = bountyContract.getBounty( nodeIndex, averageDowntime, averageLatency); nodes.changeNodeLastRewardDate(nodeIndex); // monitors.deleteMonitor(nodeIndex); // monitors.addMonitor(nodeIndex); if (bounty > 0) { _payBounty(bounty, nodes.getValidatorId(nodeIndex)); } _emitBountyEvent(nodeIndex, msg.sender, averageDowntime, averageLatency, bounty); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _emitBountyEvent( uint nodeIndex, address from, uint averageDowntime, uint averageLatency, uint bounty ) private { Monitors monitors = Monitors(contractManager.getContract("Monitors")); uint previousBlockEvent = monitors.getLastBountyBlock(nodeIndex); monitors.setLastBountyBlock(nodeIndex); emit BountyGot( nodeIndex, from, averageDowntime, averageLatency, bounty, previousBlockEvent, block.timestamp, gasleft()); } } contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev mint - create some amount of token and transfer it to the specified address * @param account - address where some amount of token would be created * @param amount - amount of tokens to mine * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @return returns success of function call. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB; if (!(signature.a == 0 && signature.b == 0)) { newSignB = Fp2Operations.P.sub((signature.b % Fp2Operations.P)); } else { newSignB = signature.b; } require(G2Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G2Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; /** * @dev Sets a penalty for a given offense * Only the owner can set penalties. * * @param offense string * @param penalty uint amount of slashing for the specified penalty */ function setPenalty(string calldata offense, uint penalty) external onlyOwner { _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } /** * @dev Returns the penalty for a given offense * * @param offense string * @return uint amount of slashing for the specified penalty */ function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUserCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Can't add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUserCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } function _totalDelegatedSatisfiesProofOfUserCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } contract TokenLaunchManager is Permissions, IERC777Recipient { event Approved( address holder, uint amount ); /** * @dev Emitted when a `holder` retrieves `amount`. */ event TokensRetrieved( address holder, uint amount ); /** * @dev Emitted when token launch is completed. */ event TokenLaunchIsCompleted( uint timestamp ); bytes32 public constant SELLER_ROLE = keccak256("SELLER_ROLE"); IERC1820Registry private _erc1820; mapping (address => uint) public approved; bool public tokenLaunchIsCompleted; uint private _totalApproved; modifier onlySeller() { require(_isOwner() || hasRole(SELLER_ROLE, _msgSender()), "Not authorized"); _; } /** * @dev Allocates values for `walletAddress` * * Requirements: * * - token launch must not be completed * - the total approved must be less than or equal to the seller balance. * * Emits an Approved event. * * @param walletAddress address wallet address to approve transfers to * @param value uint token amount to approve transfer to */ function approveTransfer(address walletAddress, uint value) external onlySeller { require(!tokenLaunchIsCompleted, "Can't approve because token launch is completed"); _approveTransfer(walletAddress, value); require(_totalApproved <= _getBalance(), "Balance is too low"); } /** * @dev Allocates values for `walletAddresses` * * Requirements: * * - token launch must not be completed * - the input arrays must be equal in size. * - the total approved must be less than or equal to the seller balance. * * Emits an Approved event. * * @param walletAddress address[] array of wallet addresses to approve transfers to * @param value uint[] array of token amounts to approve transfer to */ function approveBatchOfTransfers(address[] calldata walletAddress, uint[] calldata value) external onlySeller { require(!tokenLaunchIsCompleted, "Can't approve because token launch is completed"); require(walletAddress.length == value.length, "Wrong input arrays length"); for (uint i = 0; i < walletAddress.length; ++i) { _approveTransfer(walletAddress[i], value[i]); } require(_totalApproved <= _getBalance(), "Balance is too low"); } /** * @dev Allow withdrawals and disallow approvals changes * * Requirements: * * - all approvals must be done * - token launch must be not completed * */ function completeTokenLaunch() external onlySeller { require(!tokenLaunchIsCompleted, "Can't complete launch because it's already completed"); tokenLaunchIsCompleted = true; emit TokenLaunchIsCompleted(now); } /** * @dev Allows the seller to update a purchaser's address in case of an error. * * Requirements: * * - the updated address must not already be in use. * * Emits an Approved event. * * @param oldAddress address token purchaser's previous address * @param newAddress address token purchaser's new address */ function changeApprovalAddress(address oldAddress, address newAddress) external onlySeller { require(!tokenLaunchIsCompleted, "Can't change approval because token launch is completed"); require(approved[newAddress] == 0, "New address is already used"); uint oldValue = approved[oldAddress]; if (oldValue > 0) { _setApprovedAmount(oldAddress, 0); _approveTransfer(newAddress, oldValue); } } /** * @dev Allows the seller to update a purchaser's amount in case of an error. * * @param wallet address of the token purchaser * @param newValue uint of the updated token amount */ function changeApprovalValue(address wallet, uint newValue) external onlySeller { require(!tokenLaunchIsCompleted, "Can't change approval because token launch is completed"); _setApprovedAmount(wallet, newValue); } /** * @dev Transfers the entire value to the sender's address. Transferred tokens * are locked for Proof-of-Use. * * Requirements: * * - token transfer must be approved. */ function retrieve() external { require(tokenLaunchIsCompleted, "Can't retrive tokens because token launch is not completed"); require(approved[_msgSender()] > 0, "Transfer is not approved"); uint value = approved[_msgSender()]; _setApprovedAmount(_msgSender(), 0); require( IERC20(contractManager.getContract("SkaleToken")).transfer(_msgSender(), value), "Error in transfer call to SkaleToken"); TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")).lock(_msgSender(), value); emit TokensRetrieved(_msgSender(), value); } /** * @dev A required callback for ERC777. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); tokenLaunchIsCompleted = false; _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } // private function _approveTransfer(address walletAddress, uint value) internal onlySeller { require(value > 0, "Value must be greater than zero"); _setApprovedAmount(walletAddress, approved[walletAddress].add(value)); emit Approved(walletAddress, value); } function _getBalance() private view returns(uint balance) { return IERC20(contractManager.getContract("SkaleToken")).balanceOf(address(this)); } function _setApprovedAmount(address wallet, uint value) private { require(wallet != address(0), "Wallet address must be non zero"); uint oldValue = approved[wallet]; if (oldValue != value) { approved[wallet] = value; if (value > oldValue) { _totalApproved = _totalApproved.add(value.sub(oldValue)); } else { _totalApproved = _totalApproved.sub(oldValue.sub(value)); } } } } contract TokenState is Permissions, ILocker { /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); string[] private _lockers; /** * @dev Return and update the total locked amount of a given `holder`. * * @param holder address of the token holder * @return total locked amount */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint locked = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } /** * @dev Return and update the total locked and un-delegatable amount of a given `holder`. * * @param holder address of the token holder * @return amount total slashed amount (non-transferable and non-delegatable) */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a LockerWasRemoved event. * * @param locker string name of contract to remove from locker */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a LockerWasAdded event. * * @param locker string name of contract to add to locker */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); event ValidatorWasEnabled( uint validatorId ); event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator Id. * * Requirements: * * - sender must not already have registered a validator Id. * - fee rate must be between 0 - 1000‰. Note: per mille! * * Emits ValidatorRegistered event. * * @param name string * @param description string * @param feeRate uint Fee charged on delegations by the validator per mille * @param minimumDelegationAmount uint Minimum delegation amount accepted by the validator */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate < 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the validator whitelist. Once turned off the * whitelist cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows a validator to request a new address. * * Requirements: * * - new address must not be null * - new address must not be already registered as a validator * * @param newValidatorAddress address */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a given node address. * * Requirements: * * - the given signature must be valid. * - the address must not be assigned to a validator. * * Emits NodeAddressWasAdded event. * * @param nodeAddress address * @param sig bytes signature of validator Id by node operator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a given node address from a validator. * * Emits NodeAddressWasRemoved event. * * @param nodeAddress address */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); _removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. * * @param newName string */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. * * @param newDescription string */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - validator must not have already enabled accepting new requests */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - validator must not have already stopped accepting new requests */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } /** * @dev Returns the amount of validator bond. * * @param validatorId uint ID of validator to return the amount of locked funds * @return bondAmount uint the amount of self-delegated funds by the validator */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns a list of trusted validators. * * @return uint[] trusted validators */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } function checkMinimumDelegation(uint validatorId, uint amount) external view checkValidatorExists(validatorId) allow("DelegationController") returns (bool) { return validators[validatorId].minimumDelegationAmount <= amount ? true : false; } function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function isAuthorizedValidator(uint validatorId) external view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator with given address does not exist"); } function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } // private function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _removeNodeAddress(uint validatorId, address nodeAddress) private { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } contract Bounty is Permissions { uint public constant STAGE_LENGTH = 31558150; // 1 year uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant BOUNTY = 96250000 * 1e18; uint private _nextStage; uint private _stagePool; bool public bountyReduction; uint private _nodesPerRewardPeriod; uint private _nodesRemainingPerRewardPeriod; uint private _rewardPeriodFinished; function getBounty( uint nodeIndex, uint downtime, uint latency ) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); _refillStagePool(constantsHolder); if (_rewardPeriodFinished <= now) { _updateNodesPerRewardPeriod(constantsHolder, nodes); } uint bounty = _calculateMaximumBountyAmount(_stagePool, _nextStage, nodeIndex, constantsHolder, nodes); bounty = _reduceBounty( bounty, nodeIndex, downtime, latency, nodes, constantsHolder ); _stagePool = _stagePool.sub(bounty); _nodesRemainingPerRewardPeriod = _nodesRemainingPerRewardPeriod.sub(1); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function calculateNormalBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint stagePoolSize; uint nextStage; (stagePoolSize, nextStage) = _getStagePoolSize(constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, nextStage, nodeIndex, constantsHolder, nodes ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextStage = 0; _stagePool = 0; _rewardPeriodFinished = 0; bountyReduction = false; } // private function _calculateMaximumBountyAmount( uint stagePoolSize, uint nextStage, uint nodeIndex, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } uint numberOfRewards = _getStageBeginningTimestamp(nextStage, constantsHolder) .sub(now) .div(constantsHolder.rewardPeriod()); uint numberOfRewardsPerAllNodes = numberOfRewards.mul(_nodesPerRewardPeriod); return stagePoolSize.div( numberOfRewardsPerAllNodes.add(_nodesRemainingPerRewardPeriod) ); } function _getStageBeginningTimestamp(uint stage, ConstantsHolder constantsHolder) private view returns (uint) { return constantsHolder.launchTimestamp().add(stage.mul(STAGE_LENGTH)); } function _getStagePoolSize(ConstantsHolder constantsHolder) private view returns (uint stagePool, uint nextStage) { stagePool = _stagePool; for (nextStage = _nextStage; now >= _getStageBeginningTimestamp(nextStage, constantsHolder); ++nextStage) { stagePool += _getStageReward(_nextStage); } } function _refillStagePool(ConstantsHolder constantsHolder) private { (_stagePool, _nextStage) = _getStagePoolSize(constantsHolder); } function _updateNodesPerRewardPeriod(ConstantsHolder constantsHolder, Nodes nodes) private { _nodesPerRewardPeriod = nodes.getNumberOnlineNodes(); _nodesRemainingPerRewardPeriod = _nodesPerRewardPeriod; _rewardPeriodFinished = now.add(uint(constantsHolder.rewardPeriod())); } function _getStageReward(uint stage) private pure returns (uint) { if (stage >= 6) { return BOUNTY.div(2 ** stage.sub(6).div(3)); } else { if (stage == 0) { return YEAR1_BOUNTY; } else if (stage == 1) { return YEAR2_BOUNTY; } else if (stage == 2) { return YEAR3_BOUNTY; } else if (stage == 3) { return YEAR4_BOUNTY; } else if (stage == 4) { return YEAR5_BOUNTY; } else { return YEAR6_BOUNTY; } } } function _reduceBounty( uint bounty, uint nodeIndex, uint downtime, uint latency, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = _reduceBountyByDowntime(bounty, nodeIndex, downtime, nodes, constants); if (latency > constants.allowableLatency()) { // reduce bounty because latency is too big reducedBounty = reducedBounty.mul(constants.allowableLatency()).div(latency); } if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _reduceBountyByDowntime( uint bounty, uint nodeIndex, uint downtime, Nodes nodes, ConstantsHolder constants ) private view returns (uint reducedBounty) { reducedBounty = bounty; uint getBountyDeadline = uint(nodes.getNodeLastRewardDate(nodeIndex)) .add(constants.rewardPeriod()) .add(constants.deltaPeriod()); uint numberOfExpiredIntervals; if (now > getBountyDeadline) { numberOfExpiredIntervals = now.sub(getBountyDeadline).div(constants.checkTime()); } else { numberOfExpiredIntervals = 0; } uint normalDowntime = uint(constants.rewardPeriod()) .sub(constants.deltaPeriod()) .div(constants.checkTime()) .div(constants.DOWNTIME_THRESHOLD_PART()); uint totalDowntime = downtime.add(numberOfExpiredIntervals); if (totalDowntime > normalDowntime) { // reduce bounty because downtime is too big uint penalty = bounty .mul(totalDowntime) .div( uint(constants.rewardPeriod()).sub(constants.deltaPeriod()) .div(constants.checkTime()) ); if (bounty > penalty) { reducedBounty = bounty.sub(penalty); } else { reducedBounty = 0; } } } } contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/8 of Node) uint8 public constant MEDIUM_DIVISOR = 8; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; /** * Set reward and delta periods to new one, run only by owner. This function * only for tests. * @param newRewardPeriod - new Reward period * @param newDeltaPeriod - new Delta period */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * Set new check time. This function only for tests. * @param newCheckTime - new check time */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * Set latency new one in ms, run only by owner. This function * only for tests. * @param newAllowableLatency - new Allowable Latency */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Can't set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; } } contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * @param validatorId uint ID of validator to receive delegation proposal * @param amount uint amount of proposed delegation * @param delegationPeriod uint period of proposed delegation * @param info string extra information provided by the token holder (if any) */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); TokenState tokenState = TokenState(contractManager.getContract("TokenState")); require( validatorService.checkMinimumDelegation(validatorId, amount), "Amount does not meet the validator's minimum delegation amount"); require( validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require( delegationPeriodManager.isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); require( validatorService.isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = skaleToken.balanceOf(msg.sender); uint forbiddenForDelegation = tokenState.getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See ILocker. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows a token holder to cancel a delegation proposal. * * Requirements: * * - the sender must be the token holder of the delegation proposal. * - the delegation must still be in a PROPOSED state. * * Emits a DelegationRequestCanceledByUser event. * * @param delegationId uint ID of delegation proposal */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a DelegationAccepted event. * * @param delegationId uint ID of delegation proposal */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( validatorService.checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); tokenLaunchLocker.handleDelegationAdd( delegations[delegationId].holder, delegationId, delegations[delegationId].amount, delegations[delegationId].started); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } /** * @dev Allows a delegator to undelegate a specific delegation. * * Requirements: * * - the sender must be the delegator. * - the delegation must be in DELEGATED state. * * Emits an UndelegationRequested event. * * @param delegationId uint ID of delegation to undelegate */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); tokenLaunchLocker.handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); emit UndelegationRequested(delegationId); } /** * @dev Allows the Punisher to confiscate an `amount` of stake from * `validatorId` by slashing. This slashes all delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manger to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * See Punisher. * * Emits a SlashingEvent. * * @param validatorId uint validator to slash * @param amount uint amount to slash * */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); } function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allow("Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function getAndUpdateDelegatedToValidator(uint validatorId, uint month) public allow("Nodes") returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. * * @param delegationId uint ID of the delegation */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); if (_getCurrentMonth() == timeHelpers.timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); require( _lockedInPendingDelegations[holder].month == currentMonth, "There are no delegation requests this month"); require(_lockedInPendingDelegations[holder].amount >= amount, "Unlocking amount is too big"); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); return timeHelpers.getCurrentMonth(); } function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getContract("Punisher")); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < constantsHolder.limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } } contract DelegationPeriodManager is Permissions { /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); mapping (uint => uint) public stakeMultipliers; /** * @dev Creates a new available delegation period and return in the network. * Only the owner may set new delegation period and returns in the network. * * Emits a DelegationPeriodWasSet event. * * @param monthsCount uint delegation duration in months * @param stakeMultiplier uint return for delegation */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. * * @param monthsCount uint delegation duration in months * @return bool True if delegation period is allowed */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0 ? true : false; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[3] = 100; // 3 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when a bounty is withdrawn by the token holder. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn by the validator. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when a bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 groupIndex) external allow("SkaleDKG") { _previousSchainsPublicKeys[groupIndex].push(_schainsPublicKeys[groupIndex]); delete _schainsPublicKeys[groupIndex]; } function initPublicKeyInProgress(bytes32 groupIndex) external allow("SkaleDKG") { _publicKeysInProgress[groupIndex] = G2Operations.getG2Zero(); } function adding(bytes32 groupIndex, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[groupIndex] = value.addG2(_publicKeysInProgress[groupIndex]); } function finalizePublicKey(bytes32 groupIndex) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(groupIndex)) { _previousSchainsPublicKeys[groupIndex].push(_schainsPublicKeys[groupIndex]); } _schainsPublicKeys[groupIndex] = _publicKeysInProgress[groupIndex]; delete _publicKeysInProgress[groupIndex]; } function getCommonPublicKey(bytes32 groupIndex) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[groupIndex]; } function getPreviousPublicKey(bytes32 groupIndex) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[groupIndex].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[groupIndex][length - 1]; } function getAllPreviousPublicKeys(bytes32 groupIndex) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[groupIndex]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } contract Monitors is Permissions { using StringUtils for string; using SafeCast for uint; struct Verdict { uint toNodeIndex; uint32 downtime; uint32 latency; } struct CheckedNode { uint nodeIndex; uint time; } struct CheckedNodeWithIp { uint nodeIndex; uint time; bytes4 ip; } mapping (bytes32 => CheckedNode[]) public checkedNodes; mapping (bytes32 => uint[][]) public verdicts; mapping (bytes32 => uint[]) public groupsForMonitors; mapping (bytes32 => uint) public lastVerdictBlocks; mapping (bytes32 => uint) public lastBountyBlocks; event MonitorCreated( uint nodeIndex, bytes32 monitorIndex, uint numberOfMonitors, uint[] nodesInGroup, uint time, uint gasSpend ); event VerdictWasSent( uint indexed fromMonitorIndex, uint indexed toNodeIndex, uint32 downtime, uint32 latency, bool status, uint previousBlockEvent, uint time, uint gasSpend ); event MetricsWereCalculated( uint forNodeIndex, uint32 averageDowntime, uint32 averageLatency, uint time, uint gasSpend ); event PeriodsWereSet( uint rewardPeriod, uint deltaPeriod, uint time, uint gasSpend ); event MonitorRotated( bytes32 monitorIndex, uint newNode ); /** * addMonitor - setup monitors of node */ function addMonitor(uint nodeIndex) external allow("SkaleManager") { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); _generateGroup(monitorIndex, nodeIndex, constantsHolder.NUMBER_OF_MONITORS()); CheckedNode memory checkedNode = _getCheckedNodeData(nodeIndex); for (uint i = 0; i < groupsForMonitors[monitorIndex].length; i++) { bytes32 index = keccak256(abi.encodePacked(groupsForMonitors[monitorIndex][i])); addCheckedNode(index, checkedNode); } emit MonitorCreated( nodeIndex, monitorIndex, groupsForMonitors[monitorIndex].length, groupsForMonitors[monitorIndex], block.timestamp, gasleft() ); } function deleteMonitor(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); while (verdicts[keccak256(abi.encodePacked(nodeIndex))].length > 0) { verdicts[keccak256(abi.encodePacked(nodeIndex))].pop(); } uint[] memory nodesInGroup = groupsForMonitors[monitorIndex]; uint index; bytes32 monitoringIndex; for (uint i = 0; i < nodesInGroup.length; i++) { monitoringIndex = keccak256(abi.encodePacked(nodesInGroup[i])); (index, ) = _find(monitoringIndex, nodeIndex); if (index < checkedNodes[monitoringIndex].length) { if (index != checkedNodes[monitoringIndex].length.sub(1)) { checkedNodes[monitoringIndex][index] = checkedNodes[monitoringIndex][checkedNodes[monitoringIndex].length.sub(1)]; } checkedNodes[monitoringIndex].pop(); } } delete groupsForMonitors[monitorIndex]; } function removeCheckedNodes(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); delete checkedNodes[monitorIndex]; } function sendVerdict(uint fromMonitorIndex, Verdict calldata verdict) external allow("SkaleManager") { uint index; uint time; bytes32 monitorIndex = keccak256(abi.encodePacked(fromMonitorIndex)); (index, time) = _find(monitorIndex, verdict.toNodeIndex); require(time > 0, "Checked Node does not exist in MonitorsArray"); if (time <= block.timestamp) { if (index != checkedNodes[monitorIndex].length.sub(1)) { checkedNodes[monitorIndex][index] = checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; } delete checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; checkedNodes[monitorIndex].pop(); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bool receiveVerdict = time.add(constantsHolder.deltaPeriod()) > block.timestamp; if (receiveVerdict) { verdicts[keccak256(abi.encodePacked(verdict.toNodeIndex))].push( [uint(verdict.downtime), uint(verdict.latency)] ); } _emitVerdictsEvent(fromMonitorIndex, verdict, receiveVerdict); } } function calculateMetrics(uint nodeIndex) external allow("SkaleManager") returns (uint averageDowntime, uint averageLatency) { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); uint lengthOfArray = getLengthOfMetrics(monitorIndex); uint[] memory downtimeArray = new uint[](lengthOfArray); uint[] memory latencyArray = new uint[](lengthOfArray); for (uint i = 0; i < lengthOfArray; i++) { downtimeArray[i] = verdicts[monitorIndex][i][0]; latencyArray[i] = verdicts[monitorIndex][i][1]; } if (lengthOfArray > 0) { averageDowntime = _median(downtimeArray); averageLatency = _median(latencyArray); } delete verdicts[monitorIndex]; } function setLastBountyBlock(uint nodeIndex) external allow("SkaleManager") { lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))] = block.number; } function getCheckedArray(bytes32 monitorIndex) external view returns (CheckedNodeWithIp[] memory checkedNodesWithIp) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNodesWithIp = new CheckedNodeWithIp[](checkedNodes[monitorIndex].length); for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { checkedNodesWithIp[i].nodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodesWithIp[i].time = checkedNodes[monitorIndex][i].time; checkedNodesWithIp[i].ip = nodes.getNodeIP(checkedNodes[monitorIndex][i].nodeIndex); } } function getLastBountyBlock(uint nodeIndex) external view returns (uint) { return lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))]; } function getNodesInGroup(bytes32 monitorIndex) external view returns (uint[] memory) { return groupsForMonitors[monitorIndex]; } function getNumberOfNodesInGroup(bytes32 monitorIndex) external view returns (uint) { return groupsForMonitors[monitorIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * Add checked node or update existing one if it is already exits */ function addCheckedNode(bytes32 monitorIndex, CheckedNode memory checkedNode) public allow("SkaleManager") { for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { if (checkedNodes[monitorIndex][i].nodeIndex == checkedNode.nodeIndex) { checkedNodes[monitorIndex][i] = checkedNode; return; } } checkedNodes[monitorIndex].push(checkedNode); } function getLastReceivedVerdictBlock(uint nodeIndex) public view returns (uint) { return lastVerdictBlocks[keccak256(abi.encodePacked(nodeIndex))]; } function getLengthOfMetrics(bytes32 monitorIndex) public view returns (uint) { return verdicts[monitorIndex].length; } function _generateGroup(bytes32 monitorIndex, uint nodeIndex, uint numberOfNodes) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint[] memory activeNodes = nodes.getActiveNodeIds(); uint numberOfNodesInGroup; uint availableAmount = activeNodes.length.sub((nodes.isNodeActive(nodeIndex)) ? 1 : 0); if (numberOfNodes > availableAmount) { numberOfNodesInGroup = availableAmount; } else { numberOfNodesInGroup = numberOfNodes; } uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), monitorIndex))); for (uint i = 0; i < numberOfNodesInGroup; ++i) { uint index = random % (activeNodes.length.sub(ignoringTail)); if (activeNodes[index] == nodeIndex) { _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; index = random % (activeNodes.length.sub(ignoringTail)); } groupsForMonitors[monitorIndex].push(activeNodes[index]); _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; } } function _median(uint[] memory values) private pure returns (uint) { if (values.length < 1) { revert("Can't calculate _median of empty array"); } _quickSort(values, 0, values.length.sub(1)); return values[values.length.div(2)]; } function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } function _find(bytes32 monitorIndex, uint nodeIndex) private view returns (uint index, uint time) { index = checkedNodes[monitorIndex].length; time = 0; for (uint i = 0; i < checkedNodes[monitorIndex].length; i++) { uint checkedNodeNodeIndex; uint checkedNodeTime; checkedNodeNodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodeTime = checkedNodes[monitorIndex][i].time; if (checkedNodeNodeIndex == nodeIndex && (time == 0 || checkedNodeTime < time)) { index = i; time = checkedNodeTime; } } } function _quickSort(uint[] memory array, uint left, uint right) private pure { uint leftIndex = left; uint rightIndex = right; uint middle = array[right.add(left).div(2)]; while (leftIndex <= rightIndex) { while (array[leftIndex] < middle) { leftIndex++; } while (middle < array[rightIndex]) { rightIndex--; } if (leftIndex <= rightIndex) { (array[leftIndex], array[rightIndex]) = (array[rightIndex], array[leftIndex]); leftIndex++; rightIndex = (rightIndex > 0 ? rightIndex.sub(1) : 0); } } if (left < rightIndex) _quickSort(array, left, rightIndex); if (leftIndex < right) _quickSort(array, leftIndex, right); } function _getCheckedNodeData(uint nodeIndex) private view returns (CheckedNode memory checkedNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNode.nodeIndex = nodeIndex; checkedNode.time = nodes.getNodeNextRewardDate(nodeIndex).sub(constantsHolder.deltaPeriod()); } function _emitVerdictsEvent( uint fromMonitorIndex, Verdict memory verdict, bool receiveVerdict ) private { uint previousBlockEvent = getLastReceivedVerdictBlock(verdict.toNodeIndex); lastVerdictBlocks[keccak256(abi.encodePacked(verdict.toNodeIndex))] = block.number; emit VerdictWasSent( fromMonitorIndex, verdict.toNodeIndex, verdict.downtime, verdict.latency, receiveVerdict, previousBlockEvent, block.timestamp, gasleft() ); } } contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; /** * nodeIndex - index of Node which is in process of rotation(left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No any free Nodes for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str()); string memory dkgRevert = "DKG proccess did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccesful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev selectNodeToGroup - pseudo-randomly select new Node for Schain * @param schainId - hash of name of Schain * @return nodeIndex - global index of Node */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No any free Nodes for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; // informs that Node is created event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint time, uint gasSpend ); // informs that node is fully finished quitting from the system event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); // informs that owner starts the procedure of quitting the Node from the system event ExitInited( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } /** * @dev removeSpaceFromFractionalNode - occupies space from Fractional Node * function could be run only by Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be occupied */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev adSpaceToFractionalNode - returns space to Fractional Node * function could be run only be Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be returned */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev changeNodeLastRewardDate - changes Node's last reward date * function could be run only by SkaleManager * @param nodeIndex - index of Node */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev createNode - creates new Node and add it to the Nodes contract * function could be only run by SkaleManager * @param from - owner of Node */ // * @return nodeIndex - index of Node function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name has already registered"); require(params.port > 0, "Port is zero"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, block.timestamp, gasleft()); } /** * @dev initExit - initiate a procedure of quitting the system * function could be only run by SkaleManager * @param nodeIndex - index of Node * @return true - if everything OK */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { _setNodeLeaving(nodeIndex); emit ExitInited( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev completeExit - finish a procedure of quitting the system * function could be run only by SkaleManager * @param nodeIndex - index of Node * @return amount of SKL which be returned */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); } function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function setNodeInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.In_Maintenance; } function removeNodeFromInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintence"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.Active; } function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev isTimeForReward - checks if time for reward has come * @param nodeIndex - index of Node * @return if time for reward has come - true, else - false */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return uint(nodes[nodeIndex].lastRewardDate).add(constantsHolder.rewardPeriod()) <= block.timestamp; } /** * @dev getNodeIP - get ip address of Node * @param nodeIndex - index of Node * @return ip address */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev getNodePort - get Node's port * @param nodeIndex - index of Node * @return port */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev isNodeLeft - checks if Node status Left * @param nodeIndex - index of Node * @return if Node status Left - true, else - false */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev getNodeLastRewardDate - get Node last reward date * @param nodeIndex - index of Node * @return Node last reward date */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev getNodeNextRewardDate - get Node next reward date * @param nodeIndex - index of Node * @return Node next reward date */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes[nodeIndex].lastRewardDate.add(constantsHolder.rewardPeriod()); } /** * @dev getNumberOfNodes - get number of Nodes * @return number of Nodes */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev getNumberOfFullNodes - get number Online Nodes * @return number of active nodes plus number of leaving nodes */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev getActiveNodeIPs - get array of ips of Active Nodes * @return activeNodeIPs - array of ips of Active Nodes */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev getActiveNodesByAddress - get array of indexes of Active Nodes, which were * created by msg.sender * @return activeNodesByAddress Array of indexes of Active Nodes, which were created by msg.sender */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev getActiveNodeIds - get array of indexes of Active Nodes * @return activeNodeIds - array of indexes of Active Nodes */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev isNodeExist - checks existence of Node at this address * @param from - account address * @param nodeIndex - index of Node * @return if exist - true, else - false */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev isNodeActive - checks if Node status Active * @param nodeIndex - index of Node * @return if Node status Active - true, else - false */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev isNodeLeaving - checks if Node status Leaving * @param nodeIndex - index of Node * @return if Node status Leaving - true, else - false */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev _setNodeLeft - set Node Left * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev _setNodeLeaving - set Node Leaving * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev _addNode - adds Node to array * function could be run only by executor * @param from - owner of Node * @param name - Node name * @param ip - Node ip * @param publicIP - Node public ip * @param port - Node public port * @param publicKey - Ethereum public key * @return nodeIndex Index of Node */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } }
initialize Schain create a group for Schain
function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; require(schainParameters.typeOfSchain <= 5, "Invalid type of Schain"); _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); }
7,363,495
pragma solidity ^0.5.10; /** @title Relay */ /** @author Summa (https://summa.one) */ import {SafeMath} from "@summa-tx/bitcoin-spv-sol/contracts/SafeMath.sol"; import {TypedMemView} from "@summa-tx/bitcoin-spv-sol/contracts/TypedMemView.sol"; import {ViewBTC} from "@summa-tx/bitcoin-spv-sol/contracts/ViewBTC.sol"; import {ViewSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ViewSPV.sol"; import {IRelay} from "./Interfaces.sol"; contract Relay is IRelay { using SafeMath for uint256; using TypedMemView for bytes; using TypedMemView for bytes29; using ViewBTC for bytes29; using ViewSPV for bytes29; /* using BytesLib for bytes; using BTCUtils for bytes; using ValidateSPV for bytes; */ // How often do we store the height? // A higher number incurs less storage cost, but more lookup cost uint32 public constant HEIGHT_INTERVAL = 4; bytes32 internal relayGenesis; bytes32 internal bestKnownDigest; bytes32 internal lastReorgCommonAncestor; mapping (bytes32 => bytes32) internal previousBlock; mapping (bytes32 => uint256) internal blockHeight; uint256 internal currentEpochDiff; uint256 internal prevEpochDiff; /// @notice Gives a starting point for the relay /// @dev We don't check this AT ALL really. Don't use relays with bad genesis /// @param _genesisHeader The starting header /// @param _height The starting height /// @param _periodStart The hash of the first header in the genesis epoch constructor(bytes memory _genesisHeader, uint256 _height, bytes32 _periodStart) public { bytes29 _genesisView = _genesisHeader.ref(0).tryAsHeader(); require(_genesisView.notNull(), "Stop being dumb"); bytes32 _genesisDigest = _genesisView.hash256(); require( _periodStart & bytes32(0x0000000000000000000000000000000000000000000000000000000000ffffff) == bytes32(0), "Period start hash does not have work. Hint: wrong byte order?"); relayGenesis = _genesisDigest; bestKnownDigest = _genesisDigest; lastReorgCommonAncestor = _genesisDigest; blockHeight[_genesisDigest] = _height; blockHeight[_periodStart] = _height.sub(_height % 2016); currentEpochDiff = _genesisView.diff(); } /// @notice Getter for currentEpochDiff /// @dev This is updated when a new heavist header has a new diff /// @return The difficulty of the bestKnownDigest function getCurrentEpochDifficulty() external view returns (uint256) { return currentEpochDiff; } /// @notice Getter for prevEpochDiff /// @dev This is updated when a difficulty change is accepted /// @return The difficulty of the previous epoch function getPrevEpochDifficulty() external view returns (uint256) { return prevEpochDiff; } /// @notice Getter for relayGenesis /// @dev This is an initialization parameter /// @return The hash of the first block of the relay function getRelayGenesis() public view returns (bytes32) { return relayGenesis; } /// @notice Getter for bestKnownDigest /// @dev This updated only by calling markNewHeaviest /// @return The hash of the best marked chain tip function getBestKnownDigest() public view returns (bytes32) { return bestKnownDigest; } /// @notice Getter for relayGenesis /// @dev This is updated only by calling markNewHeaviest /// @return The hash of the shared ancestor of the most recent fork function getLastReorgCommonAncestor() public view returns (bytes32) { return lastReorgCommonAncestor; } /// @notice Finds the height of a header by its digest /// @dev Will fail if the header is unknown /// @param _digest The header digest to search for /// @return The height of the header, or error if unknown function findHeight(bytes32 _digest) external view returns (uint256) { return _findHeight(_digest); } /// @notice Finds an ancestor for a block by its digest /// @dev Will fail if the header is unknown /// @param _digest The header digest to search for /// @return The height of the header, or error if unknown function findAncestor(bytes32 _digest, uint256 _offset) external view returns (bytes32) { return _findAncestor(_digest, _offset); } /// @notice Checks if a digest is an ancestor of the current one /// @dev Limit the amount of lookups (and thus gas usage) with _limit /// @param _ancestor The prospective ancestor /// @param _descendant The descendant to check /// @param _limit The maximum number of blocks to check /// @return true if ancestor is at most limit blocks lower than descendant, otherwise false function isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) external view returns (bool) { return _isAncestor(_ancestor, _descendant, _limit); } /// @notice Adds headers to storage after validating /// @dev We check integrity and consistency of the header chain /// @param _anchor The header immediately preceeding the new chain /// @param _headers A tightly-packed list of 80-byte Bitcoin headers /// @return True if successfully written, error otherwise function addHeaders(bytes calldata _anchor, bytes calldata _headers) external returns (bool) { bytes29 _headersView = _headers.ref(0).tryAsHeaderArray(); bytes29 _anchorView = _anchor.ref(0).tryAsHeader(); require(_headersView.notNull(), "Header array length must be divisible by 80"); require(_anchorView.notNull(), "Anchor must be 80 bytes"); return _addHeaders(_anchorView, _headersView, false); } /// @notice Adds headers to storage, performs additional validation of retarget /// @dev Checks the retarget, the heights, and the linkage /// @param _oldPeriodStartHeader The first header in the difficulty period being closed /// @param _oldPeriodEndHeader The last header in the difficulty period being closed /// @param _headers A tightly-packed list of 80-byte Bitcoin headers /// @return True if successfully written, error otherwise function addHeadersWithRetarget( bytes calldata _oldPeriodStartHeader, bytes calldata _oldPeriodEndHeader, bytes calldata _headers ) external returns (bool) { bytes29 _oldStart = _oldPeriodStartHeader.ref(0).tryAsHeader(); bytes29 _oldEnd = _oldPeriodEndHeader.ref(0).tryAsHeader(); bytes29 _headersView = _headers.ref(0).tryAsHeaderArray(); require( _oldStart.notNull() && _oldEnd.notNull() && _headersView.notNull(), "Bad args. Check header and array byte lengths." ); return _addHeadersWithRetarget(_oldStart, _oldEnd, _headersView); } /// @notice Gives a starting point for the relay /// @dev We don't check this AT ALL really. Don't use relays with bad genesis /// @param _ancestor The digest of the most recent common ancestor /// @param _currentBest The 80-byte header referenced by bestKnownDigest /// @param _newBest The 80-byte header to mark as the new best /// @param _limit Limit the amount of traversal of the chain /// @return True if successfully updates bestKnownDigest, error otherwise function markNewHeaviest( bytes32 _ancestor, bytes calldata _currentBest, bytes calldata _newBest, uint256 _limit ) external returns (bool) { bytes29 _new = _newBest.ref(0).tryAsHeader(); bytes29 _current = _currentBest.ref(0).tryAsHeader(); require( _new.notNull() && _current.notNull(), "Bad args. Check header and array byte lengths." ); return _markNewHeaviest(_ancestor, _current, _new, _limit); } /// @notice Adds headers to storage after validating /// @dev We check integrity and consistency of the header chain /// @param _anchor The header immediately preceeding the new chain /// @param _headers A tightly-packed list of new 80-byte Bitcoin headers to record /// @param _internal True if called internally from addHeadersWithRetarget, false otherwise /// @return True if successfully written, error otherwise function _addHeaders(bytes29 _anchor, bytes29 _headers, bool _internal) internal returns (bool) { /// Extract basic info bytes32 _previousDigest = _anchor.hash256(); uint256 _anchorHeight = _findHeight(_previousDigest); /* NB: errors if unknown */ uint256 _target = _headers.indexHeaderArray(0).target(); require( _internal || _anchor.target() == _target, "Unexpected retarget on external call" ); /* NB: 1. check that the header has sufficient work 2. check that headers are in a coherent chain (no retargets, hash links good) 3. Store the block connection 4. Store the height */ uint256 _height; bytes32 _currentDigest; for (uint256 i = 0; i < _headers.len() / 80; i += 1) { bytes29 _header = _headers.indexHeaderArray(i); _height = _anchorHeight.add(i + 1); _currentDigest = _header.hash256(); /* NB: if the block is already authenticated, we don't need to a work check Or write anything to state. This saves gas */ if (previousBlock[_currentDigest] == bytes32(0)) { require( TypedMemView.reverseUint256(uint256(_currentDigest)) <= _target, "Header work is insufficient" ); previousBlock[_currentDigest] = _previousDigest; if (_height % HEIGHT_INTERVAL == 0) { /* NB: We store the height only every 4th header to save gas */ blockHeight[_currentDigest] = _height; } } /* NB: we do still need to make chain level checks tho */ require(_header.target() == _target, "Target changed unexpectedly"); require(_header.checkParent(_previousDigest), "Headers do not form a consistent chain"); _previousDigest = _currentDigest; } emit Extension( _anchor.hash256(), _currentDigest); return true; } /// @notice Adds headers to storage, performs additional validation of retarget /// @dev Checks the retarget, the heights, and the linkage /// @param _oldStart The first header in the difficulty period being closed /// @param _oldEnd The last header in the difficulty period being closed /// @param _headers A tightly-packed list of 80-byte Bitcoin headers /// @return True if successfully written, error otherwise function _addHeadersWithRetarget( bytes29 _oldStart, bytes29 _oldEnd, bytes29 _headers ) internal returns (bool) { /* NB: requires that both blocks are known */ uint256 _startHeight = _findHeight(_oldStart.hash256()); uint256 _endHeight = _findHeight(_oldEnd.hash256()); /* NB: retargets should happen at 2016 block intervals */ require( _endHeight % 2016 == 2015, "Must provide the last header of the closing difficulty period"); require( _endHeight == _startHeight.add(2015), "Must provide exactly 1 difficulty period"); require( _oldStart.diff() == _oldEnd.diff(), "Period header difficulties do not match"); /* NB: This comparison looks weird because header nBits encoding truncates targets */ bytes29 _newStart = _headers.indexHeaderArray(0); uint256 _actualTarget = _newStart.target(); uint256 _expectedTarget = ViewBTC.retargetAlgorithm( _oldStart.target(), _oldStart.time(), _oldEnd.time() ); require( (_actualTarget & _expectedTarget) == _actualTarget, "Invalid retarget provided"); // If the current known prevEpochDiff doesn't match, and this old period is near the chaintip/ // update the stored prevEpochDiff // Don't update if this is a deep past epoch uint256 _oldDiff = _oldStart.diff(); if (prevEpochDiff != _oldDiff && _endHeight > _findHeight(bestKnownDigest).sub(2016)) { prevEpochDiff = _oldDiff; } // Pass all but the first through to be added return _addHeaders(_oldEnd, _headers, true); } /// @notice Finds the height of a header by its digest /// @dev Will fail if the header is unknown /// @param _digest The header digest to search for /// @return The height of the header function _findHeight(bytes32 _digest) internal view returns (uint256) { uint256 _height = 0; bytes32 _current = _digest; for (uint256 i = 0; i < HEIGHT_INTERVAL + 1; i = i.add(1)) { _height = blockHeight[_current]; if (_height == 0) { _current = previousBlock[_current]; } else { return _height.add(i); } } revert("Unknown block"); } /// @notice Finds an ancestor for a block by its digest /// @dev Will fail if the header is unknown /// @param _digest The header digest to search for /// @return The height of the header, or error if unknown function _findAncestor(bytes32 _digest, uint256 _offset) internal view returns (bytes32) { bytes32 _current = _digest; for (uint256 i = 0; i < _offset; i = i.add(1)) { _current = previousBlock[_current]; } require(_current != bytes32(0), "Unknown ancestor"); return _current; } /// @notice Checks if a digest is an ancestor of the current one /// @dev Limit the amount of lookups (and thus gas usage) with _limit /// @param _ancestor The prospective ancestor /// @param _descendant The descendant to check /// @param _limit The maximum number of blocks to check /// @return true if ancestor is at most limit blocks lower than descendant, otherwise false function _isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) internal view returns (bool) { bytes32 _current = _descendant; /* NB: 200 gas/read, so gas is capped at ~200 * limit */ for (uint256 i = 0; i < _limit; i = i.add(1)) { if (_current == _ancestor) { return true; } _current = previousBlock[_current]; } return false; } /// @notice Marks the new best-known chain tip /// @param _ancestor The digest of the most recent common ancestor /// @param _current The 80-byte header referenced by bestKnownDigest /// @param _new The 80-byte header to mark as the new best /// @param _limit Limit the amount of traversal of the chain /// @return True if successfully updates bestKnownDigest, error otherwise function _markNewHeaviest( bytes32 _ancestor, bytes29 _current, // Header bytes29 _new, // Header uint256 _limit ) internal returns (bool) { require(_limit <= 2016, "Requested limit is greater than 1 difficulty period"); bytes32 _newBestDigest = _new.hash256(); bytes32 _currentBestDigest = _current.hash256(); require(_currentBestDigest == bestKnownDigest, "Passed in best is not best known"); require( previousBlock[_newBestDigest] != bytes32(0), "New best is unknown"); require( _isMostRecentAncestor(_ancestor, bestKnownDigest, _newBestDigest, _limit), "Ancestor must be heaviest common ancestor"); require( _heaviestFromAncestor(_ancestor, _current, _new) == _newBestDigest, "New best hash does not have more work than previous"); bestKnownDigest = _newBestDigest; lastReorgCommonAncestor = _ancestor; uint256 _newDiff = _new.diff(); if (_newDiff != currentEpochDiff) { currentEpochDiff = _newDiff; } emit NewTip( _currentBestDigest, _newBestDigest, _ancestor); return true; } /// @notice Checks if a digest is an ancestor of the current one /// @dev Limit the amount of lookups (and thus gas usage) with _limit /// @param _ancestor The prospective shared ancestor /// @param _left A chain tip /// @param _right A chain tip /// @param _limit The maximum number of blocks to check /// @return true if it is the most recent common ancestor within _limit, false otherwise function _isMostRecentAncestor( bytes32 _ancestor, bytes32 _left, bytes32 _right, uint256 _limit ) internal view returns (bool) { /* NB: sure why not */ if (_ancestor == _left && _ancestor == _right) { return true; } bytes32 _leftCurrent = _left; bytes32 _rightCurrent = _right; bytes32 _leftPrev = _left; bytes32 _rightPrev = _right; for(uint256 i = 0; i < _limit; i = i.add(1)) { if (_leftPrev != _ancestor) { _leftCurrent = _leftPrev; // cheap _leftPrev = previousBlock[_leftPrev]; // expensive } if (_rightPrev != _ancestor) { _rightCurrent = _rightPrev; // cheap _rightPrev = previousBlock[_rightPrev]; // expensive } } if (_leftCurrent == _rightCurrent) {return false;} /* NB: If the same, they're a nearer ancestor */ if (_leftPrev != _rightPrev) {return false;} /* NB: Both must be ancestor */ return true; } /// @notice Decides which header is heaviest from the ancestor /// @dev Does not support reorgs above 2017 blocks (: /// @param _ancestor The prospective shared ancestor /// @param _left A chain tip /// @param _right A chain tip /// @return true if it is the most recent common ancestor within _limit, false otherwise function _heaviestFromAncestor( bytes32 _ancestor, bytes29 _left, bytes29 _right ) internal view returns (bytes32) { uint256 _ancestorHeight = _findHeight(_ancestor); uint256 _leftHeight = _findHeight(_left.hash256()); uint256 _rightHeight = _findHeight(_right.hash256()); require( _leftHeight >= _ancestorHeight && _rightHeight >= _ancestorHeight, "A descendant height is below the ancestor height"); /* NB: we can shortcut if one block is in a new difficulty window and the other isn't */ uint256 _nextPeriodStartHeight = _ancestorHeight.add(2016).sub(_ancestorHeight % 2016); bool _leftInPeriod = _leftHeight < _nextPeriodStartHeight; bool _rightInPeriod = _rightHeight < _nextPeriodStartHeight; /* NB: 1. Left is in a new window, right is in the old window. Left is heavier 2. Right is in a new window, left is in the old window. Right is heavier 3. Both are in the same window, choose the higher one 4. They're in different new windows. Choose the heavier one */ if (!_leftInPeriod && _rightInPeriod) {return _left.hash256();} if (_leftInPeriod && !_rightInPeriod) {return _right.hash256();} if (_leftInPeriod && _rightInPeriod) { return _leftHeight >= _rightHeight ? _left.hash256() : _right.hash256(); } else { // if (!_leftInPeriod && !_rightInPeriod) { if (((_leftHeight % 2016).mul(_left.diff())) < (_rightHeight % 2016).mul(_right.diff())) { return _right.hash256(); } else { return _left.hash256(); } } } } // For unittests contract TestRelay is Relay { /// @notice Gives a starting point for the relay /// @dev We don't check this AT ALL really. Don't use relays with bad genesis /// @param _genesisHeader The starting header /// @param _height The starting height /// @param _periodStart The hash of the first header in the genesis epoch constructor(bytes memory _genesisHeader, uint256 _height, bytes32 _periodStart) Relay(_genesisHeader, _height, _periodStart) public {} function heaviestFromAncestor( bytes32 _ancestor, bytes calldata _left, bytes calldata _right ) external view returns (bytes32) { return _heaviestFromAncestor( _ancestor, _left.ref(0).tryAsHeader(), _right.ref(0).tryAsHeader() ); } function isMostRecentAncestor( bytes32 _ancestor, bytes32 _left, bytes32 _right, uint256 _limit ) external view returns (bool) { return _isMostRecentAncestor(_ancestor, _left, _right, _limit); } }
Getter for relayGenesis This is an initialization parameter return The hash of the first block of the relay
function getRelayGenesis() public view returns (bytes32) { return relayGenesis; }
6,484,860
./partial_match/1/0x1b6a205358e9378Bf9d6cb75F4D3cCcab38cA796/sources/src/ZeroLiquid.sol
Gets the amount of `yieldToken` that `amount` of its underlying token is exchangeable for. yieldToken The address of the yield token. amount The amount of underlying tokens. return The amount of yield tokens.
function convertUnderlyingTokensToYield(address yieldToken, uint256 amount) public view returns (uint256) { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter); return amount * 10 ** yieldTokenParams.decimals / adapter.price(); }
15,484,984
/** *Submitted for verification at Etherscan.io on 2021-05-17 */ // File: contracts/interface/ICoFiXV2VaultForTrader.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface ICoFiXV2VaultForTrader { event RouterAllowed(address router); event RouterDisallowed(address router); event ClearPendingRewardOfCNode(uint256 pendingAmount); event ClearPendingRewardOfLP(uint256 pendingAmount); function setGovernance(address gov) external; function setCofiRate(uint256 cofiRate) external; function allowRouter(address router) external; function disallowRouter(address router) external; function calcMiningRate(address pair, uint256 neededETHAmount) external view returns (uint256); function calcNeededETHAmountForAdjustment(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256); function actualMiningAmount(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 amount, uint256 totalAccruedAmount, uint256 neededETHAmount); function distributeReward(address pair, uint256 ethAmount, uint256 erc20Amount, address rewardTo) external; function clearPendingRewardOfCNode() external; function clearPendingRewardOfLP(address pair) external; function getPendingRewardOfCNode() external view returns (uint256); function getPendingRewardOfLP(address pair) external view returns (uint256); } // File: contracts/interface/ICoFiXV2Factory.sol pragma solidity 0.6.12; interface ICoFiXV2Factory { // All pairs: {ETH <-> ERC20 Token} event PairCreated(address indexed token, address pair, uint256); event NewGovernance(address _new); event NewController(address _new); event NewFeeReceiver(address _new); event NewFeeVaultForLP(address token, address feeVault); event NewVaultForLP(address _new); event NewVaultForTrader(address _new); event NewVaultForCNode(address _new); event NewDAO(address _new); /// @dev Create a new token pair for trading /// @param token the address of token to trade /// @param initToken0Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @param initToken1Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @return pair the address of new token pair function createPair( address token, uint256 initToken0Amount, uint256 initToken1Amount ) external returns (address pair); function getPair(address token) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function getTradeMiningStatus(address token) external view returns (bool status); function setTradeMiningStatus(address token, bool status) external; function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs function setFeeVaultForLP(address token, address feeVault) external; function setGovernance(address _new) external; function setController(address _new) external; function setFeeReceiver(address _new) external; function setVaultForLP(address _new) external; function setVaultForTrader(address _new) external; function setVaultForCNode(address _new) external; function setDAO(address _new) external; function getController() external view returns (address controller); function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders function getVaultForLP() external view returns (address vaultForLP); function getVaultForTrader() external view returns (address vaultForTrader); function getVaultForCNode() external view returns (address vaultForCNode); function getDAO() external view returns (address dao); } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol 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; } } // File: contracts/interface/ICoFiXStakingRewards.sol pragma solidity 0.6.12; interface ICoFiXStakingRewards { // Views /// @dev The rewards vault contract address set in factory contract /// @return Returns the vault address function rewardsVault() external view returns (address); /// @dev The lastBlock reward applicable /// @return Returns the latest block.number on-chain function lastBlockRewardApplicable() external view returns (uint256); /// @dev Reward amount represents by per staking token function rewardPerToken() external view returns (uint256); /// @dev How many reward tokens a user has earned but not claimed at present /// @param account The target account /// @return The amount of reward tokens a user earned function earned(address account) external view returns (uint256); /// @dev How many reward tokens accrued recently /// @return The amount of reward tokens accrued recently function accrued() external view returns (uint256); /// @dev Get the latest reward rate of this mining pool (tokens amount per block) /// @return The latest reward rate function rewardRate() external view returns (uint256); /// @dev How many stakingToken (XToken) deposited into to this reward pool (mining pool) /// @return The total amount of XTokens deposited in this mining pool function totalSupply() external view returns (uint256); /// @dev How many stakingToken (XToken) deposited by the target account /// @param account The target account /// @return The total amount of XToken deposited in this mining pool function balanceOf(address account) external view returns (uint256); /// @dev Get the address of token for staking in this mining pool /// @return The staking token address function stakingToken() external view returns (address); /// @dev Get the address of token for rewards in this mining pool /// @return The rewards token address function rewardsToken() external view returns (address); // Mutative /// @dev Stake/Deposit into the reward pool (mining pool) /// @param amount The target amount function stake(uint256 amount) external; /// @dev Stake/Deposit into the reward pool (mining pool) for other account /// @param other The target account /// @param amount The target amount function stakeForOther(address other, uint256 amount) external; /// @dev Withdraw from the reward pool (mining pool), get the original tokens back /// @param amount The target amount function withdraw(uint256 amount) external; /// @dev Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external; /// @dev Claim the reward the user earned function getReward() external; function getRewardAndStake() external; /// @dev User exit the reward pool, it's actually withdraw and getReward function exit() external; /// @dev Add reward to the mining pool function addReward(uint256 amount) external; // Events event RewardAdded(address sender, uint256 reward); event Staked(address indexed user, uint256 amount); event StakedForOther(address indexed user, address indexed other, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } // File: contracts/interface/ICoFiXVaultForLP.sol pragma solidity 0.6.12; interface ICoFiXVaultForLP { enum POOL_STATE {INVALID, ENABLED, DISABLED} event NewPoolAdded(address pool, uint256 index); event PoolEnabled(address pool); event PoolDisabled(address pool); function setGovernance(address _new) external; function setInitCoFiRate(uint256 _new) external; function setDecayPeriod(uint256 _new) external; function setDecayRate(uint256 _new) external; function addPool(address pool) external; function enablePool(address pool) external; function disablePool(address pool) external; function setPoolWeight(address pool, uint256 weight) external; function batchSetPoolWeight(address[] memory pools, uint256[] memory weights) external; function distributeReward(address to, uint256 amount) external; function getPendingRewardOfLP(address pair) external view returns (uint256); function currentPeriod() external view returns (uint256); function currentCoFiRate() external view returns (uint256); function currentPoolRate(address pool) external view returns (uint256 poolRate); function currentPoolRateByPair(address pair) external view returns (uint256 poolRate); /// @dev Get the award staking pool address of pair (XToken) /// @param pair The address of XToken(pair) contract /// @return pool The pool address function stakingPoolForPair(address pair) external view returns (address pool); function getPoolInfo(address pool) external view returns (POOL_STATE state, uint256 weight); function getPoolInfoByPair(address pair) external view returns (POOL_STATE state, uint256 weight); function getEnabledPoolCnt() external view returns (uint256); function getCoFiStakingPool() external view returns (address pool); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: contracts/interface/ICoFiToken.sol pragma solidity 0.6.12; interface ICoFiToken is IERC20 { /// @dev An event thats emitted when a new governance account is set /// @param _new The new governance address event NewGovernance(address _new); /// @dev An event thats emitted when a new minter account is added /// @param _minter The new minter address added event MinterAdded(address _minter); /// @dev An event thats emitted when a minter account is removed /// @param _minter The minter address removed event MinterRemoved(address _minter); /// @dev Set governance address of CoFi token. Only governance has the right to execute. /// @param _new The new governance address function setGovernance(address _new) external; /// @dev Add a new minter account to CoFi token, who can mint tokens. Only governance has the right to execute. /// @param _minter The new minter address function addMinter(address _minter) external; /// @dev Remove a minter account from CoFi token, who can mint tokens. Only governance has the right to execute. /// @param _minter The minter address removed function removeMinter(address _minter) external; /// @dev mint is used to distribute CoFi token to users, minters are CoFi mining pools /// @param _to The receiver address /// @param _amount The amount of tokens minted function mint(address _to, uint256 _amount) external; } // File: contracts/lib/ABDKMath64x64.sol /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.6.12; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * @dev Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** * @dev Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1)); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << 127 - msb; for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= 63 - (x >> 64); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } // 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: contracts/CoFiXV2VaultForLP.sol pragma solidity 0.6.12; // Reward Pool Controller for Liquidity Provider contract CoFiXV2VaultForLP is ICoFiXVaultForLP, ReentrancyGuard { using SafeMath for uint256; // uint256 public constant RATE_BASE = 1e18; uint256 public constant WEIGHT_BASE = 100; address public immutable cofiToken; address public immutable factory; uint256 public genesisBlock; // managed by governance address public governance; uint256 public initCoFiRate = 1.8*1e18; // yield per block 5*1e18 - 5*1e18/10 uint256 public decayPeriod = 2400000; // yield decays for every 2,400,000 blocks uint256 public decayRate = 80; address[] public allPools; // add every pool addr to record, make it easier to track uint256 public enabledCnt; struct PoolInfo { POOL_STATE state; uint256 weight; } mapping (address => PoolInfo) public poolInfo; // pool -> poolInfo mapping (address => address) public pairToStakingPool; // pair -> staking pool modifier onlyGovernance() { require(msg.sender == governance, "CVaultForLP: !governance"); _; } constructor(address cofi, address _factory) public { cofiToken = cofi; factory = _factory; governance = msg.sender; genesisBlock = block.number; // set v1 genesisBlock to genesisBlock later } // this is for mainnet function setGenesisBlock() external { genesisBlock = 11040688; // follow v1 } /* setters for protocol governance */ function setGovernance(address _new) external override onlyGovernance { governance = _new; } function setInitCoFiRate(uint256 _new) external override onlyGovernance { initCoFiRate = _new; } function setDecayPeriod(uint256 _new) external override onlyGovernance { require(_new != 0, "CVaultForLP: wrong period setting"); decayPeriod = _new; } function setDecayRate(uint256 _new) external override onlyGovernance { decayRate = _new; } function addPool(address pool) external override onlyGovernance { require(poolInfo[pool].state == POOL_STATE.INVALID, "CVaultForLP: pool added"); // INVALID -> ENABLED require(pool != address(0), "CVaultForTrader: invalid pool"); poolInfo[pool].state = POOL_STATE.ENABLED; // default rate is zero, to ensure safety enabledCnt = enabledCnt.add(1); // set pair to reward pool map address pair = ICoFiXStakingRewards(pool).stakingToken(); require(pairToStakingPool[pair] == address(0), "CVaultForLP: pair added"); pairToStakingPool[pair] = pool; // staking token is CoFiXPair (XToken) allPools.push(pool); // add once never delete, using for track emit NewPoolAdded(pool, allPools.length); } function enablePool(address pool) external override onlyGovernance { require(poolInfo[pool].state == POOL_STATE.DISABLED, "CVaultForLP: pool not disabled"); // DISABLED -> ENABLED require(pool != address(0), "CVaultForTrader: invalid pool"); poolInfo[pool].state = POOL_STATE.ENABLED; enabledCnt = enabledCnt.add(1); // set pair to reward pool map address pair = ICoFiXStakingRewards(pool).stakingToken(); require(pairToStakingPool[pair] == address(0), "CVaultForLP: pair added"); pairToStakingPool[pair] = pool; // staking token is CoFiXPair (XToken) emit PoolEnabled(pool); } function disablePool(address pool) external override onlyGovernance { require(poolInfo[pool].state == POOL_STATE.ENABLED, "CVaultForLP: pool not enabled"); // ENABLED -> DISABLED require(pool != address(0), "CVaultForTrader: invalid pool"); poolInfo[pool].state = POOL_STATE.DISABLED; poolInfo[pool].weight = 0; // set pool weight to zero; enabledCnt = enabledCnt.sub(1); address pair = ICoFiXStakingRewards(pool).stakingToken(); pairToStakingPool[pair] = address(0); // set pair mapping to zero emit PoolDisabled(pool); } function setPoolWeight(address pool, uint256 weight) public override onlyGovernance { require(weight <= WEIGHT_BASE, "CVaultForLP: invalid weight"); require(pool != address(0), "CVaultForTrader: invalid pool"); require(poolInfo[pool].state == POOL_STATE.ENABLED, "CVaultForLP: pool not enabled"); // only set weight if pool is enabled poolInfo[pool].weight = weight; } function batchSetPoolWeight(address[] memory pools, uint256[] memory weights) external override onlyGovernance { uint256 cnt = pools.length; require(cnt == weights.length, "CVaultForLP: mismatch len"); for (uint256 i = 0; i < cnt; i++) { require(pools[i] != address(0), "CVaultForTrader: invalid pool"); require(weights[i] <= WEIGHT_BASE, "CVaultForLP: invalid weight"); require(poolInfo[pools[i]].state == POOL_STATE.ENABLED, "CVaultForLP: pool not enabled"); // only set weight if pool is enabled poolInfo[pools[i]].weight = weights[i]; } // governance should ensure total weights equal to WEIGHT_BASE } function getPendingRewardOfLP(address pair) external override view returns (uint256) { POOL_STATE poolState = poolInfo[msg.sender].state; if (poolState == POOL_STATE.INVALID || poolState == POOL_STATE.DISABLED) { return 0; // if pool is disabled, it can't mint by call distributeReward, so don't count on any reward for it } // if poolState is enabled, then go on address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader(); if (vaultForTrader == address(0)) { return 0; // vaultForTrader is not set yet } uint256 pending = ICoFiXV2VaultForTrader(vaultForTrader).getPendingRewardOfLP(pair); return pending; } function distributeReward(address to, uint256 amount) external override nonReentrant { POOL_STATE poolState = poolInfo[msg.sender].state; require(poolState != POOL_STATE.INVALID, "CVaultForLP: only pool valid"); if (poolState == POOL_STATE.DISABLED) { return; // make sure tx would revert because user still want to withdraw and getReward } require(to != address(0), "CVaultForTrader: invalid to"); // if poolState is enabled, then go on. caution: be careful when adding new pool address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader(); if (vaultForTrader != address(0)) { // if equal, means vaultForTrader is not set yet address pair = ICoFiXStakingRewards(msg.sender).stakingToken(); require(pair != address(0), "CVaultForTrader: invalid pair"); uint256 pending = ICoFiXV2VaultForTrader(vaultForTrader).getPendingRewardOfLP(pair); if (pending > 0) { ICoFiXV2VaultForTrader(vaultForTrader).clearPendingRewardOfLP(pair); } } ICoFiToken(cofiToken).mint(to, amount); // allows zero } function currentPeriod() public override view returns (uint256) { return (block.number).sub(genesisBlock).div(decayPeriod); } function currentCoFiRate() public override view returns (uint256) { uint256 periodIdx = currentPeriod(); if (periodIdx > 4) { periodIdx = 4; // after 5 years, the rate keep constant } uint256 cofiRate = initCoFiRate; uint256 _decayRate = decayRate; for (uint256 i = 0; i < periodIdx; i++) { cofiRate = cofiRate.mul(_decayRate).div(100); } return cofiRate; } function currentPoolRate(address pool) public override view returns (uint256 poolRate) { uint256 cnt = enabledCnt; if (cnt == 0) { return 0; } uint256 cofiRate = currentCoFiRate(); uint256 weight = poolInfo[pool].weight; poolRate = cofiRate.mul(weight).div(WEIGHT_BASE); return poolRate; } function currentPoolRateByPair(address pair) external override view returns (uint256 poolRate) { address pool = pairToStakingPool[pair]; poolRate = currentPoolRate(pool); return poolRate; } function stakingPoolForPair(address pair) external override view returns (address pool) { return pairToStakingPool[pair]; } function getPoolInfo(address pool) public override view returns (POOL_STATE state, uint256 weight) { state = poolInfo[pool].state; weight = poolInfo[pool].weight; return (state, weight); } function getPoolInfoByPair(address pair) external override view returns (POOL_STATE state, uint256 weight) { address pool = pairToStakingPool[pair]; return getPoolInfo(pool); } // pools in enabled state function getEnabledPoolCnt() external override view returns (uint256) { return enabledCnt; } function getCoFiStakingPool() external override view returns (address pool) { return ICoFiXV2Factory(factory).getFeeReceiver(); } }
Views Mutative Events
interface ICoFiXStakingRewards { function rewardsVault() external view returns (address); function lastBlockRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function accrued() external view returns (uint256); function rewardRate() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function stakingToken() external view returns (address); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeForOther(address other, uint256 amount) external; function withdraw(uint256 amount) external; function emergencyWithdraw() external; function getReward() external; function getRewardAndStake() external; function exit() external; function addReward(uint256 amount) external; event RewardAdded(address sender, uint256 reward); event Staked(address indexed user, uint256 amount); event StakedForOther(address indexed user, address indexed other, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); }
2,235,705
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; import {PermissionAdmin, PermissionOperators} from '@kyber.network/utils-sc/contracts/PermissionOperators.sol'; import {Utils} from '@kyber.network/utils-sc/contracts/Utils.sol'; import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol'; import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {EnumerableSet} from '@openzeppelin/contracts/utils/EnumerableSet.sol'; import {ILiquidationCallback} from '../interfaces/liquidation/ILiquidationCallback.sol'; import {ILiquidationStrategyBase, ILiquidationPriceOracleBase} from '../interfaces/liquidation/ILiquidationStrategyBase.sol'; import {IPool} from '../interfaces/liquidation/IPool.sol'; contract LiquidationStrategyBase is ILiquidationStrategyBase, PermissionOperators, Utils, ReentrancyGuard { using SafeERC20 for IERC20Ext; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; // after repeatedPeriod since startTime, there will be duration (in seconds) // for liquidators to liquidate tokens in the treasury pool // for example: from deployed time, every 2 weeks liquidation is enabled for 4 days struct LiquidationSchedule { uint128 startTime; uint64 repeatedPeriod; uint64 duration; } // list of tokens that can be liquidate to EnumerableSet.AddressSet private _whitelistedLiquidators; EnumerableSet.AddressSet private _whitelistedPriceOracles; LiquidationSchedule private _liquidationSchedule; IPool private _treasuryPool; address payable private _rewardPool; bool public paused = false; event Pause(address caller, bool isPaused); event TreasuryPoolSet(address indexed treasuryPool); event RewardPoolSet(address indexed rewardPool); event LiquidationScheduleUpdated(uint128 startTime, uint64 repeatedPeriod, uint64 duration); event WhitelistedLiquidatorUpdated(address indexed liquidator, bool indexed isAdd); event WhitelistedPriceOracleUpdated(address indexed oracle, bool indexed isAdd); constructor( address admin, address treasuryPoolAddress, address payable rewardPoolAddress, uint128 startTime, uint64 repeatedPeriod, uint64 duration, address[] memory whitelistedLiquidators, address[] memory whitelistedOracles ) PermissionAdmin(admin) { _setTreasuryPool(treasuryPoolAddress); _setRewardPool(rewardPoolAddress); _setLiquidationSchedule(startTime, repeatedPeriod, duration); _updateWhitelistedLiquidators(whitelistedLiquidators, true); _updateWhitelistedPriceOracles(whitelistedOracles, true); } receive() external payable {} /** * @dev Update liquidation schedule * to disable the liquidation: set repeatedPeriod to 0 * to always enable the liquidation: set duration >= repeatedPeriod * @param startTime: start time of the first liquidation schedule * @param repeatedPeriod period in seconds that the schedule will be repeated * @param duration duration of each schedule */ function updateLiquidationSchedule( uint128 startTime, uint64 repeatedPeriod, uint64 duration ) external onlyAdmin { _setLiquidationSchedule(startTime, repeatedPeriod, duration); } function updateTreasuryPool(address pool) external override onlyAdmin { _setTreasuryPool(pool); } function updateRewardPool(address payable pool) external override onlyAdmin { _setRewardPool(pool); } function updateWhitelistedLiquidators(address[] calldata liquidators, bool isAdd) external override onlyAdmin { _updateWhitelistedLiquidators(liquidators, isAdd); } function updateWhitelistedOracles(address[] calldata oracles, bool isAdd) external override onlyAdmin { _updateWhitelistedPriceOracles(oracles, isAdd); } /** * @dev Allow operator to pause the liquidation in case of emergency * It's faster and more flexible than waiting for a proposal */ function setPause(bool isPause) external onlyOperator { paused = isPause; emit Pause(msg.sender, isPause); } /** @dev Liquidate list of tokens to a single dest token, * source token must not be a whitelisted token, dest must be a whitelisted token * in case whitelisted liquidator is enabled, sender must be whitelisted * funds need to be transferred back to the LiquidationStrategy before transferring to RewardPool * @param oracle the whitelisted oracle that will be used to get conversion data * @param sources list of source tokens to liquidate * @param amounts list of amounts corresponding to each source token * @param recipient receiver of source tokens * @param dest dest token to liquidate to * @param oracleHint hint for getting data from oracle * @param txData data to callback to recipient */ function liquidate( ILiquidationPriceOracleBase oracle, IERC20Ext[] calldata sources, uint256[] calldata amounts, address payable recipient, IERC20Ext dest, bytes calldata oracleHint, bytes calldata txData ) external virtual override nonReentrant returns (uint256 destAmount) { require(!paused, 'liquidate: only when not paused'); require(isWhitelistedLiquidator(msg.sender), 'liquidate: only whitelisted liquidator'); require(isWhitelistedOracle(address(oracle)), 'liquidate: only whitelisted oracle'); require(isLiquidationEnabled(), 'liquidate: only when liquidation enabled'); // request return data from oracle uint256 minReturn = oracle.getExpectedReturn( msg.sender, sources, amounts, dest, oracleHint ); require(minReturn > 0, 'liquidate: minReturn == 0'); uint256 destBalance = getBalance(dest, address(this)); // request funds from treasury pool to recipient _treasuryPool.withdrawFunds(sources, amounts, recipient); // callback to recipient to transfer dest amount to reward // internal function to prevent stack too deep _liquidationCallback(sources, amounts, recipient, dest, minReturn, txData); destAmount = getBalance(dest, address(this)).sub(destBalance); require(destAmount >= minReturn, 'liquidate: low return amount'); _transferToken(dest, rewardPool(), destAmount); } // Whitelisted liquidators function getWhitelistedLiquidatorsLength() external override view returns (uint256) { return _whitelistedLiquidators.length(); } function getWhitelistedLiquidatorAt(uint256 index) external override view returns (address) { return _whitelistedLiquidators.at(index); } function getAllWhitelistedLiquidators() external view override returns (address[] memory liquidators) { uint256 length = _whitelistedLiquidators.length(); liquidators = new address[](length); for(uint256 i = 0; i < length; i++) { liquidators[i] = _whitelistedLiquidators.at(i); } } // Whitelisted Price Orcales function getWhitelistedPriceOraclesLength() external override view returns (uint256) { return _whitelistedPriceOracles.length(); } function getWhitelistedPriceOracleAt(uint256 index) external override view returns (address) { return _whitelistedPriceOracles.at(index); } function getAllWhitelistedPriceOracles() external view override returns (address[] memory oracles) { uint256 length = _whitelistedPriceOracles.length(); oracles = new address[](length); for(uint256 i = 0; i < length; i++) { oracles[i] = _whitelistedPriceOracles.at(i); } } function getLiquidationSchedule() external override view returns( uint128 startTime, uint64 repeatedPeriod, uint64 duration ) { (startTime, repeatedPeriod, duration) = ( _liquidationSchedule.startTime, _liquidationSchedule.repeatedPeriod, _liquidationSchedule.duration ); } function treasuryPool() public override view returns (address) { return address(_treasuryPool); } function rewardPool() public override view returns (address payable) { return _rewardPool; } function isWhitelistedLiquidator(address liquidator) public view override returns (bool) { return _whitelistedLiquidators.contains(liquidator); } function isWhitelistedOracle(address oracle) public view override returns (bool) { return _whitelistedPriceOracles.contains(oracle); } function isLiquidationEnabled() public view override returns (bool) { LiquidationSchedule memory schedule = _liquidationSchedule; if (schedule.duration == 0) return false; if (block.timestamp < uint256(schedule.startTime)) return false; uint256 timeInPeriod = (block.timestamp - uint256(schedule.startTime)) % uint256(schedule.repeatedPeriod); return timeInPeriod < schedule.duration; } function _setTreasuryPool(address _pool) internal { require(_pool != address(0), 'invalid treasury pool'); _treasuryPool = IPool(_pool); emit TreasuryPoolSet(_pool); } function _setRewardPool(address payable _pool) internal { require(_pool != address(0), 'invalid reward pool'); _rewardPool = _pool; emit RewardPoolSet(_pool); } function _updateWhitelistedLiquidators(address[] memory _liquidators, bool _isAdd) internal { for(uint256 i = 0; i < _liquidators.length; i++) { if (_isAdd) { _whitelistedLiquidators.add(_liquidators[i]); } else { _whitelistedLiquidators.remove(_liquidators[i]); } emit WhitelistedLiquidatorUpdated(_liquidators[i], _isAdd); } } function _updateWhitelistedPriceOracles(address[] memory _oracles, bool _isAdd) internal { for(uint256 i = 0; i < _oracles.length; i++) { if (_isAdd) { _whitelistedPriceOracles.add(_oracles[i]); } else { _whitelistedPriceOracles.remove(_oracles[i]); } emit WhitelistedPriceOracleUpdated(_oracles[i], _isAdd); } } function _setLiquidationSchedule( uint128 _startTime, uint64 _repeatedPeriod, uint64 _duration ) internal { require(_repeatedPeriod > 0, 'repeated period is 0'); _liquidationSchedule = LiquidationSchedule({ startTime: _startTime, repeatedPeriod: _repeatedPeriod, duration: _duration }); emit LiquidationScheduleUpdated(_startTime, _repeatedPeriod, _duration); } function _transferToken(IERC20Ext token, address payable recipient, uint256 amount) internal { if (token == ETH_TOKEN_ADDRESS) { (bool success, ) = recipient.call { value: amount }(''); require(success, 'transfer eth failed'); } else { token.safeTransfer(recipient, amount); } } function _liquidationCallback( IERC20Ext[] memory sources, uint256[] memory amounts, address payable recipient, IERC20Ext dest, uint256 minReturn, bytes calldata txData ) internal { ILiquidationCallback(recipient).liquidationCallback( msg.sender, sources, amounts, address(this), dest, minReturn, txData ); } }
Allow operator to pause the liquidation in case of emergency It's faster and more flexible than waiting for a proposal/
function setPause(bool isPause) external onlyOperator { paused = isPause; emit Pause(msg.sender, isPause); }
6,357,792